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/Transforms/Utils/CmpInstAnalysis.h"
18 #include "llvm/Support/ConstantRange.h"
19 #include "llvm/Support/PatternMatch.h"
21 using namespace PatternMatch;
24 /// AddOne - Add one to a ConstantInt.
25 static Constant *AddOne(Constant *C) {
26 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
28 /// SubOne - Subtract one from a ConstantInt.
29 static Constant *SubOne(ConstantInt *C) {
30 return ConstantInt::get(C->getContext(), C->getValue()-1);
33 /// isFreeToInvert - Return true if the specified value is free to invert (apply
34 /// ~ to). This happens in cases where the ~ can be eliminated.
35 static inline bool isFreeToInvert(Value *V) {
37 if (BinaryOperator::isNot(V))
40 // Constants can be considered to be not'ed values.
41 if (isa<ConstantInt>(V))
44 // Compares can be inverted if they have a single use.
45 if (CmpInst *CI = dyn_cast<CmpInst>(V))
46 return CI->hasOneUse();
51 static inline Value *dyn_castNotVal(Value *V) {
52 // If this is not(not(x)) don't return that this is a not: we want the two
53 // not's to be folded first.
54 if (BinaryOperator::isNot(V)) {
55 Value *Operand = BinaryOperator::getNotArgument(V);
56 if (!isFreeToInvert(Operand))
60 // Constants can be considered to be not'ed values...
61 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
62 return ConstantInt::get(C->getType(), ~C->getValue());
66 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
67 /// predicate into a three bit mask. It also returns whether it is an ordered
68 /// predicate by reference.
69 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
72 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
73 case FCmpInst::FCMP_UNO: return 0; // 000
74 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
75 case FCmpInst::FCMP_UGT: return 1; // 001
76 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
77 case FCmpInst::FCMP_UEQ: return 2; // 010
78 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
79 case FCmpInst::FCMP_UGE: return 3; // 011
80 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
81 case FCmpInst::FCMP_ULT: return 4; // 100
82 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
83 case FCmpInst::FCMP_UNE: return 5; // 101
84 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
85 case FCmpInst::FCMP_ULE: return 6; // 110
88 // Not expecting FCMP_FALSE and FCMP_TRUE;
89 llvm_unreachable("Unexpected FCmp predicate!");
94 /// getICmpValue - This is the complement of getICmpCode, which turns an
95 /// opcode and two operands into either a constant true or false, or a brand
96 /// new ICmp instruction. The sign is passed in to determine which kind
97 /// of predicate to use in the new icmp instruction.
98 Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
99 InstCombiner::BuilderTy *Builder) {
100 ICmpInst::Predicate NewPred;
101 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
103 return Builder->CreateICmp(NewPred, LHS, RHS);
106 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
107 /// opcode and two operands into either a FCmp instruction. isordered is passed
108 /// in to determine which kind of predicate to use in the new fcmp instruction.
109 static Value *getFCmpValue(bool isordered, unsigned code,
110 Value *LHS, Value *RHS,
111 InstCombiner::BuilderTy *Builder) {
112 CmpInst::Predicate Pred;
114 default: assert(0 && "Illegal FCmp code!");
115 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
116 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
117 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
118 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
119 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
120 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
121 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
123 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
124 Pred = FCmpInst::FCMP_ORD; break;
126 return Builder->CreateFCmp(Pred, LHS, RHS);
129 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
130 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
131 // guaranteed to be a binary operator.
132 Instruction *InstCombiner::OptAndOp(Instruction *Op,
135 BinaryOperator &TheAnd) {
136 Value *X = Op->getOperand(0);
137 Constant *Together = 0;
139 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
141 switch (Op->getOpcode()) {
142 case Instruction::Xor:
143 if (Op->hasOneUse()) {
144 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
145 Value *And = Builder->CreateAnd(X, AndRHS);
147 return BinaryOperator::CreateXor(And, Together);
150 case Instruction::Or:
151 if (Op->hasOneUse()){
152 if (Together != OpRHS) {
153 // (X | C1) & C2 --> (X | (C1&C2)) & C2
154 Value *Or = Builder->CreateOr(X, Together);
156 return BinaryOperator::CreateAnd(Or, AndRHS);
159 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
160 if (TogetherCI && !TogetherCI->isZero()){
161 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
162 // NOTE: This reduces the number of bits set in the & mask, which
163 // can expose opportunities for store narrowing.
164 Together = ConstantExpr::getXor(AndRHS, Together);
165 Value *And = Builder->CreateAnd(X, Together);
167 return BinaryOperator::CreateOr(And, OpRHS);
172 case Instruction::Add:
173 if (Op->hasOneUse()) {
174 // Adding a one to a single bit bit-field should be turned into an XOR
175 // of the bit. First thing to check is to see if this AND is with a
176 // single bit constant.
177 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
179 // If there is only one bit set.
180 if (AndRHSV.isPowerOf2()) {
181 // Ok, at this point, we know that we are masking the result of the
182 // ADD down to exactly one bit. If the constant we are adding has
183 // no bits set below this bit, then we can eliminate the ADD.
184 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
186 // Check to see if any bits below the one bit set in AndRHSV are set.
187 if ((AddRHS & (AndRHSV-1)) == 0) {
188 // If not, the only thing that can effect the output of the AND is
189 // the bit specified by AndRHSV. If that bit is set, the effect of
190 // the XOR is to toggle the bit. If it is clear, then the ADD has
192 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
193 TheAnd.setOperand(0, X);
196 // Pull the XOR out of the AND.
197 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
198 NewAnd->takeName(Op);
199 return BinaryOperator::CreateXor(NewAnd, AndRHS);
206 case Instruction::Shl: {
207 // We know that the AND will not produce any of the bits shifted in, so if
208 // the anded constant includes them, clear them now!
210 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
211 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
212 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
213 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
214 AndRHS->getValue() & ShlMask);
216 if (CI->getValue() == ShlMask)
217 // Masking out bits that the shift already masks.
218 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
220 if (CI != AndRHS) { // Reducing bits set in and.
221 TheAnd.setOperand(1, CI);
226 case Instruction::LShr: {
227 // We know that the AND will not produce any of the bits shifted in, so if
228 // the anded constant includes them, clear them now! This only applies to
229 // unsigned shifts, because a signed shr may bring in set bits!
231 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
232 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
233 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
234 ConstantInt *CI = ConstantInt::get(Op->getContext(),
235 AndRHS->getValue() & ShrMask);
237 if (CI->getValue() == ShrMask)
238 // Masking out bits that the shift already masks.
239 return ReplaceInstUsesWith(TheAnd, Op);
242 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
247 case Instruction::AShr:
249 // See if this is shifting in some sign extension, then masking it out
251 if (Op->hasOneUse()) {
252 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
253 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
254 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
255 Constant *C = ConstantInt::get(Op->getContext(),
256 AndRHS->getValue() & ShrMask);
257 if (C == AndRHS) { // Masking out bits shifted in.
258 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
259 // Make the argument unsigned.
260 Value *ShVal = Op->getOperand(0);
261 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
262 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
271 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
272 /// true, otherwise (V < Lo || V >= Hi). In practice, we emit the more efficient
273 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
274 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
275 /// insert new instructions.
276 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
277 bool isSigned, bool Inside) {
278 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
279 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
280 "Lo is not <= Hi in range emission code!");
283 if (Lo == Hi) // Trivially false.
284 return ConstantInt::getFalse(V->getContext());
286 // V >= Min && V < Hi --> V < Hi
287 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
288 ICmpInst::Predicate pred = (isSigned ?
289 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
290 return Builder->CreateICmp(pred, V, Hi);
293 // Emit V-Lo <u Hi-Lo
294 Constant *NegLo = ConstantExpr::getNeg(Lo);
295 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
296 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
297 return Builder->CreateICmpULT(Add, UpperBound);
300 if (Lo == Hi) // Trivially true.
301 return ConstantInt::getTrue(V->getContext());
303 // V < Min || V >= Hi -> V > Hi-1
304 Hi = SubOne(cast<ConstantInt>(Hi));
305 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
306 ICmpInst::Predicate pred = (isSigned ?
307 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
308 return Builder->CreateICmp(pred, V, Hi);
311 // Emit V-Lo >u Hi-1-Lo
312 // Note that Hi has already had one subtracted from it, above.
313 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
314 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
315 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
316 return Builder->CreateICmpUGT(Add, LowerBound);
319 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
320 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
321 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
322 // not, since all 1s are not contiguous.
323 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
324 const APInt& V = Val->getValue();
325 uint32_t BitWidth = Val->getType()->getBitWidth();
326 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
328 // look for the first zero bit after the run of ones
329 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
330 // look for the first non-zero bit
331 ME = V.getActiveBits();
335 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
336 /// where isSub determines whether the operator is a sub. If we can fold one of
337 /// the following xforms:
339 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
340 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
341 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
343 /// return (A +/- B).
345 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
346 ConstantInt *Mask, bool isSub,
348 Instruction *LHSI = dyn_cast<Instruction>(LHS);
349 if (!LHSI || LHSI->getNumOperands() != 2 ||
350 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
352 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
354 switch (LHSI->getOpcode()) {
356 case Instruction::And:
357 if (ConstantExpr::getAnd(N, Mask) == Mask) {
358 // If the AndRHS is a power of two minus one (0+1+), this is simple.
359 if ((Mask->getValue().countLeadingZeros() +
360 Mask->getValue().countPopulation()) ==
361 Mask->getValue().getBitWidth())
364 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
365 // part, we don't need any explicit masks to take them out of A. If that
366 // is all N is, ignore it.
367 uint32_t MB = 0, ME = 0;
368 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
369 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
370 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
371 if (MaskedValueIsZero(RHS, Mask))
376 case Instruction::Or:
377 case Instruction::Xor:
378 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
379 if ((Mask->getValue().countLeadingZeros() +
380 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
381 && ConstantExpr::getAnd(N, Mask)->isNullValue())
387 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
388 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
391 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
392 /// One of A and B is considered the mask, the other the value. This is
393 /// described as the "AMask" or "BMask" part of the enum. If the enum
394 /// contains only "Mask", then both A and B can be considered masks.
395 /// If A is the mask, then it was proven, that (A & C) == C. This
396 /// is trivial if C == A, or C == 0. If both A and C are constants, this
397 /// proof is also easy.
398 /// For the following explanations we assume that A is the mask.
399 /// The part "AllOnes" declares, that the comparison is true only
400 /// if (A & B) == A, or all bits of A are set in B.
401 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
402 /// The part "AllZeroes" declares, that the comparison is true only
403 /// if (A & B) == 0, or all bits of A are cleared in B.
404 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
405 /// The part "Mixed" declares, that (A & B) == C and C might or might not
406 /// contain any number of one bits and zero bits.
407 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
408 /// The Part "Not" means, that in above descriptions "==" should be replaced
410 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
411 /// If the mask A contains a single bit, then the following is equivalent:
412 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
413 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
414 enum MaskedICmpType {
415 FoldMskICmp_AMask_AllOnes = 1,
416 FoldMskICmp_AMask_NotAllOnes = 2,
417 FoldMskICmp_BMask_AllOnes = 4,
418 FoldMskICmp_BMask_NotAllOnes = 8,
419 FoldMskICmp_Mask_AllZeroes = 16,
420 FoldMskICmp_Mask_NotAllZeroes = 32,
421 FoldMskICmp_AMask_Mixed = 64,
422 FoldMskICmp_AMask_NotMixed = 128,
423 FoldMskICmp_BMask_Mixed = 256,
424 FoldMskICmp_BMask_NotMixed = 512
427 /// return the set of pattern classes (from MaskedICmpType)
428 /// that (icmp SCC (A & B), C) satisfies
429 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
430 ICmpInst::Predicate SCC)
432 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
433 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
434 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
435 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
436 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
437 ACst->getValue().isPowerOf2());
438 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
439 BCst->getValue().isPowerOf2());
441 if (CCst != 0 && CCst->isZero()) {
442 // if C is zero, then both A and B qualify as mask
443 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
444 FoldMskICmp_Mask_AllZeroes |
445 FoldMskICmp_AMask_Mixed |
446 FoldMskICmp_BMask_Mixed)
447 : (FoldMskICmp_Mask_NotAllZeroes |
448 FoldMskICmp_Mask_NotAllZeroes |
449 FoldMskICmp_AMask_NotMixed |
450 FoldMskICmp_BMask_NotMixed));
452 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
453 FoldMskICmp_AMask_NotMixed)
454 : (FoldMskICmp_AMask_AllOnes |
455 FoldMskICmp_AMask_Mixed));
457 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
458 FoldMskICmp_BMask_NotMixed)
459 : (FoldMskICmp_BMask_AllOnes |
460 FoldMskICmp_BMask_Mixed));
464 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
465 FoldMskICmp_AMask_Mixed)
466 : (FoldMskICmp_AMask_NotAllOnes |
467 FoldMskICmp_AMask_NotMixed));
469 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
470 FoldMskICmp_AMask_NotMixed)
471 : (FoldMskICmp_Mask_AllZeroes |
472 FoldMskICmp_AMask_Mixed));
474 else if (ACst != 0 && CCst != 0 &&
475 ConstantExpr::getAnd(ACst, CCst) == CCst) {
476 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
477 : FoldMskICmp_AMask_NotMixed);
481 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
482 FoldMskICmp_BMask_Mixed)
483 : (FoldMskICmp_BMask_NotAllOnes |
484 FoldMskICmp_BMask_NotMixed));
486 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
487 FoldMskICmp_BMask_NotMixed)
488 : (FoldMskICmp_Mask_AllZeroes |
489 FoldMskICmp_BMask_Mixed));
491 else if (BCst != 0 && CCst != 0 &&
492 ConstantExpr::getAnd(BCst, CCst) == CCst) {
493 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
494 : FoldMskICmp_BMask_NotMixed);
499 /// foldLogOpOfMaskedICmpsHelper:
500 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
501 /// return the set of pattern classes (from MaskedICmpType)
502 /// that both LHS and RHS satisfy
503 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
504 Value*& B, Value*& C,
505 Value*& D, Value*& E,
506 ICmpInst *LHS, ICmpInst *RHS) {
507 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
508 if (LHSCC != ICmpInst::ICMP_EQ && LHSCC != ICmpInst::ICMP_NE) return 0;
509 if (RHSCC != ICmpInst::ICMP_EQ && RHSCC != ICmpInst::ICMP_NE) return 0;
510 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
511 // vectors are not (yet?) supported
512 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
514 // Here comes the tricky part:
515 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
516 // and L11 & L12 == L21 & L22. The same goes for RHS.
517 // Now we must find those components L** and R**, that are equal, so
518 // that we can extract the parameters A, B, C, D, and E for the canonical
520 Value *L1 = LHS->getOperand(0);
521 Value *L2 = LHS->getOperand(1);
522 Value *L11,*L12,*L21,*L22;
523 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
524 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
528 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
534 Value *R1 = RHS->getOperand(0);
535 Value *R2 = RHS->getOperand(1);
538 if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
539 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
540 A = R11; D = R12; E = R2; ok = true;
543 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
544 A = R12; D = R11; E = R2; ok = true;
547 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
548 if (R11 != 0 && (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22)) {
549 A = R11; D = R12; E = R1; ok = true;
552 if (R12 != 0 && (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22)) {
553 A = R12; D = R11; E = R1; ok = true;
574 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
575 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
576 return left_type & right_type;
578 /// foldLogOpOfMaskedICmps:
579 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
580 /// into a single (icmp(A & X) ==/!= Y)
581 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
582 ICmpInst::Predicate NEWCC,
583 llvm::InstCombiner::BuilderTy* Builder) {
584 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
585 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS);
586 if (mask == 0) return 0;
588 if (NEWCC == ICmpInst::ICMP_NE)
589 mask >>= 1; // treat "Not"-states as normal states
591 if (mask & FoldMskICmp_Mask_AllZeroes) {
592 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
593 // -> (icmp eq (A & (B|D)), 0)
594 Value* newOr = Builder->CreateOr(B, D);
595 Value* newAnd = Builder->CreateAnd(A, newOr);
596 // we can't use C as zero, because we might actually handle
597 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
598 // with B and D, having a single bit set
599 Value* zero = Constant::getNullValue(A->getType());
600 return Builder->CreateICmp(NEWCC, newAnd, zero);
602 else if (mask & FoldMskICmp_BMask_AllOnes) {
603 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
604 // -> (icmp eq (A & (B|D)), (B|D))
605 Value* newOr = Builder->CreateOr(B, D);
606 Value* newAnd = Builder->CreateAnd(A, newOr);
607 return Builder->CreateICmp(NEWCC, newAnd, newOr);
609 else if (mask & FoldMskICmp_AMask_AllOnes) {
610 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
611 // -> (icmp eq (A & (B&D)), A)
612 Value* newAnd1 = Builder->CreateAnd(B, D);
613 Value* newAnd = Builder->CreateAnd(A, newAnd1);
614 return Builder->CreateICmp(NEWCC, newAnd, A);
616 else if (mask & FoldMskICmp_BMask_Mixed) {
617 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
618 // We already know that B & C == C && D & E == E.
619 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
620 // C and E, which are shared by both the mask B and the mask D, don't
621 // contradict, then we can transform to
622 // -> (icmp eq (A & (B|D)), (C|E))
623 // Currently, we only handle the case of B, C, D, and E being constant.
624 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
625 if (BCst == 0) return 0;
626 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
627 if (DCst == 0) return 0;
628 // we can't simply use C and E, because we might actually handle
629 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
630 // with B and D, having a single bit set
632 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
633 if (CCst == 0) return 0;
634 if (LHS->getPredicate() != NEWCC)
635 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
636 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
637 if (ECst == 0) return 0;
638 if (RHS->getPredicate() != NEWCC)
639 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
640 ConstantInt* MCst = dyn_cast<ConstantInt>(
641 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
642 ConstantExpr::getXor(CCst, ECst)) );
643 // if there is a conflict we should actually return a false for the
647 Value *newOr1 = Builder->CreateOr(B, D);
648 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
649 Value *newAnd = Builder->CreateAnd(A, newOr1);
650 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
655 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
656 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
657 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
659 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
660 if (PredicatesFoldable(LHSCC, RHSCC)) {
661 if (LHS->getOperand(0) == RHS->getOperand(1) &&
662 LHS->getOperand(1) == RHS->getOperand(0))
664 if (LHS->getOperand(0) == RHS->getOperand(0) &&
665 LHS->getOperand(1) == RHS->getOperand(1)) {
666 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
667 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
668 bool isSigned = LHS->isSigned() || RHS->isSigned();
669 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
673 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
674 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
677 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
678 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
679 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
680 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
681 if (LHSCst == 0 || RHSCst == 0) return 0;
683 if (LHSCst == RHSCst && LHSCC == RHSCC) {
684 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
685 // where C is a power of 2
686 if (LHSCC == ICmpInst::ICMP_ULT &&
687 LHSCst->getValue().isPowerOf2()) {
688 Value *NewOr = Builder->CreateOr(Val, Val2);
689 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
692 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
693 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
694 Value *NewOr = Builder->CreateOr(Val, Val2);
695 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
698 // (icmp slt A, 0) & (icmp slt B, 0) --> (icmp slt (A&B), 0)
699 if (LHSCC == ICmpInst::ICMP_SLT && LHSCst->isZero()) {
700 Value *NewAnd = Builder->CreateAnd(Val, Val2);
701 return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
704 // (icmp sgt A, -1) & (icmp sgt B, -1) --> (icmp sgt (A|B), -1)
705 if (LHSCC == ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
706 Value *NewOr = Builder->CreateOr(Val, Val2);
707 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
711 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
712 // where CMAX is the all ones value for the truncated type,
713 // iff the lower bits of C2 and CA are zero.
714 if (LHSCC == RHSCC && ICmpInst::isEquality(LHSCC) &&
715 LHS->hasOneUse() && RHS->hasOneUse()) {
717 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
719 // (trunc x) == C1 & (and x, CA) == C2
720 if (match(Val2, m_Trunc(m_Value(V))) &&
721 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
725 // (and x, CA) == C2 & (trunc x) == C1
726 else if (match(Val, m_Trunc(m_Value(V))) &&
727 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
732 if (SmallCst && BigCst) {
733 unsigned BigBitSize = BigCst->getType()->getBitWidth();
734 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
736 // Check that the low bits are zero.
737 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
738 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
739 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
740 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
741 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
742 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
747 // From here on, we only handle:
748 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
749 if (Val != Val2) return 0;
751 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
752 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
753 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
754 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
755 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
758 // Make a constant range that's the intersection of the two icmp ranges.
759 // If the intersection is empty, we know that the result is false.
760 ConstantRange LHSRange =
761 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
762 ConstantRange RHSRange =
763 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
765 if (LHSRange.intersectWith(RHSRange).isEmptySet())
766 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
768 // We can't fold (ugt x, C) & (sgt x, C2).
769 if (!PredicatesFoldable(LHSCC, RHSCC))
772 // Ensure that the larger constant is on the RHS.
774 if (CmpInst::isSigned(LHSCC) ||
775 (ICmpInst::isEquality(LHSCC) &&
776 CmpInst::isSigned(RHSCC)))
777 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
779 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
783 std::swap(LHSCst, RHSCst);
784 std::swap(LHSCC, RHSCC);
787 // At this point, we know we have two icmp instructions
788 // comparing a value against two constants and and'ing the result
789 // together. Because of the above check, we know that we only have
790 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
791 // (from the icmp folding check above), that the two constants
792 // are not equal and that the larger constant is on the RHS
793 assert(LHSCst != RHSCst && "Compares not folded above?");
796 default: llvm_unreachable("Unknown integer condition code!");
797 case ICmpInst::ICMP_EQ:
799 default: llvm_unreachable("Unknown integer condition code!");
800 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
801 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
802 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
805 case ICmpInst::ICMP_NE:
807 default: llvm_unreachable("Unknown integer condition code!");
808 case ICmpInst::ICMP_ULT:
809 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
810 return Builder->CreateICmpULT(Val, LHSCst);
811 break; // (X != 13 & X u< 15) -> no change
812 case ICmpInst::ICMP_SLT:
813 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
814 return Builder->CreateICmpSLT(Val, LHSCst);
815 break; // (X != 13 & X s< 15) -> no change
816 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
817 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
818 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
820 case ICmpInst::ICMP_NE:
821 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
822 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
823 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
824 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
826 break; // (X != 13 & X != 15) -> no change
829 case ICmpInst::ICMP_ULT:
831 default: llvm_unreachable("Unknown integer condition code!");
832 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
833 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
834 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
835 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
837 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
838 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
840 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
844 case ICmpInst::ICMP_SLT:
846 default: llvm_unreachable("Unknown integer condition code!");
847 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
849 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
850 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
852 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
856 case ICmpInst::ICMP_UGT:
858 default: llvm_unreachable("Unknown integer condition code!");
859 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
860 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
862 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
864 case ICmpInst::ICMP_NE:
865 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
866 return Builder->CreateICmp(LHSCC, Val, RHSCst);
867 break; // (X u> 13 & X != 15) -> no change
868 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
869 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
870 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
874 case ICmpInst::ICMP_SGT:
876 default: llvm_unreachable("Unknown integer condition code!");
877 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
878 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
880 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
882 case ICmpInst::ICMP_NE:
883 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
884 return Builder->CreateICmp(LHSCC, Val, RHSCst);
885 break; // (X s> 13 & X != 15) -> no change
886 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
887 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
888 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
897 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
898 /// instcombine, this returns a Value which should already be inserted into the
900 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
901 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
902 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
903 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
904 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
905 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
906 // If either of the constants are nans, then the whole thing returns
908 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
909 return ConstantInt::getFalse(LHS->getContext());
910 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
913 // Handle vector zeros. This occurs because the canonical form of
914 // "fcmp ord x,x" is "fcmp ord x, 0".
915 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
916 isa<ConstantAggregateZero>(RHS->getOperand(1)))
917 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
921 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
922 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
923 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
926 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
927 // Swap RHS operands to match LHS.
928 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
929 std::swap(Op1LHS, Op1RHS);
932 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
933 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
935 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
936 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
937 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
938 if (Op0CC == FCmpInst::FCMP_TRUE)
940 if (Op1CC == FCmpInst::FCMP_TRUE)
945 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
946 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
949 std::swap(Op0Pred, Op1Pred);
950 std::swap(Op0Ordered, Op1Ordered);
953 // uno && ueq -> uno && (uno || eq) -> ueq
954 // ord && olt -> ord && (ord && lt) -> olt
955 if (Op0Ordered == Op1Ordered)
958 // uno && oeq -> uno && (ord && eq) -> false
959 // uno && ord -> false
961 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
962 // ord && ueq -> ord && (uno || eq) -> oeq
963 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
971 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
972 bool Changed = SimplifyAssociativeOrCommutative(I);
973 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
975 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
976 return ReplaceInstUsesWith(I, V);
978 // (A|B)&(A|C) -> A|(B&C) etc
979 if (Value *V = SimplifyUsingDistributiveLaws(I))
980 return ReplaceInstUsesWith(I, V);
982 // See if we can simplify any instructions used by the instruction whose sole
983 // purpose is to compute bits we don't care about.
984 if (SimplifyDemandedInstructionBits(I))
987 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
988 const APInt &AndRHSMask = AndRHS->getValue();
990 // Optimize a variety of ((val OP C1) & C2) combinations...
991 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
992 Value *Op0LHS = Op0I->getOperand(0);
993 Value *Op0RHS = Op0I->getOperand(1);
994 switch (Op0I->getOpcode()) {
996 case Instruction::Xor:
997 case Instruction::Or: {
998 // If the mask is only needed on one incoming arm, push it up.
999 if (!Op0I->hasOneUse()) break;
1001 APInt NotAndRHS(~AndRHSMask);
1002 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1003 // Not masking anything out for the LHS, move to RHS.
1004 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1005 Op0RHS->getName()+".masked");
1006 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1008 if (!isa<Constant>(Op0RHS) &&
1009 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1010 // Not masking anything out for the RHS, move to LHS.
1011 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1012 Op0LHS->getName()+".masked");
1013 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1018 case Instruction::Add:
1019 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1020 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1021 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1022 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1023 return BinaryOperator::CreateAnd(V, AndRHS);
1024 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1025 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1028 case Instruction::Sub:
1029 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1030 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1031 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1032 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1033 return BinaryOperator::CreateAnd(V, AndRHS);
1035 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1036 // has 1's for all bits that the subtraction with A might affect.
1037 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1038 uint32_t BitWidth = AndRHSMask.getBitWidth();
1039 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1040 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1042 if (MaskedValueIsZero(Op0LHS, Mask)) {
1043 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1044 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1049 case Instruction::Shl:
1050 case Instruction::LShr:
1051 // (1 << x) & 1 --> zext(x == 0)
1052 // (1 >> x) & 1 --> zext(x == 0)
1053 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1055 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1056 return new ZExtInst(NewICmp, I.getType());
1061 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1062 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1066 // If this is an integer truncation, and if the source is an 'and' with
1067 // immediate, transform it. This frequently occurs for bitfield accesses.
1069 Value *X = 0; ConstantInt *YC = 0;
1070 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1071 // Change: and (trunc (and X, YC) to T), C2
1072 // into : and (trunc X to T), trunc(YC) & C2
1073 // This will fold the two constants together, which may allow
1074 // other simplifications.
1075 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1076 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1077 C3 = ConstantExpr::getAnd(C3, AndRHS);
1078 return BinaryOperator::CreateAnd(NewCast, C3);
1082 // Try to fold constant and into select arguments.
1083 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1084 if (Instruction *R = FoldOpIntoSelect(I, SI))
1086 if (isa<PHINode>(Op0))
1087 if (Instruction *NV = FoldOpIntoPhi(I))
1092 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1093 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1094 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1095 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1096 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1097 I.getName()+".demorgan");
1098 return BinaryOperator::CreateNot(Or);
1102 Value *A = 0, *B = 0, *C = 0, *D = 0;
1103 // (A|B) & ~(A&B) -> A^B
1104 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1105 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1106 ((A == C && B == D) || (A == D && B == C)))
1107 return BinaryOperator::CreateXor(A, B);
1109 // ~(A&B) & (A|B) -> A^B
1110 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1111 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1112 ((A == C && B == D) || (A == D && B == C)))
1113 return BinaryOperator::CreateXor(A, B);
1115 // A&(A^B) => A & ~B
1117 Value *tmpOp0 = Op0;
1118 Value *tmpOp1 = Op1;
1119 if (Op0->hasOneUse() &&
1120 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1121 if (A == Op1 || B == Op1 ) {
1128 if (tmpOp1->hasOneUse() &&
1129 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1133 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1134 // A is originally -1 (or a vector of -1 and undefs), then we enter
1135 // an endless loop. By checking that A is non-constant we ensure that
1136 // we will never get to the loop.
1137 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1138 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1142 // (A&((~A)|B)) -> A&B
1143 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1144 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1145 return BinaryOperator::CreateAnd(A, Op1);
1146 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1147 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1148 return BinaryOperator::CreateAnd(A, Op0);
1151 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1152 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1153 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1154 return ReplaceInstUsesWith(I, Res);
1156 // If and'ing two fcmp, try combine them into one.
1157 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1158 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1159 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1160 return ReplaceInstUsesWith(I, Res);
1163 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1164 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1165 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1166 Type *SrcTy = Op0C->getOperand(0)->getType();
1167 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1168 SrcTy == Op1C->getOperand(0)->getType() &&
1169 SrcTy->isIntOrIntVectorTy()) {
1170 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1172 // Only do this if the casts both really cause code to be generated.
1173 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1174 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1175 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1176 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1179 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1180 // cast is otherwise not optimizable. This happens for vector sexts.
1181 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1182 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1183 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1184 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1186 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1187 // cast is otherwise not optimizable. This happens for vector sexts.
1188 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1189 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1190 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1191 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1195 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1196 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1197 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1198 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1199 SI0->getOperand(1) == SI1->getOperand(1) &&
1200 (SI0->hasOneUse() || SI1->hasOneUse())) {
1202 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1204 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1205 SI1->getOperand(1));
1209 return Changed ? &I : 0;
1212 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1213 /// capable of providing pieces of a bswap. The subexpression provides pieces
1214 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1215 /// the expression came from the corresponding "byte swapped" byte in some other
1216 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1217 /// we know that the expression deposits the low byte of %X into the high byte
1218 /// of the bswap result and that all other bytes are zero. This expression is
1219 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1222 /// This function returns true if the match was unsuccessful and false if so.
1223 /// On entry to the function the "OverallLeftShift" is a signed integer value
1224 /// indicating the number of bytes that the subexpression is later shifted. For
1225 /// example, if the expression is later right shifted by 16 bits, the
1226 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1227 /// byte of ByteValues is actually being set.
1229 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1230 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1231 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1232 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1233 /// always in the local (OverallLeftShift) coordinate space.
1235 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1236 SmallVector<Value*, 8> &ByteValues) {
1237 if (Instruction *I = dyn_cast<Instruction>(V)) {
1238 // If this is an or instruction, it may be an inner node of the bswap.
1239 if (I->getOpcode() == Instruction::Or) {
1240 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1242 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1246 // If this is a logical shift by a constant multiple of 8, recurse with
1247 // OverallLeftShift and ByteMask adjusted.
1248 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1250 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1251 // Ensure the shift amount is defined and of a byte value.
1252 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1255 unsigned ByteShift = ShAmt >> 3;
1256 if (I->getOpcode() == Instruction::Shl) {
1257 // X << 2 -> collect(X, +2)
1258 OverallLeftShift += ByteShift;
1259 ByteMask >>= ByteShift;
1261 // X >>u 2 -> collect(X, -2)
1262 OverallLeftShift -= ByteShift;
1263 ByteMask <<= ByteShift;
1264 ByteMask &= (~0U >> (32-ByteValues.size()));
1267 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1268 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1270 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1274 // If this is a logical 'and' with a mask that clears bytes, clear the
1275 // corresponding bytes in ByteMask.
1276 if (I->getOpcode() == Instruction::And &&
1277 isa<ConstantInt>(I->getOperand(1))) {
1278 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1279 unsigned NumBytes = ByteValues.size();
1280 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1281 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1283 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1284 // If this byte is masked out by a later operation, we don't care what
1286 if ((ByteMask & (1 << i)) == 0)
1289 // If the AndMask is all zeros for this byte, clear the bit.
1290 APInt MaskB = AndMask & Byte;
1292 ByteMask &= ~(1U << i);
1296 // If the AndMask is not all ones for this byte, it's not a bytezap.
1300 // Otherwise, this byte is kept.
1303 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1308 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1309 // the input value to the bswap. Some observations: 1) if more than one byte
1310 // is demanded from this input, then it could not be successfully assembled
1311 // into a byteswap. At least one of the two bytes would not be aligned with
1312 // their ultimate destination.
1313 if (!isPowerOf2_32(ByteMask)) return true;
1314 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1316 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1317 // is demanded, it needs to go into byte 0 of the result. This means that the
1318 // byte needs to be shifted until it lands in the right byte bucket. The
1319 // shift amount depends on the position: if the byte is coming from the high
1320 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1321 // low part, it must be shifted left.
1322 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1323 if (InputByteNo < ByteValues.size()/2) {
1324 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1327 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1331 // If the destination byte value is already defined, the values are or'd
1332 // together, which isn't a bswap (unless it's an or of the same bits).
1333 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1335 ByteValues[DestByteNo] = V;
1339 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1340 /// If so, insert the new bswap intrinsic and return it.
1341 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1342 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1343 if (!ITy || ITy->getBitWidth() % 16 ||
1344 // ByteMask only allows up to 32-byte values.
1345 ITy->getBitWidth() > 32*8)
1346 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1348 /// ByteValues - For each byte of the result, we keep track of which value
1349 /// defines each byte.
1350 SmallVector<Value*, 8> ByteValues;
1351 ByteValues.resize(ITy->getBitWidth()/8);
1353 // Try to find all the pieces corresponding to the bswap.
1354 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1355 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1358 // Check to see if all of the bytes come from the same value.
1359 Value *V = ByteValues[0];
1360 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1362 // Check to make sure that all of the bytes come from the same value.
1363 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1364 if (ByteValues[i] != V)
1366 Module *M = I.getParent()->getParent()->getParent();
1367 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1368 return CallInst::Create(F, V);
1371 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1372 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1373 /// we can simplify this expression to "cond ? C : D or B".
1374 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1375 Value *C, Value *D) {
1376 // If A is not a select of -1/0, this cannot match.
1378 if (!match(A, m_SExt(m_Value(Cond))) ||
1379 !Cond->getType()->isIntegerTy(1))
1382 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1383 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1384 return SelectInst::Create(Cond, C, B);
1385 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1386 return SelectInst::Create(Cond, C, B);
1388 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1389 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1390 return SelectInst::Create(Cond, C, D);
1391 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1392 return SelectInst::Create(Cond, C, D);
1396 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1397 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1398 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1400 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1401 if (PredicatesFoldable(LHSCC, RHSCC)) {
1402 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1403 LHS->getOperand(1) == RHS->getOperand(0))
1404 LHS->swapOperands();
1405 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1406 LHS->getOperand(1) == RHS->getOperand(1)) {
1407 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1408 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1409 bool isSigned = LHS->isSigned() || RHS->isSigned();
1410 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1414 // handle (roughly):
1415 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1416 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1419 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1420 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1421 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1422 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1423 if (LHSCst == 0 || RHSCst == 0) return 0;
1425 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1426 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1427 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1428 Value *NewOr = Builder->CreateOr(Val, Val2);
1429 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1432 // (icmp slt A, 0) | (icmp slt B, 0) --> (icmp slt (A|B), 0)
1433 if (LHSCC == ICmpInst::ICMP_SLT && LHSCst->isZero()) {
1434 Value *NewOr = Builder->CreateOr(Val, Val2);
1435 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1438 // (icmp sgt A, -1) | (icmp sgt B, -1) --> (icmp sgt (A&B), -1)
1439 if (LHSCC == ICmpInst::ICMP_SGT && LHSCst->isAllOnesValue()) {
1440 Value *NewAnd = Builder->CreateAnd(Val, Val2);
1441 return Builder->CreateICmp(LHSCC, NewAnd, LHSCst);
1445 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1446 // iff C2 + CA == C1.
1447 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1448 ConstantInt *AddCst;
1449 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1450 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1451 return Builder->CreateICmpULE(Val, 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 // (A&B)|(A&C) -> A&(B|C) etc
1699 if (Value *V = SimplifyUsingDistributiveLaws(I))
1700 return ReplaceInstUsesWith(I, V);
1702 // See if we can simplify any instructions used by the instruction whose sole
1703 // purpose is to compute bits we don't care about.
1704 if (SimplifyDemandedInstructionBits(I))
1707 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1708 ConstantInt *C1 = 0; Value *X = 0;
1709 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1710 // iff (C1 & C2) == 0.
1711 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1712 (RHS->getValue() & C1->getValue()) != 0 &&
1714 Value *Or = Builder->CreateOr(X, RHS);
1716 return BinaryOperator::CreateAnd(Or,
1717 ConstantInt::get(I.getContext(),
1718 RHS->getValue() | C1->getValue()));
1721 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1722 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1724 Value *Or = Builder->CreateOr(X, RHS);
1726 return BinaryOperator::CreateXor(Or,
1727 ConstantInt::get(I.getContext(),
1728 C1->getValue() & ~RHS->getValue()));
1731 // Try to fold constant and into select arguments.
1732 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1733 if (Instruction *R = FoldOpIntoSelect(I, SI))
1736 if (isa<PHINode>(Op0))
1737 if (Instruction *NV = FoldOpIntoPhi(I))
1741 Value *A = 0, *B = 0;
1742 ConstantInt *C1 = 0, *C2 = 0;
1744 // (A | B) | C and A | (B | C) -> bswap if possible.
1745 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1746 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1747 match(Op1, m_Or(m_Value(), m_Value())) ||
1748 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1749 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1750 if (Instruction *BSwap = MatchBSwap(I))
1754 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1755 if (Op0->hasOneUse() &&
1756 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1757 MaskedValueIsZero(Op1, C1->getValue())) {
1758 Value *NOr = Builder->CreateOr(A, Op1);
1760 return BinaryOperator::CreateXor(NOr, C1);
1763 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1764 if (Op1->hasOneUse() &&
1765 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1766 MaskedValueIsZero(Op0, C1->getValue())) {
1767 Value *NOr = Builder->CreateOr(A, Op0);
1769 return BinaryOperator::CreateXor(NOr, C1);
1773 Value *C = 0, *D = 0;
1774 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1775 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1776 Value *V1 = 0, *V2 = 0;
1777 C1 = dyn_cast<ConstantInt>(C);
1778 C2 = dyn_cast<ConstantInt>(D);
1779 if (C1 && C2) { // (A & C1)|(B & C2)
1780 // If we have: ((V + N) & C1) | (V & C2)
1781 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1782 // replace with V+N.
1783 if (C1->getValue() == ~C2->getValue()) {
1784 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1785 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1786 // Add commutes, try both ways.
1787 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1788 return ReplaceInstUsesWith(I, A);
1789 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1790 return ReplaceInstUsesWith(I, A);
1792 // Or commutes, try both ways.
1793 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1794 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1795 // Add commutes, try both ways.
1796 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1797 return ReplaceInstUsesWith(I, B);
1798 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1799 return ReplaceInstUsesWith(I, B);
1803 if ((C1->getValue() & C2->getValue()) == 0) {
1804 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1805 // iff (C1&C2) == 0 and (N&~C1) == 0
1806 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1807 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1808 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1809 return BinaryOperator::CreateAnd(A,
1810 ConstantInt::get(A->getContext(),
1811 C1->getValue()|C2->getValue()));
1812 // Or commutes, try both ways.
1813 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1814 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1815 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1816 return BinaryOperator::CreateAnd(B,
1817 ConstantInt::get(B->getContext(),
1818 C1->getValue()|C2->getValue()));
1820 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1821 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1822 ConstantInt *C3 = 0, *C4 = 0;
1823 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1824 (C3->getValue() & ~C1->getValue()) == 0 &&
1825 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1826 (C4->getValue() & ~C2->getValue()) == 0) {
1827 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1828 return BinaryOperator::CreateAnd(V2,
1829 ConstantInt::get(B->getContext(),
1830 C1->getValue()|C2->getValue()));
1835 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1836 // Don't do this for vector select idioms, the code generator doesn't handle
1838 if (!I.getType()->isVectorTy()) {
1839 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1841 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1843 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1845 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1849 // ((A&~B)|(~A&B)) -> A^B
1850 if ((match(C, m_Not(m_Specific(D))) &&
1851 match(B, m_Not(m_Specific(A)))))
1852 return BinaryOperator::CreateXor(A, D);
1853 // ((~B&A)|(~A&B)) -> A^B
1854 if ((match(A, m_Not(m_Specific(D))) &&
1855 match(B, m_Not(m_Specific(C)))))
1856 return BinaryOperator::CreateXor(C, D);
1857 // ((A&~B)|(B&~A)) -> A^B
1858 if ((match(C, m_Not(m_Specific(B))) &&
1859 match(D, m_Not(m_Specific(A)))))
1860 return BinaryOperator::CreateXor(A, B);
1861 // ((~B&A)|(B&~A)) -> A^B
1862 if ((match(A, m_Not(m_Specific(B))) &&
1863 match(D, m_Not(m_Specific(C)))))
1864 return BinaryOperator::CreateXor(C, B);
1866 // ((A|B)&1)|(B&-2) -> (A&1) | B
1867 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1868 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1869 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1870 if (Ret) return Ret;
1872 // (B&-2)|((A|B)&1) -> (A&1) | B
1873 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1874 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1875 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1876 if (Ret) return Ret;
1880 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1881 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1882 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1883 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1884 SI0->getOperand(1) == SI1->getOperand(1) &&
1885 (SI0->hasOneUse() || SI1->hasOneUse())) {
1886 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1888 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1889 SI1->getOperand(1));
1893 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1894 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1895 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1896 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1897 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1898 I.getName()+".demorgan");
1899 return BinaryOperator::CreateNot(And);
1902 // Canonicalize xor to the RHS.
1903 if (match(Op0, m_Xor(m_Value(), m_Value())))
1904 std::swap(Op0, Op1);
1906 // A | ( A ^ B) -> A | B
1907 // A | (~A ^ B) -> A | ~B
1908 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1909 if (Op0 == A || Op0 == B)
1910 return BinaryOperator::CreateOr(A, B);
1912 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1913 Value *Not = Builder->CreateNot(B, B->getName()+".not");
1914 return BinaryOperator::CreateOr(Not, Op0);
1916 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1917 Value *Not = Builder->CreateNot(A, A->getName()+".not");
1918 return BinaryOperator::CreateOr(Not, Op0);
1922 // A | ~(A | B) -> A | ~B
1923 // A | ~(A ^ B) -> A | ~B
1924 if (match(Op1, m_Not(m_Value(A))))
1925 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
1926 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1927 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1928 B->getOpcode() == Instruction::Xor)) {
1929 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1931 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
1932 return BinaryOperator::CreateOr(Not, Op0);
1935 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1936 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1937 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1938 return ReplaceInstUsesWith(I, Res);
1940 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1941 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1942 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1943 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1944 return ReplaceInstUsesWith(I, Res);
1946 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1947 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1948 CastInst *Op1C = dyn_cast<CastInst>(Op1);
1949 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1950 Type *SrcTy = Op0C->getOperand(0)->getType();
1951 if (SrcTy == Op1C->getOperand(0)->getType() &&
1952 SrcTy->isIntOrIntVectorTy()) {
1953 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1955 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1956 // Only do this if the casts both really cause code to be
1958 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1959 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1960 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1961 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1964 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1965 // cast is otherwise not optimizable. This happens for vector sexts.
1966 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1967 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1968 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1969 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1971 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1972 // cast is otherwise not optimizable. This happens for vector sexts.
1973 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1974 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1975 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1976 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1981 // or(sext(A), B) -> A ? -1 : B where A is an i1
1982 // or(A, sext(B)) -> B ? -1 : A where B is an i1
1983 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
1984 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
1985 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
1986 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
1988 // Note: If we've gotten to the point of visiting the outer OR, then the
1989 // inner one couldn't be simplified. If it was a constant, then it won't
1990 // be simplified by a later pass either, so we try swapping the inner/outer
1991 // ORs in the hopes that we'll be able to simplify it this way.
1992 // (X|C) | V --> (X|V) | C
1993 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
1994 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
1995 Value *Inner = Builder->CreateOr(A, Op1);
1996 Inner->takeName(Op0);
1997 return BinaryOperator::CreateOr(Inner, C1);
2000 return Changed ? &I : 0;
2003 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2004 bool Changed = SimplifyAssociativeOrCommutative(I);
2005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2007 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2008 return ReplaceInstUsesWith(I, V);
2010 // (A&B)^(A&C) -> A&(B^C) etc
2011 if (Value *V = SimplifyUsingDistributiveLaws(I))
2012 return ReplaceInstUsesWith(I, V);
2014 // See if we can simplify any instructions used by the instruction whose sole
2015 // purpose is to compute bits we don't care about.
2016 if (SimplifyDemandedInstructionBits(I))
2019 // Is this a ~ operation?
2020 if (Value *NotOp = dyn_castNotVal(&I)) {
2021 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2022 if (Op0I->getOpcode() == Instruction::And ||
2023 Op0I->getOpcode() == Instruction::Or) {
2024 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2025 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2026 if (dyn_castNotVal(Op0I->getOperand(1)))
2027 Op0I->swapOperands();
2028 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2030 Builder->CreateNot(Op0I->getOperand(1),
2031 Op0I->getOperand(1)->getName()+".not");
2032 if (Op0I->getOpcode() == Instruction::And)
2033 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2034 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2037 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2038 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2039 if (isFreeToInvert(Op0I->getOperand(0)) &&
2040 isFreeToInvert(Op0I->getOperand(1))) {
2042 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2044 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2045 if (Op0I->getOpcode() == Instruction::And)
2046 return BinaryOperator::CreateOr(NotX, NotY);
2047 return BinaryOperator::CreateAnd(NotX, NotY);
2050 } else if (Op0I->getOpcode() == Instruction::AShr) {
2051 // ~(~X >>s Y) --> (X >>s Y)
2052 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2053 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2059 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2060 if (RHS->isOne() && Op0->hasOneUse())
2061 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2062 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2063 return CmpInst::Create(CI->getOpcode(),
2064 CI->getInversePredicate(),
2065 CI->getOperand(0), CI->getOperand(1));
2067 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2068 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2069 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2070 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2071 Instruction::CastOps Opcode = Op0C->getOpcode();
2072 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2073 (RHS == ConstantExpr::getCast(Opcode,
2074 ConstantInt::getTrue(I.getContext()),
2075 Op0C->getDestTy()))) {
2076 CI->setPredicate(CI->getInversePredicate());
2077 return CastInst::Create(Opcode, CI, Op0C->getType());
2083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2084 // ~(c-X) == X-c-1 == X+(-c-1)
2085 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2086 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2087 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2088 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2089 ConstantInt::get(I.getType(), 1));
2090 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2093 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2094 if (Op0I->getOpcode() == Instruction::Add) {
2095 // ~(X-c) --> (-c-1)-X
2096 if (RHS->isAllOnesValue()) {
2097 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2098 return BinaryOperator::CreateSub(
2099 ConstantExpr::getSub(NegOp0CI,
2100 ConstantInt::get(I.getType(), 1)),
2101 Op0I->getOperand(0));
2102 } else if (RHS->getValue().isSignBit()) {
2103 // (X + C) ^ signbit -> (X + C + signbit)
2104 Constant *C = ConstantInt::get(I.getContext(),
2105 RHS->getValue() + Op0CI->getValue());
2106 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2109 } else if (Op0I->getOpcode() == Instruction::Or) {
2110 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2111 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2112 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2113 // Anything in both C1 and C2 is known to be zero, remove it from
2115 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2116 NewRHS = ConstantExpr::getAnd(NewRHS,
2117 ConstantExpr::getNot(CommonBits));
2119 I.setOperand(0, Op0I->getOperand(0));
2120 I.setOperand(1, NewRHS);
2127 // Try to fold constant and into select arguments.
2128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2129 if (Instruction *R = FoldOpIntoSelect(I, SI))
2131 if (isa<PHINode>(Op0))
2132 if (Instruction *NV = FoldOpIntoPhi(I))
2136 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2139 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2140 if (A == Op0) { // B^(B|A) == (A|B)^B
2141 Op1I->swapOperands();
2143 std::swap(Op0, Op1);
2144 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2145 I.swapOperands(); // Simplified below.
2146 std::swap(Op0, Op1);
2148 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2150 if (A == Op0) { // A^(A&B) -> A^(B&A)
2151 Op1I->swapOperands();
2154 if (B == Op0) { // A^(B&A) -> (B&A)^A
2155 I.swapOperands(); // Simplified below.
2156 std::swap(Op0, Op1);
2161 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2164 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2165 Op0I->hasOneUse()) {
2166 if (A == Op1) // (B|A)^B == (A|B)^B
2168 if (B == Op1) // (A|B)^B == A & ~B
2169 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2170 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2172 if (A == Op1) // (A&B)^A -> (B&A)^A
2174 if (B == Op1 && // (B&A)^A == ~B & A
2175 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2176 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2181 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2182 if (Op0I && Op1I && Op0I->isShift() &&
2183 Op0I->getOpcode() == Op1I->getOpcode() &&
2184 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2185 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2187 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2189 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2190 Op1I->getOperand(1));
2194 Value *A, *B, *C, *D;
2195 // (A & B)^(A | B) -> A ^ B
2196 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2197 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2198 if ((A == C && B == D) || (A == D && B == C))
2199 return BinaryOperator::CreateXor(A, B);
2201 // (A | B)^(A & B) -> A ^ B
2202 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2203 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2204 if ((A == C && B == D) || (A == D && B == C))
2205 return BinaryOperator::CreateXor(A, B);
2209 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2210 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2211 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2212 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2213 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2214 LHS->getOperand(1) == RHS->getOperand(0))
2215 LHS->swapOperands();
2216 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2217 LHS->getOperand(1) == RHS->getOperand(1)) {
2218 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2219 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2220 bool isSigned = LHS->isSigned() || RHS->isSigned();
2221 return ReplaceInstUsesWith(I,
2222 getNewICmpValue(isSigned, Code, Op0, Op1,
2227 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2228 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2229 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2230 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2231 Type *SrcTy = Op0C->getOperand(0)->getType();
2232 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2233 // Only do this if the casts both really cause code to be generated.
2234 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2236 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2238 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2239 Op1C->getOperand(0), I.getName());
2240 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2245 return Changed ? &I : 0;