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;
175 case 7: return ConstantInt::getTrue(LHS->getContext());
177 return Builder->CreateFCmp(Pred, LHS, RHS);
180 /// PredicatesFoldable - Return true if both predicates match sign or if at
181 /// least one of them is an equality comparison (which is signless).
182 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
183 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
184 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
185 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
188 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
189 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
190 // guaranteed to be a binary operator.
191 Instruction *InstCombiner::OptAndOp(Instruction *Op,
194 BinaryOperator &TheAnd) {
195 Value *X = Op->getOperand(0);
196 Constant *Together = 0;
198 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
200 switch (Op->getOpcode()) {
201 case Instruction::Xor:
202 if (Op->hasOneUse()) {
203 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
204 Value *And = Builder->CreateAnd(X, AndRHS);
206 return BinaryOperator::CreateXor(And, Together);
209 case Instruction::Or:
210 if (Op->hasOneUse()){
211 if (Together != OpRHS) {
212 // (X | C1) & C2 --> (X | (C1&C2)) & C2
213 Value *Or = Builder->CreateOr(X, Together);
215 return BinaryOperator::CreateAnd(Or, AndRHS);
218 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
219 if (TogetherCI && !TogetherCI->isZero()){
220 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
221 // NOTE: This reduces the number of bits set in the & mask, which
222 // can expose opportunities for store narrowing.
223 Together = ConstantExpr::getXor(AndRHS, Together);
224 Value *And = Builder->CreateAnd(X, Together);
226 return BinaryOperator::CreateOr(And, OpRHS);
231 case Instruction::Add:
232 if (Op->hasOneUse()) {
233 // Adding a one to a single bit bit-field should be turned into an XOR
234 // of the bit. First thing to check is to see if this AND is with a
235 // single bit constant.
236 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
238 // If there is only one bit set.
239 if (AndRHSV.isPowerOf2()) {
240 // Ok, at this point, we know that we are masking the result of the
241 // ADD down to exactly one bit. If the constant we are adding has
242 // no bits set below this bit, then we can eliminate the ADD.
243 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
245 // Check to see if any bits below the one bit set in AndRHSV are set.
246 if ((AddRHS & (AndRHSV-1)) == 0) {
247 // If not, the only thing that can effect the output of the AND is
248 // the bit specified by AndRHSV. If that bit is set, the effect of
249 // the XOR is to toggle the bit. If it is clear, then the ADD has
251 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
252 TheAnd.setOperand(0, X);
255 // Pull the XOR out of the AND.
256 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
257 NewAnd->takeName(Op);
258 return BinaryOperator::CreateXor(NewAnd, AndRHS);
265 case Instruction::Shl: {
266 // We know that the AND will not produce any of the bits shifted in, so if
267 // the anded constant includes them, clear them now!
269 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
270 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
271 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
272 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
273 AndRHS->getValue() & ShlMask);
275 if (CI->getValue() == ShlMask) {
276 // Masking out bits that the shift already masks
277 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
278 } else if (CI != AndRHS) { // Reducing bits set in and.
279 TheAnd.setOperand(1, CI);
284 case Instruction::LShr: {
285 // We know that the AND will not produce any of the bits shifted in, so if
286 // the anded constant includes them, clear them now! This only applies to
287 // unsigned shifts, because a signed shr may bring in set bits!
289 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
290 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
291 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
292 ConstantInt *CI = ConstantInt::get(Op->getContext(),
293 AndRHS->getValue() & ShrMask);
295 if (CI->getValue() == ShrMask) {
296 // Masking out bits that the shift already masks.
297 return ReplaceInstUsesWith(TheAnd, Op);
298 } else if (CI != AndRHS) {
299 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
304 case Instruction::AShr:
306 // See if this is shifting in some sign extension, then masking it out
308 if (Op->hasOneUse()) {
309 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
310 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
311 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
312 Constant *C = ConstantInt::get(Op->getContext(),
313 AndRHS->getValue() & ShrMask);
314 if (C == AndRHS) { // Masking out bits shifted in.
315 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
316 // Make the argument unsigned.
317 Value *ShVal = Op->getOperand(0);
318 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
319 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
328 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
329 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
330 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
331 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
332 /// insert new instructions.
333 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
334 bool isSigned, bool Inside) {
335 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
336 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
337 "Lo is not <= Hi in range emission code!");
340 if (Lo == Hi) // Trivially false.
341 return ConstantInt::getFalse(V->getContext());
343 // V >= Min && V < Hi --> V < Hi
344 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
345 ICmpInst::Predicate pred = (isSigned ?
346 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
347 return Builder->CreateICmp(pred, V, Hi);
350 // Emit V-Lo <u Hi-Lo
351 Constant *NegLo = ConstantExpr::getNeg(Lo);
352 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
353 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
354 return Builder->CreateICmpULT(Add, UpperBound);
357 if (Lo == Hi) // Trivially true.
358 return ConstantInt::getTrue(V->getContext());
360 // V < Min || V >= Hi -> V > Hi-1
361 Hi = SubOne(cast<ConstantInt>(Hi));
362 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
363 ICmpInst::Predicate pred = (isSigned ?
364 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
365 return Builder->CreateICmp(pred, V, Hi);
368 // Emit V-Lo >u Hi-1-Lo
369 // Note that Hi has already had one subtracted from it, above.
370 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
371 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
372 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
373 return Builder->CreateICmpUGT(Add, LowerBound);
376 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
377 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
378 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
379 // not, since all 1s are not contiguous.
380 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
381 const APInt& V = Val->getValue();
382 uint32_t BitWidth = Val->getType()->getBitWidth();
383 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
385 // look for the first zero bit after the run of ones
386 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
387 // look for the first non-zero bit
388 ME = V.getActiveBits();
392 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
393 /// where isSub determines whether the operator is a sub. If we can fold one of
394 /// the following xforms:
396 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
397 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
398 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
400 /// return (A +/- B).
402 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
403 ConstantInt *Mask, bool isSub,
405 Instruction *LHSI = dyn_cast<Instruction>(LHS);
406 if (!LHSI || LHSI->getNumOperands() != 2 ||
407 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
409 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
411 switch (LHSI->getOpcode()) {
413 case Instruction::And:
414 if (ConstantExpr::getAnd(N, Mask) == Mask) {
415 // If the AndRHS is a power of two minus one (0+1+), this is simple.
416 if ((Mask->getValue().countLeadingZeros() +
417 Mask->getValue().countPopulation()) ==
418 Mask->getValue().getBitWidth())
421 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
422 // part, we don't need any explicit masks to take them out of A. If that
423 // is all N is, ignore it.
424 uint32_t MB = 0, ME = 0;
425 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
426 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
427 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
428 if (MaskedValueIsZero(RHS, Mask))
433 case Instruction::Or:
434 case Instruction::Xor:
435 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
436 if ((Mask->getValue().countLeadingZeros() +
437 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
438 && ConstantExpr::getAnd(N, Mask)->isNullValue())
444 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
445 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
448 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
449 /// One of A and B is considered the mask, the other the value. This is
450 /// described as the "AMask" or "BMask" part of the enum. If the enum
451 /// contains only "Mask", then both A and B can be considered masks.
452 /// If A is the mask, then it was proven, that (A & C) == C. This
453 /// is trivial if C == A, or C == 0. If both A and C are constants, this
454 /// proof is also easy.
455 /// For the following explanations we assume that A is the mask.
456 /// The part "AllOnes" declares, that the comparison is true only
457 /// if (A & B) == A, or all bits of A are set in B.
458 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
459 /// The part "AllZeroes" declares, that the comparison is true only
460 /// if (A & B) == 0, or all bits of A are cleared in B.
461 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
462 /// The part "Mixed" declares, that (A & B) == C and C might or might not
463 /// contain any number of one bits and zero bits.
464 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
465 /// The Part "Not" means, that in above descriptions "==" should be replaced
467 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
468 /// If the mask A contains a single bit, then the following is equivalent:
469 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
470 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
471 enum MaskedICmpType {
472 FoldMskICmp_AMask_AllOnes = 1,
473 FoldMskICmp_AMask_NotAllOnes = 2,
474 FoldMskICmp_BMask_AllOnes = 4,
475 FoldMskICmp_BMask_NotAllOnes = 8,
476 FoldMskICmp_Mask_AllZeroes = 16,
477 FoldMskICmp_Mask_NotAllZeroes = 32,
478 FoldMskICmp_AMask_Mixed = 64,
479 FoldMskICmp_AMask_NotMixed = 128,
480 FoldMskICmp_BMask_Mixed = 256,
481 FoldMskICmp_BMask_NotMixed = 512
484 /// return the set of pattern classes (from MaskedICmpType)
485 /// that (icmp SCC (A & B), C) satisfies
486 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
487 ICmpInst::Predicate SCC)
489 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
490 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
491 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
492 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
493 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
494 ACst->getValue().isPowerOf2());
495 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
496 BCst->getValue().isPowerOf2());
498 if (CCst != 0 && CCst->isZero()) {
499 // if C is zero, then both A and B qualify as mask
500 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
501 FoldMskICmp_Mask_AllZeroes |
502 FoldMskICmp_AMask_Mixed |
503 FoldMskICmp_BMask_Mixed)
504 : (FoldMskICmp_Mask_NotAllZeroes |
505 FoldMskICmp_Mask_NotAllZeroes |
506 FoldMskICmp_AMask_NotMixed |
507 FoldMskICmp_BMask_NotMixed));
509 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
510 FoldMskICmp_AMask_NotMixed)
511 : (FoldMskICmp_AMask_AllOnes |
512 FoldMskICmp_AMask_Mixed));
514 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
515 FoldMskICmp_BMask_NotMixed)
516 : (FoldMskICmp_BMask_AllOnes |
517 FoldMskICmp_BMask_Mixed));
521 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
522 FoldMskICmp_AMask_Mixed)
523 : (FoldMskICmp_AMask_NotAllOnes |
524 FoldMskICmp_AMask_NotMixed));
526 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
527 FoldMskICmp_AMask_NotMixed)
528 : (FoldMskICmp_Mask_AllZeroes |
529 FoldMskICmp_AMask_Mixed));
531 else if (ACst != 0 && CCst != 0 &&
532 ConstantExpr::getAnd(ACst, CCst) == CCst) {
533 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
534 : FoldMskICmp_AMask_NotMixed);
538 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
539 FoldMskICmp_BMask_Mixed)
540 : (FoldMskICmp_BMask_NotAllOnes |
541 FoldMskICmp_BMask_NotMixed));
543 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
544 FoldMskICmp_BMask_NotMixed)
545 : (FoldMskICmp_Mask_AllZeroes |
546 FoldMskICmp_BMask_Mixed));
548 else if (BCst != 0 && CCst != 0 &&
549 ConstantExpr::getAnd(BCst, CCst) == CCst) {
550 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
551 : FoldMskICmp_BMask_NotMixed);
556 /// foldLogOpOfMaskedICmpsHelper:
557 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
558 /// return the set of pattern classes (from MaskedICmpType)
559 /// that both LHS and RHS satisfy
560 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
561 Value*& B, Value*& C,
562 Value*& D, Value*& E,
563 ICmpInst *LHS, ICmpInst *RHS) {
564 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
565 if (LHSCC != ICmpInst::ICMP_EQ && LHSCC != ICmpInst::ICMP_NE) return 0;
566 if (RHSCC != ICmpInst::ICMP_EQ && RHSCC != ICmpInst::ICMP_NE) return 0;
567 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
568 // vectors are not (yet?) supported
569 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
571 // Here comes the tricky part:
572 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
573 // and L11 & L12 == L21 & L22. The same goes for RHS.
574 // Now we must find those components L** and R**, that are equal, so
575 // that we can extract the parameters A, B, C, D, and E for the canonical
577 Value *L1 = LHS->getOperand(0);
578 Value *L2 = LHS->getOperand(1);
579 Value *L11,*L12,*L21,*L22;
580 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
581 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
585 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
591 Value *R1 = RHS->getOperand(0);
592 Value *R2 = RHS->getOperand(1);
595 if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
596 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
597 A = R11; D = R12; E = R2; ok = true;
600 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
601 A = R12; D = R11; E = R2; ok = true;
604 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
605 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
606 A = R11; D = R12; E = R1; ok = true;
609 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
610 A = R12; D = R11; E = R1; ok = true;
631 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
632 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
633 return left_type & right_type;
635 /// foldLogOpOfMaskedICmps:
636 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
637 /// into a single (icmp(A & X) ==/!= Y)
638 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
639 ICmpInst::Predicate NEWCC,
640 llvm::InstCombiner::BuilderTy* Builder) {
641 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
642 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS);
643 if (mask == 0) return 0;
645 if (NEWCC == ICmpInst::ICMP_NE)
646 mask >>= 1; // treat "Not"-states as normal states
648 if (mask & FoldMskICmp_Mask_AllZeroes) {
649 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
650 // -> (icmp eq (A & (B|D)), 0)
651 Value* newOr = Builder->CreateOr(B, D);
652 Value* newAnd = Builder->CreateAnd(A, newOr);
653 // we can't use C as zero, because we might actually handle
654 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
655 // with B and D, having a single bit set
656 Value* zero = Constant::getNullValue(A->getType());
657 return Builder->CreateICmp(NEWCC, newAnd, zero);
659 else if (mask & FoldMskICmp_BMask_AllOnes) {
660 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
661 // -> (icmp eq (A & (B|D)), (B|D))
662 Value* newOr = Builder->CreateOr(B, D);
663 Value* newAnd = Builder->CreateAnd(A, newOr);
664 return Builder->CreateICmp(NEWCC, newAnd, newOr);
666 else if (mask & FoldMskICmp_AMask_AllOnes) {
667 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
668 // -> (icmp eq (A & (B&D)), A)
669 Value* newAnd1 = Builder->CreateAnd(B, D);
670 Value* newAnd = Builder->CreateAnd(A, newAnd1);
671 return Builder->CreateICmp(NEWCC, newAnd, A);
673 else if (mask & FoldMskICmp_BMask_Mixed) {
674 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
675 // We already know that B & C == C && D & E == E.
676 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
677 // C and E, which are shared by both the mask B and the mask D, don't
678 // contradict, then we can transform to
679 // -> (icmp eq (A & (B|D)), (C|E))
680 // Currently, we only handle the case of B, C, D, and E being constant.
681 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
682 if (BCst == 0) return 0;
683 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
684 if (DCst == 0) return 0;
685 // we can't simply use C and E, because we might actually handle
686 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
687 // with B and D, having a single bit set
689 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
690 if (CCst == 0) return 0;
691 if (LHS->getPredicate() != NEWCC)
692 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
693 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
694 if (ECst == 0) return 0;
695 if (RHS->getPredicate() != NEWCC)
696 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
697 ConstantInt* MCst = dyn_cast<ConstantInt>(
698 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
699 ConstantExpr::getXor(CCst, ECst)) );
700 // if there is a conflict we should actually return a false for the
704 Value* newOr1 = Builder->CreateOr(B, D);
705 Value* newOr2 = ConstantExpr::getOr(CCst, ECst);
706 Value* newAnd = Builder->CreateAnd(A, newOr1);
707 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
712 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
713 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
714 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
716 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
717 if (PredicatesFoldable(LHSCC, RHSCC)) {
718 if (LHS->getOperand(0) == RHS->getOperand(1) &&
719 LHS->getOperand(1) == RHS->getOperand(0))
721 if (LHS->getOperand(0) == RHS->getOperand(0) &&
722 LHS->getOperand(1) == RHS->getOperand(1)) {
723 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
724 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
725 bool isSigned = LHS->isSigned() || RHS->isSigned();
726 return getICmpValue(isSigned, Code, Op0, Op1, Builder);
732 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
733 Value* fold = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder);
734 if (fold) return fold;
737 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
738 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
739 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
740 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
741 if (LHSCst == 0 || RHSCst == 0) return 0;
743 if (LHSCst == RHSCst && LHSCC == RHSCC) {
744 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
745 // where C is a power of 2
746 if (LHSCC == ICmpInst::ICMP_ULT &&
747 LHSCst->getValue().isPowerOf2()) {
748 Value *NewOr = Builder->CreateOr(Val, Val2);
749 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
752 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
753 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
754 Value *NewOr = Builder->CreateOr(Val, Val2);
755 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
759 // From here on, we only handle:
760 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
761 if (Val != Val2) return 0;
763 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
764 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
765 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
766 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
767 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
770 // We can't fold (ugt x, C) & (sgt x, C2).
771 if (!PredicatesFoldable(LHSCC, RHSCC))
774 // Ensure that the larger constant is on the RHS.
776 if (CmpInst::isSigned(LHSCC) ||
777 (ICmpInst::isEquality(LHSCC) &&
778 CmpInst::isSigned(RHSCC)))
779 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
781 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
785 std::swap(LHSCst, RHSCst);
786 std::swap(LHSCC, RHSCC);
789 // At this point, we know we have two icmp instructions
790 // comparing a value against two constants and and'ing the result
791 // together. Because of the above check, we know that we only have
792 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
793 // (from the icmp folding check above), that the two constants
794 // are not equal and that the larger constant is on the RHS
795 assert(LHSCst != RHSCst && "Compares not folded above?");
798 default: llvm_unreachable("Unknown integer condition code!");
799 case ICmpInst::ICMP_EQ:
801 default: llvm_unreachable("Unknown integer condition code!");
802 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
803 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
804 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
805 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
806 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
807 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
808 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
811 case ICmpInst::ICMP_NE:
813 default: llvm_unreachable("Unknown integer condition code!");
814 case ICmpInst::ICMP_ULT:
815 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
816 return Builder->CreateICmpULT(Val, LHSCst);
817 break; // (X != 13 & X u< 15) -> no change
818 case ICmpInst::ICMP_SLT:
819 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
820 return Builder->CreateICmpSLT(Val, LHSCst);
821 break; // (X != 13 & X s< 15) -> no change
822 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
823 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
824 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
826 case ICmpInst::ICMP_NE:
827 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
828 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
829 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
830 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
832 break; // (X != 13 & X != 15) -> no change
835 case ICmpInst::ICMP_ULT:
837 default: llvm_unreachable("Unknown integer condition code!");
838 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
839 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
840 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
841 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
843 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
844 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
846 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
850 case ICmpInst::ICMP_SLT:
852 default: llvm_unreachable("Unknown integer condition code!");
853 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
854 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
855 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
856 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
858 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
859 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
861 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
865 case ICmpInst::ICMP_UGT:
867 default: llvm_unreachable("Unknown integer condition code!");
868 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
869 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
871 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
873 case ICmpInst::ICMP_NE:
874 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
875 return Builder->CreateICmp(LHSCC, Val, RHSCst);
876 break; // (X u> 13 & X != 15) -> no change
877 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
878 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
879 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
883 case ICmpInst::ICMP_SGT:
885 default: llvm_unreachable("Unknown integer condition code!");
886 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
887 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
889 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
891 case ICmpInst::ICMP_NE:
892 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
893 return Builder->CreateICmp(LHSCC, Val, RHSCst);
894 break; // (X s> 13 & X != 15) -> no change
895 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
896 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
897 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
906 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
907 /// instcombine, this returns a Value which should already be inserted into the
909 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
910 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
911 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
912 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
913 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
914 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
915 // If either of the constants are nans, then the whole thing returns
917 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
918 return ConstantInt::getFalse(LHS->getContext());
919 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
922 // Handle vector zeros. This occurs because the canonical form of
923 // "fcmp ord x,x" is "fcmp ord x, 0".
924 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
925 isa<ConstantAggregateZero>(RHS->getOperand(1)))
926 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
930 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
931 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
932 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
935 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
936 // Swap RHS operands to match LHS.
937 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
938 std::swap(Op1LHS, Op1RHS);
941 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
942 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
944 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
945 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
946 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
947 if (Op0CC == FCmpInst::FCMP_TRUE)
949 if (Op1CC == FCmpInst::FCMP_TRUE)
954 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
955 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
958 std::swap(Op0Pred, Op1Pred);
959 std::swap(Op0Ordered, Op1Ordered);
962 // uno && ueq -> uno && (uno || eq) -> ueq
963 // ord && olt -> ord && (ord && lt) -> olt
964 if (Op0Ordered == Op1Ordered)
967 // uno && oeq -> uno && (ord && eq) -> false
968 // uno && ord -> false
970 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
971 // ord && ueq -> ord && (uno || eq) -> oeq
972 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
980 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
981 bool Changed = SimplifyAssociativeOrCommutative(I);
982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
984 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
985 return ReplaceInstUsesWith(I, V);
987 if (Instruction *NV = SimplifyDistributed(I)) // (A|B)&(A|C) -> A|(B&C)
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();
997 APInt NotAndRHS(~AndRHSMask);
999 // Optimize a variety of ((val OP C1) & C2) combinations...
1000 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1001 Value *Op0LHS = Op0I->getOperand(0);
1002 Value *Op0RHS = Op0I->getOperand(1);
1003 switch (Op0I->getOpcode()) {
1005 case Instruction::Xor:
1006 case Instruction::Or:
1007 // If the mask is only needed on one incoming arm, push it up.
1008 if (!Op0I->hasOneUse()) break;
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);
1025 case Instruction::Add:
1026 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1027 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1028 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1029 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1030 return BinaryOperator::CreateAnd(V, AndRHS);
1031 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1032 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1035 case Instruction::Sub:
1036 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1037 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1038 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1039 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1040 return BinaryOperator::CreateAnd(V, AndRHS);
1042 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1043 // has 1's for all bits that the subtraction with A might affect.
1044 if (Op0I->hasOneUse()) {
1045 uint32_t BitWidth = AndRHSMask.getBitWidth();
1046 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1047 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1049 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
1050 if (!(A && A->isZero()) && // avoid infinite recursion.
1051 MaskedValueIsZero(Op0LHS, Mask)) {
1052 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1053 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1058 case Instruction::Shl:
1059 case Instruction::LShr:
1060 // (1 << x) & 1 --> zext(x == 0)
1061 // (1 >> x) & 1 --> zext(x == 0)
1062 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1064 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1065 return new ZExtInst(NewICmp, I.getType());
1070 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1071 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1073 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1074 // If this is an integer truncation or change from signed-to-unsigned, and
1075 // if the source is an and/or with immediate, transform it. This
1076 // frequently occurs for bitfield accesses.
1077 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1078 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
1079 CastOp->getNumOperands() == 2)
1080 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
1081 if (CastOp->getOpcode() == Instruction::And) {
1082 // Change: and (cast (and X, C1) to T), C2
1083 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
1084 // This will fold the two constants together, which may allow
1085 // other simplifications.
1086 Value *NewCast = Builder->CreateTruncOrBitCast(
1087 CastOp->getOperand(0), I.getType(),
1088 CastOp->getName()+".shrunk");
1089 // trunc_or_bitcast(C1)&C2
1090 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
1091 C3 = ConstantExpr::getAnd(C3, AndRHS);
1092 return BinaryOperator::CreateAnd(NewCast, C3);
1093 } else if (CastOp->getOpcode() == Instruction::Or) {
1094 // Change: and (cast (or X, C1) to T), C2
1095 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1096 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
1097 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
1099 return ReplaceInstUsesWith(I, AndRHS);
1105 // Try to fold constant and into select arguments.
1106 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1107 if (Instruction *R = FoldOpIntoSelect(I, SI))
1109 if (isa<PHINode>(Op0))
1110 if (Instruction *NV = FoldOpIntoPhi(I))
1115 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1116 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1117 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1118 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1119 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1120 I.getName()+".demorgan");
1121 return BinaryOperator::CreateNot(Or);
1125 Value *A = 0, *B = 0, *C = 0, *D = 0;
1126 // (A|B) & ~(A&B) -> A^B
1127 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1128 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1129 ((A == C && B == D) || (A == D && B == C)))
1130 return BinaryOperator::CreateXor(A, B);
1132 // ~(A&B) & (A|B) -> A^B
1133 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1134 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1135 ((A == C && B == D) || (A == D && B == C)))
1136 return BinaryOperator::CreateXor(A, B);
1138 if (Op0->hasOneUse() &&
1139 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1140 if (A == Op1) { // (A^B)&A -> A&(A^B)
1141 I.swapOperands(); // Simplify below
1142 std::swap(Op0, Op1);
1143 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
1144 cast<BinaryOperator>(Op0)->swapOperands();
1145 I.swapOperands(); // Simplify below
1146 std::swap(Op0, Op1);
1150 if (Op1->hasOneUse() &&
1151 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1152 if (B == Op0) { // B&(A^B) -> B&(B^A)
1153 cast<BinaryOperator>(Op1)->swapOperands();
1156 if (A == Op0) // A&(A^B) -> A & ~B
1157 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
1160 // (A&((~A)|B)) -> A&B
1161 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1162 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1163 return BinaryOperator::CreateAnd(A, Op1);
1164 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1165 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1166 return BinaryOperator::CreateAnd(A, Op0);
1169 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1170 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1171 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1172 return ReplaceInstUsesWith(I, Res);
1174 // If and'ing two fcmp, try combine them into one.
1175 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1176 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1177 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1178 return ReplaceInstUsesWith(I, Res);
1181 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1182 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1183 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1184 const Type *SrcTy = Op0C->getOperand(0)->getType();
1185 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1186 SrcTy == Op1C->getOperand(0)->getType() &&
1187 SrcTy->isIntOrIntVectorTy()) {
1188 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1190 // Only do this if the casts both really cause code to be generated.
1191 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1192 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1193 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1194 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1197 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1198 // cast is otherwise not optimizable. This happens for vector sexts.
1199 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1200 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1201 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1202 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1204 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1205 // cast is otherwise not optimizable. This happens for vector sexts.
1206 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1207 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1208 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1209 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1213 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1214 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1215 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1216 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1217 SI0->getOperand(1) == SI1->getOperand(1) &&
1218 (SI0->hasOneUse() || SI1->hasOneUse())) {
1220 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1222 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1223 SI1->getOperand(1));
1227 return Changed ? &I : 0;
1230 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1231 /// capable of providing pieces of a bswap. The subexpression provides pieces
1232 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1233 /// the expression came from the corresponding "byte swapped" byte in some other
1234 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1235 /// we know that the expression deposits the low byte of %X into the high byte
1236 /// of the bswap result and that all other bytes are zero. This expression is
1237 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1240 /// This function returns true if the match was unsuccessful and false if so.
1241 /// On entry to the function the "OverallLeftShift" is a signed integer value
1242 /// indicating the number of bytes that the subexpression is later shifted. For
1243 /// example, if the expression is later right shifted by 16 bits, the
1244 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1245 /// byte of ByteValues is actually being set.
1247 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1248 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1249 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1250 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1251 /// always in the local (OverallLeftShift) coordinate space.
1253 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1254 SmallVector<Value*, 8> &ByteValues) {
1255 if (Instruction *I = dyn_cast<Instruction>(V)) {
1256 // If this is an or instruction, it may be an inner node of the bswap.
1257 if (I->getOpcode() == Instruction::Or) {
1258 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1260 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1264 // If this is a logical shift by a constant multiple of 8, recurse with
1265 // OverallLeftShift and ByteMask adjusted.
1266 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1268 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1269 // Ensure the shift amount is defined and of a byte value.
1270 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1273 unsigned ByteShift = ShAmt >> 3;
1274 if (I->getOpcode() == Instruction::Shl) {
1275 // X << 2 -> collect(X, +2)
1276 OverallLeftShift += ByteShift;
1277 ByteMask >>= ByteShift;
1279 // X >>u 2 -> collect(X, -2)
1280 OverallLeftShift -= ByteShift;
1281 ByteMask <<= ByteShift;
1282 ByteMask &= (~0U >> (32-ByteValues.size()));
1285 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1286 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1288 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1292 // If this is a logical 'and' with a mask that clears bytes, clear the
1293 // corresponding bytes in ByteMask.
1294 if (I->getOpcode() == Instruction::And &&
1295 isa<ConstantInt>(I->getOperand(1))) {
1296 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1297 unsigned NumBytes = ByteValues.size();
1298 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1299 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1301 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1302 // If this byte is masked out by a later operation, we don't care what
1304 if ((ByteMask & (1 << i)) == 0)
1307 // If the AndMask is all zeros for this byte, clear the bit.
1308 APInt MaskB = AndMask & Byte;
1310 ByteMask &= ~(1U << i);
1314 // If the AndMask is not all ones for this byte, it's not a bytezap.
1318 // Otherwise, this byte is kept.
1321 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1326 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1327 // the input value to the bswap. Some observations: 1) if more than one byte
1328 // is demanded from this input, then it could not be successfully assembled
1329 // into a byteswap. At least one of the two bytes would not be aligned with
1330 // their ultimate destination.
1331 if (!isPowerOf2_32(ByteMask)) return true;
1332 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1334 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1335 // is demanded, it needs to go into byte 0 of the result. This means that the
1336 // byte needs to be shifted until it lands in the right byte bucket. The
1337 // shift amount depends on the position: if the byte is coming from the high
1338 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1339 // low part, it must be shifted left.
1340 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1341 if (InputByteNo < ByteValues.size()/2) {
1342 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1345 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1349 // If the destination byte value is already defined, the values are or'd
1350 // together, which isn't a bswap (unless it's an or of the same bits).
1351 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1353 ByteValues[DestByteNo] = V;
1357 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1358 /// If so, insert the new bswap intrinsic and return it.
1359 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1360 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1361 if (!ITy || ITy->getBitWidth() % 16 ||
1362 // ByteMask only allows up to 32-byte values.
1363 ITy->getBitWidth() > 32*8)
1364 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1366 /// ByteValues - For each byte of the result, we keep track of which value
1367 /// defines each byte.
1368 SmallVector<Value*, 8> ByteValues;
1369 ByteValues.resize(ITy->getBitWidth()/8);
1371 // Try to find all the pieces corresponding to the bswap.
1372 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1373 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1376 // Check to see if all of the bytes come from the same value.
1377 Value *V = ByteValues[0];
1378 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1380 // Check to make sure that all of the bytes come from the same value.
1381 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1382 if (ByteValues[i] != V)
1384 const Type *Tys[] = { ITy };
1385 Module *M = I.getParent()->getParent()->getParent();
1386 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1387 return CallInst::Create(F, V);
1390 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1391 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1392 /// we can simplify this expression to "cond ? C : D or B".
1393 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1394 Value *C, Value *D) {
1395 // If A is not a select of -1/0, this cannot match.
1397 if (!match(A, m_SExt(m_Value(Cond))) ||
1398 !Cond->getType()->isIntegerTy(1))
1401 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1402 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1403 return SelectInst::Create(Cond, C, B);
1404 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1405 return SelectInst::Create(Cond, C, B);
1407 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1408 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1409 return SelectInst::Create(Cond, C, D);
1410 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1411 return SelectInst::Create(Cond, C, D);
1415 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1416 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1417 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1419 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1420 if (PredicatesFoldable(LHSCC, RHSCC)) {
1421 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1422 LHS->getOperand(1) == RHS->getOperand(0))
1423 LHS->swapOperands();
1424 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1425 LHS->getOperand(1) == RHS->getOperand(1)) {
1426 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1427 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1428 bool isSigned = LHS->isSigned() || RHS->isSigned();
1429 return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1434 // handle (roughly):
1435 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1436 Value* fold = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder);
1437 if (fold) return fold;
1440 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1441 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1442 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1443 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1444 if (LHSCst == 0 || RHSCst == 0) return 0;
1446 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1447 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1448 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1449 Value *NewOr = Builder->CreateOr(Val, Val2);
1450 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1454 // From here on, we only handle:
1455 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1456 if (Val != Val2) return 0;
1458 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1459 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1460 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1461 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1462 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1465 // We can't fold (ugt x, C) | (sgt x, C2).
1466 if (!PredicatesFoldable(LHSCC, RHSCC))
1469 // Ensure that the larger constant is on the RHS.
1471 if (CmpInst::isSigned(LHSCC) ||
1472 (ICmpInst::isEquality(LHSCC) &&
1473 CmpInst::isSigned(RHSCC)))
1474 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1476 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1479 std::swap(LHS, RHS);
1480 std::swap(LHSCst, RHSCst);
1481 std::swap(LHSCC, RHSCC);
1484 // At this point, we know we have two icmp instructions
1485 // comparing a value against two constants and or'ing the result
1486 // together. Because of the above check, we know that we only have
1487 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1488 // icmp folding check above), that the two constants are not
1490 assert(LHSCst != RHSCst && "Compares not folded above?");
1493 default: llvm_unreachable("Unknown integer condition code!");
1494 case ICmpInst::ICMP_EQ:
1496 default: llvm_unreachable("Unknown integer condition code!");
1497 case ICmpInst::ICMP_EQ:
1498 if (LHSCst == SubOne(RHSCst)) {
1499 // (X == 13 | X == 14) -> X-13 <u 2
1500 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1501 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1502 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1503 return Builder->CreateICmpULT(Add, AddCST);
1505 break; // (X == 13 | X == 15) -> no change
1506 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1507 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1509 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1510 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1511 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1515 case ICmpInst::ICMP_NE:
1517 default: llvm_unreachable("Unknown integer condition code!");
1518 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1519 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1520 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1522 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1523 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1524 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1525 return ConstantInt::getTrue(LHS->getContext());
1528 case ICmpInst::ICMP_ULT:
1530 default: llvm_unreachable("Unknown integer condition code!");
1531 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1533 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1534 // If RHSCst is [us]MAXINT, it is always false. Not handling
1535 // this can cause overflow.
1536 if (RHSCst->isMaxValue(false))
1538 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1539 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1541 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1542 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1544 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1548 case ICmpInst::ICMP_SLT:
1550 default: llvm_unreachable("Unknown integer condition code!");
1551 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1553 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1554 // If RHSCst is [us]MAXINT, it is always false. Not handling
1555 // this can cause overflow.
1556 if (RHSCst->isMaxValue(true))
1558 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1559 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1561 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1562 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1564 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1568 case ICmpInst::ICMP_UGT:
1570 default: llvm_unreachable("Unknown integer condition code!");
1571 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1572 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1574 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1576 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1577 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1578 return ConstantInt::getTrue(LHS->getContext());
1579 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1583 case ICmpInst::ICMP_SGT:
1585 default: llvm_unreachable("Unknown integer condition code!");
1586 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1587 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1589 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1591 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1592 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1593 return ConstantInt::getTrue(LHS->getContext());
1594 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1602 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1603 /// instcombine, this returns a Value which should already be inserted into the
1605 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1606 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1607 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1608 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1609 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1610 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1611 // If either of the constants are nans, then the whole thing returns
1613 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1614 return ConstantInt::getTrue(LHS->getContext());
1616 // Otherwise, no need to compare the two constants, compare the
1618 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1621 // Handle vector zeros. This occurs because the canonical form of
1622 // "fcmp uno x,x" is "fcmp uno x, 0".
1623 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1624 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1625 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1630 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1631 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1632 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1634 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1635 // Swap RHS operands to match LHS.
1636 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1637 std::swap(Op1LHS, Op1RHS);
1639 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1640 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1642 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1643 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1644 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1645 if (Op0CC == FCmpInst::FCMP_FALSE)
1647 if (Op1CC == FCmpInst::FCMP_FALSE)
1651 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1652 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1653 if (Op0Ordered == Op1Ordered) {
1654 // If both are ordered or unordered, return a new fcmp with
1655 // or'ed predicates.
1656 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1662 /// FoldOrWithConstants - This helper function folds:
1664 /// ((A | B) & C1) | (B & C2)
1670 /// when the XOR of the two constants is "all ones" (-1).
1671 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1672 Value *A, Value *B, Value *C) {
1673 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1677 ConstantInt *CI2 = 0;
1678 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1680 APInt Xor = CI1->getValue() ^ CI2->getValue();
1681 if (!Xor.isAllOnesValue()) return 0;
1683 if (V1 == A || V1 == B) {
1684 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1685 return BinaryOperator::CreateOr(NewOp, V1);
1691 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1692 bool Changed = SimplifyAssociativeOrCommutative(I);
1693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1695 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1696 return ReplaceInstUsesWith(I, V);
1698 if (Instruction *NV = SimplifyDistributed(I)) // (A&B)|(A&C) -> A&(B|C)
1701 // See if we can simplify any instructions used by the instruction whose sole
1702 // purpose is to compute bits we don't care about.
1703 if (SimplifyDemandedInstructionBits(I))
1706 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1707 ConstantInt *C1 = 0; Value *X = 0;
1708 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1709 // iff (C1 & C2) == 0.
1710 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1711 (RHS->getValue() & C1->getValue()) != 0 &&
1713 Value *Or = Builder->CreateOr(X, RHS);
1715 return BinaryOperator::CreateAnd(Or,
1716 ConstantInt::get(I.getContext(),
1717 RHS->getValue() | C1->getValue()));
1720 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1721 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1723 Value *Or = Builder->CreateOr(X, RHS);
1725 return BinaryOperator::CreateXor(Or,
1726 ConstantInt::get(I.getContext(),
1727 C1->getValue() & ~RHS->getValue()));
1730 // Try to fold constant and into select arguments.
1731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1732 if (Instruction *R = FoldOpIntoSelect(I, SI))
1735 if (isa<PHINode>(Op0))
1736 if (Instruction *NV = FoldOpIntoPhi(I))
1740 Value *A = 0, *B = 0;
1741 ConstantInt *C1 = 0, *C2 = 0;
1743 // (A | B) | C and A | (B | C) -> bswap if possible.
1744 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1745 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1746 match(Op1, m_Or(m_Value(), m_Value())) ||
1747 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1748 match(Op1, m_Shift(m_Value(), m_Value())))) {
1749 if (Instruction *BSwap = MatchBSwap(I))
1753 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1754 if (Op0->hasOneUse() &&
1755 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1756 MaskedValueIsZero(Op1, C1->getValue())) {
1757 Value *NOr = Builder->CreateOr(A, Op1);
1759 return BinaryOperator::CreateXor(NOr, C1);
1762 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1763 if (Op1->hasOneUse() &&
1764 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1765 MaskedValueIsZero(Op0, C1->getValue())) {
1766 Value *NOr = Builder->CreateOr(A, Op0);
1768 return BinaryOperator::CreateXor(NOr, C1);
1772 Value *C = 0, *D = 0;
1773 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1774 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1775 Value *V1 = 0, *V2 = 0;
1776 C1 = dyn_cast<ConstantInt>(C);
1777 C2 = dyn_cast<ConstantInt>(D);
1778 if (C1 && C2) { // (A & C1)|(B & C2)
1779 // If we have: ((V + N) & C1) | (V & C2)
1780 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1781 // replace with V+N.
1782 if (C1->getValue() == ~C2->getValue()) {
1783 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1784 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1785 // Add commutes, try both ways.
1786 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1787 return ReplaceInstUsesWith(I, A);
1788 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1789 return ReplaceInstUsesWith(I, A);
1791 // Or commutes, try both ways.
1792 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1793 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1794 // Add commutes, try both ways.
1795 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1796 return ReplaceInstUsesWith(I, B);
1797 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1798 return ReplaceInstUsesWith(I, B);
1802 if ((C1->getValue() & C2->getValue()) == 0) {
1803 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1804 // iff (C1&C2) == 0 and (N&~C1) == 0
1805 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1806 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1807 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1808 return BinaryOperator::CreateAnd(A,
1809 ConstantInt::get(A->getContext(),
1810 C1->getValue()|C2->getValue()));
1811 // Or commutes, try both ways.
1812 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1813 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1814 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1815 return BinaryOperator::CreateAnd(B,
1816 ConstantInt::get(B->getContext(),
1817 C1->getValue()|C2->getValue()));
1819 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1820 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1821 ConstantInt *C3 = 0, *C4 = 0;
1822 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1823 (C3->getValue() & ~C1->getValue()) == 0 &&
1824 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1825 (C4->getValue() & ~C2->getValue()) == 0) {
1826 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1827 return BinaryOperator::CreateAnd(V2,
1828 ConstantInt::get(B->getContext(),
1829 C1->getValue()|C2->getValue()));
1834 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1835 // Don't do this for vector select idioms, the code generator doesn't handle
1837 if (!I.getType()->isVectorTy()) {
1838 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1840 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1842 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1844 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1848 // ((A&~B)|(~A&B)) -> A^B
1849 if ((match(C, m_Not(m_Specific(D))) &&
1850 match(B, m_Not(m_Specific(A)))))
1851 return BinaryOperator::CreateXor(A, D);
1852 // ((~B&A)|(~A&B)) -> A^B
1853 if ((match(A, m_Not(m_Specific(D))) &&
1854 match(B, m_Not(m_Specific(C)))))
1855 return BinaryOperator::CreateXor(C, D);
1856 // ((A&~B)|(B&~A)) -> A^B
1857 if ((match(C, m_Not(m_Specific(B))) &&
1858 match(D, m_Not(m_Specific(A)))))
1859 return BinaryOperator::CreateXor(A, B);
1860 // ((~B&A)|(B&~A)) -> A^B
1861 if ((match(A, m_Not(m_Specific(B))) &&
1862 match(D, m_Not(m_Specific(C)))))
1863 return BinaryOperator::CreateXor(C, B);
1865 // ((A|B)&1)|(B&-2) -> (A&1) | B
1866 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1867 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1868 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1869 if (Ret) return Ret;
1871 // (B&-2)|((A|B)&1) -> (A&1) | B
1872 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1873 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1874 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1875 if (Ret) return Ret;
1879 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1880 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1881 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1882 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1883 SI0->getOperand(1) == SI1->getOperand(1) &&
1884 (SI0->hasOneUse() || SI1->hasOneUse())) {
1885 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1887 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1888 SI1->getOperand(1));
1892 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1893 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1894 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1895 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1896 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1897 I.getName()+".demorgan");
1898 return BinaryOperator::CreateNot(And);
1901 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1902 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1903 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1904 return ReplaceInstUsesWith(I, Res);
1906 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1907 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1908 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1909 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1910 return ReplaceInstUsesWith(I, Res);
1912 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1913 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1914 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1915 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1916 const Type *SrcTy = Op0C->getOperand(0)->getType();
1917 if (SrcTy == Op1C->getOperand(0)->getType() &&
1918 SrcTy->isIntOrIntVectorTy()) {
1919 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1921 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1922 // Only do this if the casts both really cause code to be
1924 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1925 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1926 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1927 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1930 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1931 // cast is otherwise not optimizable. This happens for vector sexts.
1932 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1933 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1934 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1935 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1937 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1938 // cast is otherwise not optimizable. This happens for vector sexts.
1939 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1940 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1941 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1942 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1947 // Note: If we've gotten to the point of visiting the outer OR, then the
1948 // inner one couldn't be simplified. If it was a constant, then it won't
1949 // be simplified by a later pass either, so we try swapping the inner/outer
1950 // ORs in the hopes that we'll be able to simplify it this way.
1951 // (X|C) | V --> (X|V) | C
1952 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
1953 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
1954 Value *Inner = Builder->CreateOr(A, Op1);
1955 Inner->takeName(Op0);
1956 return BinaryOperator::CreateOr(Inner, C1);
1959 return Changed ? &I : 0;
1962 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1963 bool Changed = SimplifyAssociativeOrCommutative(I);
1964 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1966 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
1967 return ReplaceInstUsesWith(I, V);
1969 if (Instruction *NV = SimplifyDistributed(I)) // (A&B)^(A&C) -> A&(B^C)
1972 // See if we can simplify any instructions used by the instruction whose sole
1973 // purpose is to compute bits we don't care about.
1974 if (SimplifyDemandedInstructionBits(I))
1977 // Is this a ~ operation?
1978 if (Value *NotOp = dyn_castNotVal(&I)) {
1979 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1980 if (Op0I->getOpcode() == Instruction::And ||
1981 Op0I->getOpcode() == Instruction::Or) {
1982 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1983 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1984 if (dyn_castNotVal(Op0I->getOperand(1)))
1985 Op0I->swapOperands();
1986 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1988 Builder->CreateNot(Op0I->getOperand(1),
1989 Op0I->getOperand(1)->getName()+".not");
1990 if (Op0I->getOpcode() == Instruction::And)
1991 return BinaryOperator::CreateOr(Op0NotVal, NotY);
1992 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1995 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1996 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1997 if (isFreeToInvert(Op0I->getOperand(0)) &&
1998 isFreeToInvert(Op0I->getOperand(1))) {
2000 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2002 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2003 if (Op0I->getOpcode() == Instruction::And)
2004 return BinaryOperator::CreateOr(NotX, NotY);
2005 return BinaryOperator::CreateAnd(NotX, NotY);
2008 } else if (Op0I->getOpcode() == Instruction::AShr) {
2009 // ~(~X >>s Y) --> (X >>s Y)
2010 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2011 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2017 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2018 if (RHS->isOne() && Op0->hasOneUse())
2019 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2020 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2021 return CmpInst::Create(CI->getOpcode(),
2022 CI->getInversePredicate(),
2023 CI->getOperand(0), CI->getOperand(1));
2025 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2026 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2027 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2028 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2029 Instruction::CastOps Opcode = Op0C->getOpcode();
2030 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2031 (RHS == ConstantExpr::getCast(Opcode,
2032 ConstantInt::getTrue(I.getContext()),
2033 Op0C->getDestTy()))) {
2034 CI->setPredicate(CI->getInversePredicate());
2035 return CastInst::Create(Opcode, CI, Op0C->getType());
2041 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2042 // ~(c-X) == X-c-1 == X+(-c-1)
2043 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2044 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2045 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2046 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2047 ConstantInt::get(I.getType(), 1));
2048 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2051 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2052 if (Op0I->getOpcode() == Instruction::Add) {
2053 // ~(X-c) --> (-c-1)-X
2054 if (RHS->isAllOnesValue()) {
2055 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2056 return BinaryOperator::CreateSub(
2057 ConstantExpr::getSub(NegOp0CI,
2058 ConstantInt::get(I.getType(), 1)),
2059 Op0I->getOperand(0));
2060 } else if (RHS->getValue().isSignBit()) {
2061 // (X + C) ^ signbit -> (X + C + signbit)
2062 Constant *C = ConstantInt::get(I.getContext(),
2063 RHS->getValue() + Op0CI->getValue());
2064 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2067 } else if (Op0I->getOpcode() == Instruction::Or) {
2068 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2069 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2070 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2071 // Anything in both C1 and C2 is known to be zero, remove it from
2073 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2074 NewRHS = ConstantExpr::getAnd(NewRHS,
2075 ConstantExpr::getNot(CommonBits));
2077 I.setOperand(0, Op0I->getOperand(0));
2078 I.setOperand(1, NewRHS);
2085 // Try to fold constant and into select arguments.
2086 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2087 if (Instruction *R = FoldOpIntoSelect(I, SI))
2089 if (isa<PHINode>(Op0))
2090 if (Instruction *NV = FoldOpIntoPhi(I))
2094 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2097 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2098 if (A == Op0) { // B^(B|A) == (A|B)^B
2099 Op1I->swapOperands();
2101 std::swap(Op0, Op1);
2102 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2103 I.swapOperands(); // Simplified below.
2104 std::swap(Op0, Op1);
2106 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2108 if (A == Op0) { // A^(A&B) -> A^(B&A)
2109 Op1I->swapOperands();
2112 if (B == Op0) { // A^(B&A) -> (B&A)^A
2113 I.swapOperands(); // Simplified below.
2114 std::swap(Op0, Op1);
2119 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2122 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2123 Op0I->hasOneUse()) {
2124 if (A == Op1) // (B|A)^B == (A|B)^B
2126 if (B == Op1) // (A|B)^B == A & ~B
2127 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
2128 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2130 if (A == Op1) // (A&B)^A -> (B&A)^A
2132 if (B == Op1 && // (B&A)^A == ~B & A
2133 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2134 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
2139 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2140 if (Op0I && Op1I && Op0I->isShift() &&
2141 Op0I->getOpcode() == Op1I->getOpcode() &&
2142 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2143 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2145 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2147 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2148 Op1I->getOperand(1));
2152 Value *A, *B, *C, *D;
2153 // (A & B)^(A | B) -> A ^ B
2154 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2155 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2156 if ((A == C && B == D) || (A == D && B == C))
2157 return BinaryOperator::CreateXor(A, B);
2159 // (A | B)^(A & B) -> A ^ B
2160 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2161 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2162 if ((A == C && B == D) || (A == D && B == C))
2163 return BinaryOperator::CreateXor(A, B);
2167 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2168 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2169 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2170 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2171 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2172 LHS->getOperand(1) == RHS->getOperand(0))
2173 LHS->swapOperands();
2174 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2175 LHS->getOperand(1) == RHS->getOperand(1)) {
2176 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2177 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2178 bool isSigned = LHS->isSigned() || RHS->isSigned();
2179 return ReplaceInstUsesWith(I,
2180 getICmpValue(isSigned, Code, Op0, Op1, Builder));
2184 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2185 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2186 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2187 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2188 const Type *SrcTy = Op0C->getOperand(0)->getType();
2189 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2190 // Only do this if the casts both really cause code to be generated.
2191 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2193 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2195 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2196 Op1C->getOperand(0), I.getName());
2197 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2202 return Changed ? &I : 0;