1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitAnd, visitOr, and visitXor functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/PatternMatch.h"
19 using namespace PatternMatch;
22 /// AddOne - Add one to a ConstantInt.
23 static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
26 /// SubOne - Subtract one from a ConstantInt.
27 static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
31 /// isFreeToInvert - Return true if the specified value is free to invert (apply
32 /// ~ to). This happens in cases where the ~ can be eliminated.
33 static inline bool isFreeToInvert(Value *V) {
35 if (BinaryOperator::isNot(V))
38 // Constants can be considered to be not'ed values.
39 if (isa<ConstantInt>(V))
42 // Compares can be inverted if they have a single use.
43 if (CmpInst *CI = dyn_cast<CmpInst>(V))
44 return CI->hasOneUse();
49 static inline Value *dyn_castNotVal(Value *V) {
50 // If this is not(not(x)) don't return that this is a not: we want the two
51 // not's to be folded first.
52 if (BinaryOperator::isNot(V)) {
53 Value *Operand = BinaryOperator::getNotArgument(V);
54 if (!isFreeToInvert(Operand))
58 // Constants can be considered to be not'ed values...
59 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
60 return ConstantInt::get(C->getType(), ~C->getValue());
65 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
66 /// are carefully arranged to allow folding of expressions such as:
68 /// (A < B) | (A > B) --> (A != B)
70 /// Note that this is only valid if the first and second predicates have the
71 /// same sign. Is illegal to do: (A u< B) | (A s> B)
73 /// Three bits are used to represent the condition, as follows:
78 /// <=> Value Definition
79 /// 000 0 Always false
88 static unsigned getICmpCode(const ICmpInst *ICI) {
89 switch (ICI->getPredicate()) {
91 case ICmpInst::ICMP_UGT: return 1; // 001
92 case ICmpInst::ICMP_SGT: return 1; // 001
93 case ICmpInst::ICMP_EQ: return 2; // 010
94 case ICmpInst::ICMP_UGE: return 3; // 011
95 case ICmpInst::ICMP_SGE: return 3; // 011
96 case ICmpInst::ICMP_ULT: return 4; // 100
97 case ICmpInst::ICMP_SLT: return 4; // 100
98 case ICmpInst::ICMP_NE: return 5; // 101
99 case ICmpInst::ICMP_ULE: return 6; // 110
100 case ICmpInst::ICMP_SLE: return 6; // 110
103 llvm_unreachable("Invalid ICmp predicate!");
108 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
109 /// predicate into a three bit mask. It also returns whether it is an ordered
110 /// predicate by reference.
111 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
114 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
115 case FCmpInst::FCMP_UNO: return 0; // 000
116 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
117 case FCmpInst::FCMP_UGT: return 1; // 001
118 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
119 case FCmpInst::FCMP_UEQ: return 2; // 010
120 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
121 case FCmpInst::FCMP_UGE: return 3; // 011
122 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
123 case FCmpInst::FCMP_ULT: return 4; // 100
124 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
125 case FCmpInst::FCMP_UNE: return 5; // 101
126 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
127 case FCmpInst::FCMP_ULE: return 6; // 110
130 // Not expecting FCMP_FALSE and FCMP_TRUE;
131 llvm_unreachable("Unexpected FCmp predicate!");
136 /// getICmpValue - This is the complement of getICmpCode, which turns an
137 /// opcode and two operands into either a constant true or false, or a brand
138 /// new ICmp instruction. The sign is passed in to determine which kind
139 /// of predicate to use in the new icmp instruction.
140 static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
141 InstCombiner::BuilderTy *Builder) {
142 CmpInst::Predicate Pred;
144 default: assert(0 && "Illegal ICmp code!");
146 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
147 case 1: Pred = Sign ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
148 case 2: Pred = ICmpInst::ICMP_EQ; break;
149 case 3: Pred = Sign ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
150 case 4: Pred = Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
151 case 5: Pred = ICmpInst::ICMP_NE; break;
152 case 6: Pred = Sign ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
154 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
156 return Builder->CreateICmp(Pred, LHS, RHS);
159 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
160 /// opcode and two operands into either a FCmp instruction. isordered is passed
161 /// in to determine which kind of predicate to use in the new fcmp instruction.
162 static Value *getFCmpValue(bool isordered, unsigned code,
163 Value *LHS, Value *RHS,
164 InstCombiner::BuilderTy *Builder) {
165 CmpInst::Predicate Pred;
167 default: assert(0 && "Illegal FCmp code!");
168 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
169 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
170 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
171 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
172 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
173 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
174 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
176 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
177 Pred = FCmpInst::FCMP_ORD; break;
179 return Builder->CreateFCmp(Pred, LHS, RHS);
182 /// PredicatesFoldable - Return true if both predicates match sign or if at
183 /// least one of them is an equality comparison (which is signless).
184 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
185 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
186 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
187 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
190 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
191 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
192 // guaranteed to be a binary operator.
193 Instruction *InstCombiner::OptAndOp(Instruction *Op,
196 BinaryOperator &TheAnd) {
197 Value *X = Op->getOperand(0);
198 Constant *Together = 0;
200 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
202 switch (Op->getOpcode()) {
203 case Instruction::Xor:
204 if (Op->hasOneUse()) {
205 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
206 Value *And = Builder->CreateAnd(X, AndRHS);
208 return BinaryOperator::CreateXor(And, Together);
211 case Instruction::Or:
212 if (Op->hasOneUse()){
213 if (Together != OpRHS) {
214 // (X | C1) & C2 --> (X | (C1&C2)) & C2
215 Value *Or = Builder->CreateOr(X, Together);
217 return BinaryOperator::CreateAnd(Or, AndRHS);
220 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
221 if (TogetherCI && !TogetherCI->isZero()){
222 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
223 // NOTE: This reduces the number of bits set in the & mask, which
224 // can expose opportunities for store narrowing.
225 Together = ConstantExpr::getXor(AndRHS, Together);
226 Value *And = Builder->CreateAnd(X, Together);
228 return BinaryOperator::CreateOr(And, OpRHS);
233 case Instruction::Add:
234 if (Op->hasOneUse()) {
235 // Adding a one to a single bit bit-field should be turned into an XOR
236 // of the bit. First thing to check is to see if this AND is with a
237 // single bit constant.
238 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
240 // If there is only one bit set.
241 if (AndRHSV.isPowerOf2()) {
242 // Ok, at this point, we know that we are masking the result of the
243 // ADD down to exactly one bit. If the constant we are adding has
244 // no bits set below this bit, then we can eliminate the ADD.
245 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
247 // Check to see if any bits below the one bit set in AndRHSV are set.
248 if ((AddRHS & (AndRHSV-1)) == 0) {
249 // If not, the only thing that can effect the output of the AND is
250 // the bit specified by AndRHSV. If that bit is set, the effect of
251 // the XOR is to toggle the bit. If it is clear, then the ADD has
253 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
254 TheAnd.setOperand(0, X);
257 // Pull the XOR out of the AND.
258 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
259 NewAnd->takeName(Op);
260 return BinaryOperator::CreateXor(NewAnd, AndRHS);
267 case Instruction::Shl: {
268 // We know that the AND will not produce any of the bits shifted in, so if
269 // the anded constant includes them, clear them now!
271 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
272 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
273 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
274 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
275 AndRHS->getValue() & ShlMask);
277 if (CI->getValue() == ShlMask) {
278 // Masking out bits that the shift already masks
279 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
280 } else if (CI != AndRHS) { // Reducing bits set in and.
281 TheAnd.setOperand(1, CI);
286 case Instruction::LShr: {
287 // We know that the AND will not produce any of the bits shifted in, so if
288 // the anded constant includes them, clear them now! This only applies to
289 // unsigned shifts, because a signed shr may bring in set bits!
291 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
292 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
293 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
294 ConstantInt *CI = ConstantInt::get(Op->getContext(),
295 AndRHS->getValue() & ShrMask);
297 if (CI->getValue() == ShrMask) {
298 // Masking out bits that the shift already masks.
299 return ReplaceInstUsesWith(TheAnd, Op);
300 } else if (CI != AndRHS) {
301 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
306 case Instruction::AShr:
308 // See if this is shifting in some sign extension, then masking it out
310 if (Op->hasOneUse()) {
311 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
312 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
313 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
314 Constant *C = ConstantInt::get(Op->getContext(),
315 AndRHS->getValue() & ShrMask);
316 if (C == AndRHS) { // Masking out bits shifted in.
317 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
318 // Make the argument unsigned.
319 Value *ShVal = Op->getOperand(0);
320 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
321 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
330 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
331 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
332 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
333 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
334 /// insert new instructions.
335 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
336 bool isSigned, bool Inside) {
337 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
338 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
339 "Lo is not <= Hi in range emission code!");
342 if (Lo == Hi) // Trivially false.
343 return ConstantInt::getFalse(V->getContext());
345 // V >= Min && V < Hi --> V < Hi
346 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
347 ICmpInst::Predicate pred = (isSigned ?
348 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
349 return Builder->CreateICmp(pred, V, Hi);
352 // Emit V-Lo <u Hi-Lo
353 Constant *NegLo = ConstantExpr::getNeg(Lo);
354 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
355 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
356 return Builder->CreateICmpULT(Add, UpperBound);
359 if (Lo == Hi) // Trivially true.
360 return ConstantInt::getTrue(V->getContext());
362 // V < Min || V >= Hi -> V > Hi-1
363 Hi = SubOne(cast<ConstantInt>(Hi));
364 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
365 ICmpInst::Predicate pred = (isSigned ?
366 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
367 return Builder->CreateICmp(pred, V, Hi);
370 // Emit V-Lo >u Hi-1-Lo
371 // Note that Hi has already had one subtracted from it, above.
372 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
373 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
374 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
375 return Builder->CreateICmpUGT(Add, LowerBound);
378 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
379 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
380 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
381 // not, since all 1s are not contiguous.
382 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
383 const APInt& V = Val->getValue();
384 uint32_t BitWidth = Val->getType()->getBitWidth();
385 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
387 // look for the first zero bit after the run of ones
388 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
389 // look for the first non-zero bit
390 ME = V.getActiveBits();
394 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
395 /// where isSub determines whether the operator is a sub. If we can fold one of
396 /// the following xforms:
398 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
399 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
400 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
402 /// return (A +/- B).
404 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
405 ConstantInt *Mask, bool isSub,
407 Instruction *LHSI = dyn_cast<Instruction>(LHS);
408 if (!LHSI || LHSI->getNumOperands() != 2 ||
409 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
411 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
413 switch (LHSI->getOpcode()) {
415 case Instruction::And:
416 if (ConstantExpr::getAnd(N, Mask) == Mask) {
417 // If the AndRHS is a power of two minus one (0+1+), this is simple.
418 if ((Mask->getValue().countLeadingZeros() +
419 Mask->getValue().countPopulation()) ==
420 Mask->getValue().getBitWidth())
423 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
424 // part, we don't need any explicit masks to take them out of A. If that
425 // is all N is, ignore it.
426 uint32_t MB = 0, ME = 0;
427 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
428 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
429 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
430 if (MaskedValueIsZero(RHS, Mask))
435 case Instruction::Or:
436 case Instruction::Xor:
437 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
438 if ((Mask->getValue().countLeadingZeros() +
439 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
440 && ConstantExpr::getAnd(N, Mask)->isNullValue())
446 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
447 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
450 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
451 /// One of A and B is considered the mask, the other the value. This is
452 /// described as the "AMask" or "BMask" part of the enum. If the enum
453 /// contains only "Mask", then both A and B can be considered masks.
454 /// If A is the mask, then it was proven, that (A & C) == C. This
455 /// is trivial if C == A, or C == 0. If both A and C are constants, this
456 /// proof is also easy.
457 /// For the following explanations we assume that A is the mask.
458 /// The part "AllOnes" declares, that the comparison is true only
459 /// if (A & B) == A, or all bits of A are set in B.
460 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
461 /// The part "AllZeroes" declares, that the comparison is true only
462 /// if (A & B) == 0, or all bits of A are cleared in B.
463 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
464 /// The part "Mixed" declares, that (A & B) == C and C might or might not
465 /// contain any number of one bits and zero bits.
466 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
467 /// The Part "Not" means, that in above descriptions "==" should be replaced
469 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
470 /// If the mask A contains a single bit, then the following is equivalent:
471 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
472 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
473 enum MaskedICmpType {
474 FoldMskICmp_AMask_AllOnes = 1,
475 FoldMskICmp_AMask_NotAllOnes = 2,
476 FoldMskICmp_BMask_AllOnes = 4,
477 FoldMskICmp_BMask_NotAllOnes = 8,
478 FoldMskICmp_Mask_AllZeroes = 16,
479 FoldMskICmp_Mask_NotAllZeroes = 32,
480 FoldMskICmp_AMask_Mixed = 64,
481 FoldMskICmp_AMask_NotMixed = 128,
482 FoldMskICmp_BMask_Mixed = 256,
483 FoldMskICmp_BMask_NotMixed = 512
486 /// return the set of pattern classes (from MaskedICmpType)
487 /// that (icmp SCC (A & B), C) satisfies
488 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
489 ICmpInst::Predicate SCC)
491 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
492 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
493 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
494 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
495 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
496 ACst->getValue().isPowerOf2());
497 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
498 BCst->getValue().isPowerOf2());
500 if (CCst != 0 && CCst->isZero()) {
501 // if C is zero, then both A and B qualify as mask
502 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
503 FoldMskICmp_Mask_AllZeroes |
504 FoldMskICmp_AMask_Mixed |
505 FoldMskICmp_BMask_Mixed)
506 : (FoldMskICmp_Mask_NotAllZeroes |
507 FoldMskICmp_Mask_NotAllZeroes |
508 FoldMskICmp_AMask_NotMixed |
509 FoldMskICmp_BMask_NotMixed));
511 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
512 FoldMskICmp_AMask_NotMixed)
513 : (FoldMskICmp_AMask_AllOnes |
514 FoldMskICmp_AMask_Mixed));
516 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
517 FoldMskICmp_BMask_NotMixed)
518 : (FoldMskICmp_BMask_AllOnes |
519 FoldMskICmp_BMask_Mixed));
523 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
524 FoldMskICmp_AMask_Mixed)
525 : (FoldMskICmp_AMask_NotAllOnes |
526 FoldMskICmp_AMask_NotMixed));
528 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
529 FoldMskICmp_AMask_NotMixed)
530 : (FoldMskICmp_Mask_AllZeroes |
531 FoldMskICmp_AMask_Mixed));
533 else if (ACst != 0 && CCst != 0 &&
534 ConstantExpr::getAnd(ACst, CCst) == CCst) {
535 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
536 : FoldMskICmp_AMask_NotMixed);
540 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
541 FoldMskICmp_BMask_Mixed)
542 : (FoldMskICmp_BMask_NotAllOnes |
543 FoldMskICmp_BMask_NotMixed));
545 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
546 FoldMskICmp_BMask_NotMixed)
547 : (FoldMskICmp_Mask_AllZeroes |
548 FoldMskICmp_BMask_Mixed));
550 else if (BCst != 0 && CCst != 0 &&
551 ConstantExpr::getAnd(BCst, CCst) == CCst) {
552 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
553 : FoldMskICmp_BMask_NotMixed);
558 /// foldLogOpOfMaskedICmpsHelper:
559 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
560 /// return the set of pattern classes (from MaskedICmpType)
561 /// that both LHS and RHS satisfy
562 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
563 Value*& B, Value*& C,
564 Value*& D, Value*& E,
565 ICmpInst *LHS, ICmpInst *RHS) {
566 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
567 if (LHSCC != ICmpInst::ICMP_EQ && LHSCC != ICmpInst::ICMP_NE) return 0;
568 if (RHSCC != ICmpInst::ICMP_EQ && RHSCC != ICmpInst::ICMP_NE) return 0;
569 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
570 // vectors are not (yet?) supported
571 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
573 // Here comes the tricky part:
574 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
575 // and L11 & L12 == L21 & L22. The same goes for RHS.
576 // Now we must find those components L** and R**, that are equal, so
577 // that we can extract the parameters A, B, C, D, and E for the canonical
579 Value *L1 = LHS->getOperand(0);
580 Value *L2 = LHS->getOperand(1);
581 Value *L11,*L12,*L21,*L22;
582 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
583 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
587 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
593 Value *R1 = RHS->getOperand(0);
594 Value *R2 = RHS->getOperand(1);
597 if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
598 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
599 A = R11; D = R12; E = R2; ok = true;
602 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
603 A = R12; D = R11; E = R2; ok = true;
606 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
607 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
608 A = R11; D = R12; E = R1; ok = true;
611 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
612 A = R12; D = R11; E = R1; ok = true;
633 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
634 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
635 return left_type & right_type;
637 /// foldLogOpOfMaskedICmps:
638 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
639 /// into a single (icmp(A & X) ==/!= Y)
640 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
641 ICmpInst::Predicate NEWCC,
642 llvm::InstCombiner::BuilderTy* Builder) {
643 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
644 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS);
645 if (mask == 0) return 0;
647 if (NEWCC == ICmpInst::ICMP_NE)
648 mask >>= 1; // treat "Not"-states as normal states
650 if (mask & FoldMskICmp_Mask_AllZeroes) {
651 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
652 // -> (icmp eq (A & (B|D)), 0)
653 Value* newOr = Builder->CreateOr(B, D);
654 Value* newAnd = Builder->CreateAnd(A, newOr);
655 // we can't use C as zero, because we might actually handle
656 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
657 // with B and D, having a single bit set
658 Value* zero = Constant::getNullValue(A->getType());
659 return Builder->CreateICmp(NEWCC, newAnd, zero);
661 else if (mask & FoldMskICmp_BMask_AllOnes) {
662 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
663 // -> (icmp eq (A & (B|D)), (B|D))
664 Value* newOr = Builder->CreateOr(B, D);
665 Value* newAnd = Builder->CreateAnd(A, newOr);
666 return Builder->CreateICmp(NEWCC, newAnd, newOr);
668 else if (mask & FoldMskICmp_AMask_AllOnes) {
669 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
670 // -> (icmp eq (A & (B&D)), A)
671 Value* newAnd1 = Builder->CreateAnd(B, D);
672 Value* newAnd = Builder->CreateAnd(A, newAnd1);
673 return Builder->CreateICmp(NEWCC, newAnd, A);
675 else if (mask & FoldMskICmp_BMask_Mixed) {
676 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
677 // We already know that B & C == C && D & E == E.
678 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
679 // C and E, which are shared by both the mask B and the mask D, don't
680 // contradict, then we can transform to
681 // -> (icmp eq (A & (B|D)), (C|E))
682 // Currently, we only handle the case of B, C, D, and E being constant.
683 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
684 if (BCst == 0) return 0;
685 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
686 if (DCst == 0) return 0;
687 // we can't simply use C and E, because we might actually handle
688 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
689 // with B and D, having a single bit set
691 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
692 if (CCst == 0) return 0;
693 if (LHS->getPredicate() != NEWCC)
694 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
695 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
696 if (ECst == 0) return 0;
697 if (RHS->getPredicate() != NEWCC)
698 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
699 ConstantInt* MCst = dyn_cast<ConstantInt>(
700 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
701 ConstantExpr::getXor(CCst, ECst)) );
702 // if there is a conflict we should actually return a false for the
706 Value *newOr1 = Builder->CreateOr(B, D);
707 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
708 Value *newAnd = Builder->CreateAnd(A, newOr1);
709 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
714 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
715 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
716 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
718 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
719 if (PredicatesFoldable(LHSCC, RHSCC)) {
720 if (LHS->getOperand(0) == RHS->getOperand(1) &&
721 LHS->getOperand(1) == RHS->getOperand(0))
723 if (LHS->getOperand(0) == RHS->getOperand(0) &&
724 LHS->getOperand(1) == RHS->getOperand(1)) {
725 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
726 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
727 bool isSigned = LHS->isSigned() || RHS->isSigned();
728 return getICmpValue(isSigned, Code, Op0, Op1, Builder);
732 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
733 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
736 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
737 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
738 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
739 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
740 if (LHSCst == 0 || RHSCst == 0) return 0;
742 if (LHSCst == RHSCst && LHSCC == RHSCC) {
743 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
744 // where C is a power of 2
745 if (LHSCC == ICmpInst::ICMP_ULT &&
746 LHSCst->getValue().isPowerOf2()) {
747 Value *NewOr = Builder->CreateOr(Val, Val2);
748 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
751 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
752 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
753 Value *NewOr = Builder->CreateOr(Val, Val2);
754 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
758 // From here on, we only handle:
759 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
760 if (Val != Val2) return 0;
762 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
763 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
764 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
765 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
766 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
769 // We can't fold (ugt x, C) & (sgt x, C2).
770 if (!PredicatesFoldable(LHSCC, RHSCC))
773 // Ensure that the larger constant is on the RHS.
775 if (CmpInst::isSigned(LHSCC) ||
776 (ICmpInst::isEquality(LHSCC) &&
777 CmpInst::isSigned(RHSCC)))
778 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
780 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
784 std::swap(LHSCst, RHSCst);
785 std::swap(LHSCC, RHSCC);
788 // At this point, we know we have two icmp instructions
789 // comparing a value against two constants and and'ing the result
790 // together. Because of the above check, we know that we only have
791 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
792 // (from the icmp folding check above), that the two constants
793 // are not equal and that the larger constant is on the RHS
794 assert(LHSCst != RHSCst && "Compares not folded above?");
797 default: llvm_unreachable("Unknown integer condition code!");
798 case ICmpInst::ICMP_EQ:
800 default: llvm_unreachable("Unknown integer condition code!");
801 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
802 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
803 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
804 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
805 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
806 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
807 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
810 case ICmpInst::ICMP_NE:
812 default: llvm_unreachable("Unknown integer condition code!");
813 case ICmpInst::ICMP_ULT:
814 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
815 return Builder->CreateICmpULT(Val, LHSCst);
816 break; // (X != 13 & X u< 15) -> no change
817 case ICmpInst::ICMP_SLT:
818 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
819 return Builder->CreateICmpSLT(Val, LHSCst);
820 break; // (X != 13 & X s< 15) -> no change
821 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
822 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
823 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
825 case ICmpInst::ICMP_NE:
826 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
827 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
828 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
829 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
831 break; // (X != 13 & X != 15) -> no change
834 case ICmpInst::ICMP_ULT:
836 default: llvm_unreachable("Unknown integer condition code!");
837 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
838 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
839 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
840 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
842 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
843 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
845 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
849 case ICmpInst::ICMP_SLT:
851 default: llvm_unreachable("Unknown integer condition code!");
852 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
853 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
854 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
855 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
857 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
858 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
860 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
864 case ICmpInst::ICMP_UGT:
866 default: llvm_unreachable("Unknown integer condition code!");
867 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
868 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
870 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
872 case ICmpInst::ICMP_NE:
873 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
874 return Builder->CreateICmp(LHSCC, Val, RHSCst);
875 break; // (X u> 13 & X != 15) -> no change
876 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
877 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
878 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
882 case ICmpInst::ICMP_SGT:
884 default: llvm_unreachable("Unknown integer condition code!");
885 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
886 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
888 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
890 case ICmpInst::ICMP_NE:
891 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
892 return Builder->CreateICmp(LHSCC, Val, RHSCst);
893 break; // (X s> 13 & X != 15) -> no change
894 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
895 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
896 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
905 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
906 /// instcombine, this returns a Value which should already be inserted into the
908 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
909 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
910 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
911 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
912 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
913 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
914 // If either of the constants are nans, then the whole thing returns
916 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
917 return ConstantInt::getFalse(LHS->getContext());
918 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
921 // Handle vector zeros. This occurs because the canonical form of
922 // "fcmp ord x,x" is "fcmp ord x, 0".
923 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
924 isa<ConstantAggregateZero>(RHS->getOperand(1)))
925 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
929 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
930 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
931 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
934 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
935 // Swap RHS operands to match LHS.
936 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
937 std::swap(Op1LHS, Op1RHS);
940 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
941 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
943 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
944 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
945 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
946 if (Op0CC == FCmpInst::FCMP_TRUE)
948 if (Op1CC == FCmpInst::FCMP_TRUE)
953 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
954 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
957 std::swap(Op0Pred, Op1Pred);
958 std::swap(Op0Ordered, Op1Ordered);
961 // uno && ueq -> uno && (uno || eq) -> ueq
962 // ord && olt -> ord && (ord && lt) -> olt
963 if (Op0Ordered == Op1Ordered)
966 // uno && oeq -> uno && (ord && eq) -> false
967 // uno && ord -> false
969 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
970 // ord && ueq -> ord && (uno || eq) -> oeq
971 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
979 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
980 bool Changed = SimplifyAssociativeOrCommutative(I);
981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
983 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
984 return ReplaceInstUsesWith(I, V);
986 // (A|B)&(A|C) -> A|(B&C) etc
987 if (Value *V = SimplifyUsingDistributiveLaws(I))
988 return ReplaceInstUsesWith(I, V);
990 // See if we can simplify any instructions used by the instruction whose sole
991 // purpose is to compute bits we don't care about.
992 if (SimplifyDemandedInstructionBits(I))
995 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
996 const APInt &AndRHSMask = AndRHS->getValue();
998 // Optimize a variety of ((val OP C1) & C2) combinations...
999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1000 Value *Op0LHS = Op0I->getOperand(0);
1001 Value *Op0RHS = Op0I->getOperand(1);
1002 switch (Op0I->getOpcode()) {
1004 case Instruction::Xor:
1005 case Instruction::Or: {
1006 // If the mask is only needed on one incoming arm, push it up.
1007 if (!Op0I->hasOneUse()) break;
1009 APInt NotAndRHS(~AndRHSMask);
1010 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1011 // Not masking anything out for the LHS, move to RHS.
1012 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1013 Op0RHS->getName()+".masked");
1014 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1016 if (!isa<Constant>(Op0RHS) &&
1017 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1018 // Not masking anything out for the RHS, move to LHS.
1019 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1020 Op0LHS->getName()+".masked");
1021 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1026 case Instruction::Add:
1027 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1028 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1029 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1030 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1031 return BinaryOperator::CreateAnd(V, AndRHS);
1032 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1033 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1036 case Instruction::Sub:
1037 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1038 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1039 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1040 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1041 return BinaryOperator::CreateAnd(V, AndRHS);
1043 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1044 // has 1's for all bits that the subtraction with A might affect.
1045 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1046 uint32_t BitWidth = AndRHSMask.getBitWidth();
1047 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1048 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1050 if (MaskedValueIsZero(Op0LHS, Mask)) {
1051 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1052 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1057 case Instruction::Shl:
1058 case Instruction::LShr:
1059 // (1 << x) & 1 --> zext(x == 0)
1060 // (1 >> x) & 1 --> zext(x == 0)
1061 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1063 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1064 return new ZExtInst(NewICmp, I.getType());
1069 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1070 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1074 // If this is an integer truncation, and if the source is an 'and' with
1075 // immediate, transform it. This frequently occurs for bitfield accesses.
1077 Value *X = 0; ConstantInt *YC = 0;
1078 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1079 // Change: and (trunc (and X, YC) to T), C2
1080 // into : and (trunc X to T), trunc(YC) & C2
1081 // This will fold the two constants together, which may allow
1082 // other simplifications.
1083 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1084 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1085 C3 = ConstantExpr::getAnd(C3, AndRHS);
1086 return BinaryOperator::CreateAnd(NewCast, C3);
1090 // Try to fold constant and into select arguments.
1091 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1092 if (Instruction *R = FoldOpIntoSelect(I, SI))
1094 if (isa<PHINode>(Op0))
1095 if (Instruction *NV = FoldOpIntoPhi(I))
1100 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1101 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1102 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1103 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1104 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1105 I.getName()+".demorgan");
1106 return BinaryOperator::CreateNot(Or);
1110 Value *A = 0, *B = 0, *C = 0, *D = 0;
1111 // (A|B) & ~(A&B) -> A^B
1112 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1113 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1114 ((A == C && B == D) || (A == D && B == C)))
1115 return BinaryOperator::CreateXor(A, B);
1117 // ~(A&B) & (A|B) -> A^B
1118 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1119 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1120 ((A == C && B == D) || (A == D && B == C)))
1121 return BinaryOperator::CreateXor(A, B);
1123 if (Op0->hasOneUse() &&
1124 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1125 if (A == Op1) { // (A^B)&A -> A&(A^B)
1126 I.swapOperands(); // Simplify below
1127 std::swap(Op0, Op1);
1128 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
1129 cast<BinaryOperator>(Op0)->swapOperands();
1130 I.swapOperands(); // Simplify below
1131 std::swap(Op0, Op1);
1135 if (Op1->hasOneUse() &&
1136 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1137 if (B == Op0) { // B&(A^B) -> B&(B^A)
1138 cast<BinaryOperator>(Op1)->swapOperands();
1141 if (A == Op0) // A&(A^B) -> A & ~B
1142 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
1145 // (A&((~A)|B)) -> A&B
1146 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1147 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1148 return BinaryOperator::CreateAnd(A, Op1);
1149 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1150 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1151 return BinaryOperator::CreateAnd(A, Op0);
1154 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1155 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1156 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1157 return ReplaceInstUsesWith(I, Res);
1159 // If and'ing two fcmp, try combine them into one.
1160 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1161 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1162 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1163 return ReplaceInstUsesWith(I, Res);
1166 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1167 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1168 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1169 const Type *SrcTy = Op0C->getOperand(0)->getType();
1170 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1171 SrcTy == Op1C->getOperand(0)->getType() &&
1172 SrcTy->isIntOrIntVectorTy()) {
1173 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1175 // Only do this if the casts both really cause code to be generated.
1176 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1177 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1178 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1179 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1182 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1183 // cast is otherwise not optimizable. This happens for vector sexts.
1184 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1185 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1186 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1187 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1189 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1190 // cast is otherwise not optimizable. This happens for vector sexts.
1191 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1192 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1193 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1194 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1198 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1199 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1200 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1201 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1202 SI0->getOperand(1) == SI1->getOperand(1) &&
1203 (SI0->hasOneUse() || SI1->hasOneUse())) {
1205 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1207 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1208 SI1->getOperand(1));
1212 return Changed ? &I : 0;
1215 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1216 /// capable of providing pieces of a bswap. The subexpression provides pieces
1217 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1218 /// the expression came from the corresponding "byte swapped" byte in some other
1219 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1220 /// we know that the expression deposits the low byte of %X into the high byte
1221 /// of the bswap result and that all other bytes are zero. This expression is
1222 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1225 /// This function returns true if the match was unsuccessful and false if so.
1226 /// On entry to the function the "OverallLeftShift" is a signed integer value
1227 /// indicating the number of bytes that the subexpression is later shifted. For
1228 /// example, if the expression is later right shifted by 16 bits, the
1229 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1230 /// byte of ByteValues is actually being set.
1232 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1233 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1234 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1235 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1236 /// always in the local (OverallLeftShift) coordinate space.
1238 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1239 SmallVector<Value*, 8> &ByteValues) {
1240 if (Instruction *I = dyn_cast<Instruction>(V)) {
1241 // If this is an or instruction, it may be an inner node of the bswap.
1242 if (I->getOpcode() == Instruction::Or) {
1243 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1245 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1249 // If this is a logical shift by a constant multiple of 8, recurse with
1250 // OverallLeftShift and ByteMask adjusted.
1251 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1253 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1254 // Ensure the shift amount is defined and of a byte value.
1255 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1258 unsigned ByteShift = ShAmt >> 3;
1259 if (I->getOpcode() == Instruction::Shl) {
1260 // X << 2 -> collect(X, +2)
1261 OverallLeftShift += ByteShift;
1262 ByteMask >>= ByteShift;
1264 // X >>u 2 -> collect(X, -2)
1265 OverallLeftShift -= ByteShift;
1266 ByteMask <<= ByteShift;
1267 ByteMask &= (~0U >> (32-ByteValues.size()));
1270 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1271 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1273 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1277 // If this is a logical 'and' with a mask that clears bytes, clear the
1278 // corresponding bytes in ByteMask.
1279 if (I->getOpcode() == Instruction::And &&
1280 isa<ConstantInt>(I->getOperand(1))) {
1281 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1282 unsigned NumBytes = ByteValues.size();
1283 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1284 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1286 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1287 // If this byte is masked out by a later operation, we don't care what
1289 if ((ByteMask & (1 << i)) == 0)
1292 // If the AndMask is all zeros for this byte, clear the bit.
1293 APInt MaskB = AndMask & Byte;
1295 ByteMask &= ~(1U << i);
1299 // If the AndMask is not all ones for this byte, it's not a bytezap.
1303 // Otherwise, this byte is kept.
1306 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1311 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1312 // the input value to the bswap. Some observations: 1) if more than one byte
1313 // is demanded from this input, then it could not be successfully assembled
1314 // into a byteswap. At least one of the two bytes would not be aligned with
1315 // their ultimate destination.
1316 if (!isPowerOf2_32(ByteMask)) return true;
1317 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1319 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1320 // is demanded, it needs to go into byte 0 of the result. This means that the
1321 // byte needs to be shifted until it lands in the right byte bucket. The
1322 // shift amount depends on the position: if the byte is coming from the high
1323 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1324 // low part, it must be shifted left.
1325 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1326 if (InputByteNo < ByteValues.size()/2) {
1327 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1330 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1334 // If the destination byte value is already defined, the values are or'd
1335 // together, which isn't a bswap (unless it's an or of the same bits).
1336 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1338 ByteValues[DestByteNo] = V;
1342 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1343 /// If so, insert the new bswap intrinsic and return it.
1344 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1345 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1346 if (!ITy || ITy->getBitWidth() % 16 ||
1347 // ByteMask only allows up to 32-byte values.
1348 ITy->getBitWidth() > 32*8)
1349 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1351 /// ByteValues - For each byte of the result, we keep track of which value
1352 /// defines each byte.
1353 SmallVector<Value*, 8> ByteValues;
1354 ByteValues.resize(ITy->getBitWidth()/8);
1356 // Try to find all the pieces corresponding to the bswap.
1357 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1358 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1361 // Check to see if all of the bytes come from the same value.
1362 Value *V = ByteValues[0];
1363 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1365 // Check to make sure that all of the bytes come from the same value.
1366 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1367 if (ByteValues[i] != V)
1369 const Type *Tys[] = { ITy };
1370 Module *M = I.getParent()->getParent()->getParent();
1371 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1372 return CallInst::Create(F, V);
1375 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1376 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1377 /// we can simplify this expression to "cond ? C : D or B".
1378 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1379 Value *C, Value *D) {
1380 // If A is not a select of -1/0, this cannot match.
1382 if (!match(A, m_SExt(m_Value(Cond))) ||
1383 !Cond->getType()->isIntegerTy(1))
1386 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1387 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1388 return SelectInst::Create(Cond, C, B);
1389 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1390 return SelectInst::Create(Cond, C, B);
1392 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1393 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1394 return SelectInst::Create(Cond, C, D);
1395 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1396 return SelectInst::Create(Cond, C, D);
1400 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1401 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1402 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1404 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1405 if (PredicatesFoldable(LHSCC, RHSCC)) {
1406 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1407 LHS->getOperand(1) == RHS->getOperand(0))
1408 LHS->swapOperands();
1409 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1410 LHS->getOperand(1) == RHS->getOperand(1)) {
1411 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1412 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1413 bool isSigned = LHS->isSigned() || RHS->isSigned();
1414 return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1418 // handle (roughly):
1419 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1420 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1423 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1424 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1425 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1426 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1427 if (LHSCst == 0 || RHSCst == 0) return 0;
1429 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1430 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1431 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1432 Value *NewOr = Builder->CreateOr(Val, Val2);
1433 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1437 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1438 // iff C2 + CA == C1.
1439 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1440 ConstantInt *AddCst;
1441 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1442 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1443 return Builder->CreateICmpULE(Val, LHSCst);
1446 // From here on, we only handle:
1447 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1448 if (Val != Val2) return 0;
1450 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1451 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1452 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1453 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1454 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1457 // We can't fold (ugt x, C) | (sgt x, C2).
1458 if (!PredicatesFoldable(LHSCC, RHSCC))
1461 // Ensure that the larger constant is on the RHS.
1463 if (CmpInst::isSigned(LHSCC) ||
1464 (ICmpInst::isEquality(LHSCC) &&
1465 CmpInst::isSigned(RHSCC)))
1466 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1468 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1471 std::swap(LHS, RHS);
1472 std::swap(LHSCst, RHSCst);
1473 std::swap(LHSCC, RHSCC);
1476 // At this point, we know we have two icmp instructions
1477 // comparing a value against two constants and or'ing the result
1478 // together. Because of the above check, we know that we only have
1479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1480 // icmp folding check above), that the two constants are not
1482 assert(LHSCst != RHSCst && "Compares not folded above?");
1485 default: llvm_unreachable("Unknown integer condition code!");
1486 case ICmpInst::ICMP_EQ:
1488 default: llvm_unreachable("Unknown integer condition code!");
1489 case ICmpInst::ICMP_EQ:
1490 if (LHSCst == SubOne(RHSCst)) {
1491 // (X == 13 | X == 14) -> X-13 <u 2
1492 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1493 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1494 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1495 return Builder->CreateICmpULT(Add, AddCST);
1497 break; // (X == 13 | X == 15) -> no change
1498 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1499 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1501 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1502 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1503 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1507 case ICmpInst::ICMP_NE:
1509 default: llvm_unreachable("Unknown integer condition code!");
1510 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1511 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1512 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1514 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1515 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1516 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1517 return ConstantInt::getTrue(LHS->getContext());
1520 case ICmpInst::ICMP_ULT:
1522 default: llvm_unreachable("Unknown integer condition code!");
1523 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1525 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1526 // If RHSCst is [us]MAXINT, it is always false. Not handling
1527 // this can cause overflow.
1528 if (RHSCst->isMaxValue(false))
1530 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1531 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1533 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1534 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1536 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1540 case ICmpInst::ICMP_SLT:
1542 default: llvm_unreachable("Unknown integer condition code!");
1543 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1545 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1546 // If RHSCst is [us]MAXINT, it is always false. Not handling
1547 // this can cause overflow.
1548 if (RHSCst->isMaxValue(true))
1550 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1551 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1553 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1554 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1556 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1560 case ICmpInst::ICMP_UGT:
1562 default: llvm_unreachable("Unknown integer condition code!");
1563 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1564 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1566 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1568 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1569 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1570 return ConstantInt::getTrue(LHS->getContext());
1571 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1575 case ICmpInst::ICMP_SGT:
1577 default: llvm_unreachable("Unknown integer condition code!");
1578 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1579 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1581 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1583 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1584 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1585 return ConstantInt::getTrue(LHS->getContext());
1586 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1594 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1595 /// instcombine, this returns a Value which should already be inserted into the
1597 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1598 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1599 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1600 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1601 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1602 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1603 // If either of the constants are nans, then the whole thing returns
1605 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1606 return ConstantInt::getTrue(LHS->getContext());
1608 // Otherwise, no need to compare the two constants, compare the
1610 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1613 // Handle vector zeros. This occurs because the canonical form of
1614 // "fcmp uno x,x" is "fcmp uno x, 0".
1615 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1616 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1617 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1622 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1623 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1624 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1626 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1627 // Swap RHS operands to match LHS.
1628 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1629 std::swap(Op1LHS, Op1RHS);
1631 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1632 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1634 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1635 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1636 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1637 if (Op0CC == FCmpInst::FCMP_FALSE)
1639 if (Op1CC == FCmpInst::FCMP_FALSE)
1643 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1644 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1645 if (Op0Ordered == Op1Ordered) {
1646 // If both are ordered or unordered, return a new fcmp with
1647 // or'ed predicates.
1648 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1654 /// FoldOrWithConstants - This helper function folds:
1656 /// ((A | B) & C1) | (B & C2)
1662 /// when the XOR of the two constants is "all ones" (-1).
1663 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1664 Value *A, Value *B, Value *C) {
1665 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1669 ConstantInt *CI2 = 0;
1670 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1672 APInt Xor = CI1->getValue() ^ CI2->getValue();
1673 if (!Xor.isAllOnesValue()) return 0;
1675 if (V1 == A || V1 == B) {
1676 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1677 return BinaryOperator::CreateOr(NewOp, V1);
1683 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1684 bool Changed = SimplifyAssociativeOrCommutative(I);
1685 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1687 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1688 return ReplaceInstUsesWith(I, V);
1690 // (A&B)|(A&C) -> A&(B|C) etc
1691 if (Value *V = SimplifyUsingDistributiveLaws(I))
1692 return ReplaceInstUsesWith(I, V);
1694 // See if we can simplify any instructions used by the instruction whose sole
1695 // purpose is to compute bits we don't care about.
1696 if (SimplifyDemandedInstructionBits(I))
1699 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1700 ConstantInt *C1 = 0; Value *X = 0;
1701 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1702 // iff (C1 & C2) == 0.
1703 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1704 (RHS->getValue() & C1->getValue()) != 0 &&
1706 Value *Or = Builder->CreateOr(X, RHS);
1708 return BinaryOperator::CreateAnd(Or,
1709 ConstantInt::get(I.getContext(),
1710 RHS->getValue() | C1->getValue()));
1713 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1714 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1716 Value *Or = Builder->CreateOr(X, RHS);
1718 return BinaryOperator::CreateXor(Or,
1719 ConstantInt::get(I.getContext(),
1720 C1->getValue() & ~RHS->getValue()));
1723 // Try to fold constant and into select arguments.
1724 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1725 if (Instruction *R = FoldOpIntoSelect(I, SI))
1728 if (isa<PHINode>(Op0))
1729 if (Instruction *NV = FoldOpIntoPhi(I))
1733 Value *A = 0, *B = 0;
1734 ConstantInt *C1 = 0, *C2 = 0;
1736 // (A | B) | C and A | (B | C) -> bswap if possible.
1737 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1738 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1739 match(Op1, m_Or(m_Value(), m_Value())) ||
1740 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1741 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1742 if (Instruction *BSwap = MatchBSwap(I))
1746 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1747 if (Op0->hasOneUse() &&
1748 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1749 MaskedValueIsZero(Op1, C1->getValue())) {
1750 Value *NOr = Builder->CreateOr(A, Op1);
1752 return BinaryOperator::CreateXor(NOr, C1);
1755 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1756 if (Op1->hasOneUse() &&
1757 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1758 MaskedValueIsZero(Op0, C1->getValue())) {
1759 Value *NOr = Builder->CreateOr(A, Op0);
1761 return BinaryOperator::CreateXor(NOr, C1);
1765 Value *C = 0, *D = 0;
1766 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1767 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1768 Value *V1 = 0, *V2 = 0;
1769 C1 = dyn_cast<ConstantInt>(C);
1770 C2 = dyn_cast<ConstantInt>(D);
1771 if (C1 && C2) { // (A & C1)|(B & C2)
1772 // If we have: ((V + N) & C1) | (V & C2)
1773 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1774 // replace with V+N.
1775 if (C1->getValue() == ~C2->getValue()) {
1776 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1777 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1778 // Add commutes, try both ways.
1779 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1780 return ReplaceInstUsesWith(I, A);
1781 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1782 return ReplaceInstUsesWith(I, A);
1784 // Or commutes, try both ways.
1785 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1786 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1787 // Add commutes, try both ways.
1788 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1789 return ReplaceInstUsesWith(I, B);
1790 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1791 return ReplaceInstUsesWith(I, B);
1795 if ((C1->getValue() & C2->getValue()) == 0) {
1796 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1797 // iff (C1&C2) == 0 and (N&~C1) == 0
1798 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1799 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1800 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1801 return BinaryOperator::CreateAnd(A,
1802 ConstantInt::get(A->getContext(),
1803 C1->getValue()|C2->getValue()));
1804 // Or commutes, try both ways.
1805 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1806 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1807 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1808 return BinaryOperator::CreateAnd(B,
1809 ConstantInt::get(B->getContext(),
1810 C1->getValue()|C2->getValue()));
1812 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1813 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1814 ConstantInt *C3 = 0, *C4 = 0;
1815 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1816 (C3->getValue() & ~C1->getValue()) == 0 &&
1817 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1818 (C4->getValue() & ~C2->getValue()) == 0) {
1819 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1820 return BinaryOperator::CreateAnd(V2,
1821 ConstantInt::get(B->getContext(),
1822 C1->getValue()|C2->getValue()));
1827 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1828 // Don't do this for vector select idioms, the code generator doesn't handle
1830 if (!I.getType()->isVectorTy()) {
1831 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1833 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1835 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1837 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1841 // ((A&~B)|(~A&B)) -> A^B
1842 if ((match(C, m_Not(m_Specific(D))) &&
1843 match(B, m_Not(m_Specific(A)))))
1844 return BinaryOperator::CreateXor(A, D);
1845 // ((~B&A)|(~A&B)) -> A^B
1846 if ((match(A, m_Not(m_Specific(D))) &&
1847 match(B, m_Not(m_Specific(C)))))
1848 return BinaryOperator::CreateXor(C, D);
1849 // ((A&~B)|(B&~A)) -> A^B
1850 if ((match(C, m_Not(m_Specific(B))) &&
1851 match(D, m_Not(m_Specific(A)))))
1852 return BinaryOperator::CreateXor(A, B);
1853 // ((~B&A)|(B&~A)) -> A^B
1854 if ((match(A, m_Not(m_Specific(B))) &&
1855 match(D, m_Not(m_Specific(C)))))
1856 return BinaryOperator::CreateXor(C, B);
1858 // ((A|B)&1)|(B&-2) -> (A&1) | B
1859 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1860 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1861 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1862 if (Ret) return Ret;
1864 // (B&-2)|((A|B)&1) -> (A&1) | B
1865 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1866 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1867 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1868 if (Ret) return Ret;
1872 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1873 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1874 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1875 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1876 SI0->getOperand(1) == SI1->getOperand(1) &&
1877 (SI0->hasOneUse() || SI1->hasOneUse())) {
1878 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1880 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1881 SI1->getOperand(1));
1885 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1886 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1887 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1888 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1889 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1890 I.getName()+".demorgan");
1891 return BinaryOperator::CreateNot(And);
1894 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1895 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1896 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1897 return ReplaceInstUsesWith(I, Res);
1899 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1900 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1901 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1902 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1903 return ReplaceInstUsesWith(I, Res);
1905 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1906 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1907 CastInst *Op1C = dyn_cast<CastInst>(Op1);
1908 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1909 const Type *SrcTy = Op0C->getOperand(0)->getType();
1910 if (SrcTy == Op1C->getOperand(0)->getType() &&
1911 SrcTy->isIntOrIntVectorTy()) {
1912 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1914 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1915 // Only do this if the casts both really cause code to be
1917 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1918 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1919 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1920 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1923 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1924 // cast is otherwise not optimizable. This happens for vector sexts.
1925 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1926 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1927 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1928 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1930 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1931 // cast is otherwise not optimizable. This happens for vector sexts.
1932 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1933 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1934 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1935 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1940 // Note: If we've gotten to the point of visiting the outer OR, then the
1941 // inner one couldn't be simplified. If it was a constant, then it won't
1942 // be simplified by a later pass either, so we try swapping the inner/outer
1943 // ORs in the hopes that we'll be able to simplify it this way.
1944 // (X|C) | V --> (X|V) | C
1945 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
1946 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
1947 Value *Inner = Builder->CreateOr(A, Op1);
1948 Inner->takeName(Op0);
1949 return BinaryOperator::CreateOr(Inner, C1);
1952 return Changed ? &I : 0;
1955 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1956 bool Changed = SimplifyAssociativeOrCommutative(I);
1957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1959 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
1960 return ReplaceInstUsesWith(I, V);
1962 // (A&B)^(A&C) -> A&(B^C) etc
1963 if (Value *V = SimplifyUsingDistributiveLaws(I))
1964 return ReplaceInstUsesWith(I, V);
1966 // See if we can simplify any instructions used by the instruction whose sole
1967 // purpose is to compute bits we don't care about.
1968 if (SimplifyDemandedInstructionBits(I))
1971 // Is this a ~ operation?
1972 if (Value *NotOp = dyn_castNotVal(&I)) {
1973 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1974 if (Op0I->getOpcode() == Instruction::And ||
1975 Op0I->getOpcode() == Instruction::Or) {
1976 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1977 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1978 if (dyn_castNotVal(Op0I->getOperand(1)))
1979 Op0I->swapOperands();
1980 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1982 Builder->CreateNot(Op0I->getOperand(1),
1983 Op0I->getOperand(1)->getName()+".not");
1984 if (Op0I->getOpcode() == Instruction::And)
1985 return BinaryOperator::CreateOr(Op0NotVal, NotY);
1986 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1989 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1990 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1991 if (isFreeToInvert(Op0I->getOperand(0)) &&
1992 isFreeToInvert(Op0I->getOperand(1))) {
1994 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1996 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1997 if (Op0I->getOpcode() == Instruction::And)
1998 return BinaryOperator::CreateOr(NotX, NotY);
1999 return BinaryOperator::CreateAnd(NotX, NotY);
2002 } else if (Op0I->getOpcode() == Instruction::AShr) {
2003 // ~(~X >>s Y) --> (X >>s Y)
2004 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2005 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2012 if (RHS->isOne() && Op0->hasOneUse())
2013 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2014 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2015 return CmpInst::Create(CI->getOpcode(),
2016 CI->getInversePredicate(),
2017 CI->getOperand(0), CI->getOperand(1));
2019 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2020 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2021 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2022 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2023 Instruction::CastOps Opcode = Op0C->getOpcode();
2024 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2025 (RHS == ConstantExpr::getCast(Opcode,
2026 ConstantInt::getTrue(I.getContext()),
2027 Op0C->getDestTy()))) {
2028 CI->setPredicate(CI->getInversePredicate());
2029 return CastInst::Create(Opcode, CI, Op0C->getType());
2035 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2036 // ~(c-X) == X-c-1 == X+(-c-1)
2037 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2038 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2039 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2040 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2041 ConstantInt::get(I.getType(), 1));
2042 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2046 if (Op0I->getOpcode() == Instruction::Add) {
2047 // ~(X-c) --> (-c-1)-X
2048 if (RHS->isAllOnesValue()) {
2049 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2050 return BinaryOperator::CreateSub(
2051 ConstantExpr::getSub(NegOp0CI,
2052 ConstantInt::get(I.getType(), 1)),
2053 Op0I->getOperand(0));
2054 } else if (RHS->getValue().isSignBit()) {
2055 // (X + C) ^ signbit -> (X + C + signbit)
2056 Constant *C = ConstantInt::get(I.getContext(),
2057 RHS->getValue() + Op0CI->getValue());
2058 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2061 } else if (Op0I->getOpcode() == Instruction::Or) {
2062 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2063 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2064 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2065 // Anything in both C1 and C2 is known to be zero, remove it from
2067 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2068 NewRHS = ConstantExpr::getAnd(NewRHS,
2069 ConstantExpr::getNot(CommonBits));
2071 I.setOperand(0, Op0I->getOperand(0));
2072 I.setOperand(1, NewRHS);
2079 // Try to fold constant and into select arguments.
2080 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2081 if (Instruction *R = FoldOpIntoSelect(I, SI))
2083 if (isa<PHINode>(Op0))
2084 if (Instruction *NV = FoldOpIntoPhi(I))
2088 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2091 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2092 if (A == Op0) { // B^(B|A) == (A|B)^B
2093 Op1I->swapOperands();
2095 std::swap(Op0, Op1);
2096 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2097 I.swapOperands(); // Simplified below.
2098 std::swap(Op0, Op1);
2100 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2102 if (A == Op0) { // A^(A&B) -> A^(B&A)
2103 Op1I->swapOperands();
2106 if (B == Op0) { // A^(B&A) -> (B&A)^A
2107 I.swapOperands(); // Simplified below.
2108 std::swap(Op0, Op1);
2113 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2116 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2117 Op0I->hasOneUse()) {
2118 if (A == Op1) // (B|A)^B == (A|B)^B
2120 if (B == Op1) // (A|B)^B == A & ~B
2121 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
2122 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2124 if (A == Op1) // (A&B)^A -> (B&A)^A
2126 if (B == Op1 && // (B&A)^A == ~B & A
2127 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2128 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
2133 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2134 if (Op0I && Op1I && Op0I->isShift() &&
2135 Op0I->getOpcode() == Op1I->getOpcode() &&
2136 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2137 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2139 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2141 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2142 Op1I->getOperand(1));
2146 Value *A, *B, *C, *D;
2147 // (A & B)^(A | B) -> A ^ B
2148 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2149 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2150 if ((A == C && B == D) || (A == D && B == C))
2151 return BinaryOperator::CreateXor(A, B);
2153 // (A | B)^(A & B) -> A ^ B
2154 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2155 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2156 if ((A == C && B == D) || (A == D && B == C))
2157 return BinaryOperator::CreateXor(A, B);
2161 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2162 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2163 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2164 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2165 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2166 LHS->getOperand(1) == RHS->getOperand(0))
2167 LHS->swapOperands();
2168 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2169 LHS->getOperand(1) == RHS->getOperand(1)) {
2170 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2171 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2172 bool isSigned = LHS->isSigned() || RHS->isSigned();
2173 return ReplaceInstUsesWith(I,
2174 getICmpValue(isSigned, Code, Op0, Op1, Builder));
2178 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2179 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2180 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2181 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2182 const Type *SrcTy = Op0C->getOperand(0)->getType();
2183 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2184 // Only do this if the casts both really cause code to be generated.
2185 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2187 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2189 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2190 Op1C->getOperand(0), I.getName());
2191 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2196 return Changed ? &I : 0;