Grammo.
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineAndOrXor.cpp
1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitAnd, visitOr, and visitXor functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombine.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/Support/ConstantRange.h"
18 #include "llvm/Support/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
20 using namespace llvm;
21 using namespace PatternMatch;
22
23
24 /// AddOne - Add one to a ConstantInt.
25 static Constant *AddOne(Constant *C) {
26   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
27 }
28 /// SubOne - Subtract one from a ConstantInt.
29 static Constant *SubOne(ConstantInt *C) {
30   return ConstantInt::get(C->getContext(), C->getValue()-1);
31 }
32
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) {
36   // ~(~(X)) -> X.
37   if (BinaryOperator::isNot(V))
38     return true;
39
40   // Constants can be considered to be not'ed values.
41   if (isa<ConstantInt>(V))
42     return true;
43
44   // Compares can be inverted if they have a single use.
45   if (CmpInst *CI = dyn_cast<CmpInst>(V))
46     return CI->hasOneUse();
47
48   return false;
49 }
50
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))
57       return Operand;
58   }
59
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());
63   return 0;
64 }
65
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) {
70   isOrdered = false;
71   switch (CC) {
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
86     // True -> 7
87   default:
88     // Not expecting FCMP_FALSE and FCMP_TRUE;
89     llvm_unreachable("Unexpected FCmp predicate!");
90   }
91 }
92
93 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
94 /// opcode and two operands into either a constant true or false, or a brand
95 /// new ICmp instruction. The sign is passed in to determine which kind
96 /// of predicate to use in the new icmp instruction.
97 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
98                               InstCombiner::BuilderTy *Builder) {
99   ICmpInst::Predicate NewPred;
100   if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
101     return NewConstant;
102   return Builder->CreateICmp(NewPred, LHS, RHS);
103 }
104
105 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
106 /// opcode and two operands into either a FCmp instruction. isordered is passed
107 /// in to determine which kind of predicate to use in the new fcmp instruction.
108 static Value *getFCmpValue(bool isordered, unsigned code,
109                            Value *LHS, Value *RHS,
110                            InstCombiner::BuilderTy *Builder) {
111   CmpInst::Predicate Pred;
112   switch (code) {
113   default: llvm_unreachable("Illegal FCmp code!");
114   case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
115   case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
116   case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
117   case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
118   case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
119   case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
120   case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
121   case 7:
122     if (!isordered) return ConstantInt::getTrue(LHS->getContext());
123     Pred = FCmpInst::FCMP_ORD; break;
124   }
125   return Builder->CreateFCmp(Pred, LHS, RHS);
126 }
127
128 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
129 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
130 // guaranteed to be a binary operator.
131 Instruction *InstCombiner::OptAndOp(Instruction *Op,
132                                     ConstantInt *OpRHS,
133                                     ConstantInt *AndRHS,
134                                     BinaryOperator &TheAnd) {
135   Value *X = Op->getOperand(0);
136   Constant *Together = 0;
137   if (!Op->isShift())
138     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
139
140   switch (Op->getOpcode()) {
141   case Instruction::Xor:
142     if (Op->hasOneUse()) {
143       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
144       Value *And = Builder->CreateAnd(X, AndRHS);
145       And->takeName(Op);
146       return BinaryOperator::CreateXor(And, Together);
147     }
148     break;
149   case Instruction::Or:
150     if (Op->hasOneUse()){
151       if (Together != OpRHS) {
152         // (X | C1) & C2 --> (X | (C1&C2)) & C2
153         Value *Or = Builder->CreateOr(X, Together);
154         Or->takeName(Op);
155         return BinaryOperator::CreateAnd(Or, AndRHS);
156       }
157
158       ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
159       if (TogetherCI && !TogetherCI->isZero()){
160         // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
161         // NOTE: This reduces the number of bits set in the & mask, which
162         // can expose opportunities for store narrowing.
163         Together = ConstantExpr::getXor(AndRHS, Together);
164         Value *And = Builder->CreateAnd(X, Together);
165         And->takeName(Op);
166         return BinaryOperator::CreateOr(And, OpRHS);
167       }
168     }
169
170     break;
171   case Instruction::Add:
172     if (Op->hasOneUse()) {
173       // Adding a one to a single bit bit-field should be turned into an XOR
174       // of the bit.  First thing to check is to see if this AND is with a
175       // single bit constant.
176       const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
177
178       // If there is only one bit set.
179       if (AndRHSV.isPowerOf2()) {
180         // Ok, at this point, we know that we are masking the result of the
181         // ADD down to exactly one bit.  If the constant we are adding has
182         // no bits set below this bit, then we can eliminate the ADD.
183         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
184
185         // Check to see if any bits below the one bit set in AndRHSV are set.
186         if ((AddRHS & (AndRHSV-1)) == 0) {
187           // If not, the only thing that can effect the output of the AND is
188           // the bit specified by AndRHSV.  If that bit is set, the effect of
189           // the XOR is to toggle the bit.  If it is clear, then the ADD has
190           // no effect.
191           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
192             TheAnd.setOperand(0, X);
193             return &TheAnd;
194           } else {
195             // Pull the XOR out of the AND.
196             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
197             NewAnd->takeName(Op);
198             return BinaryOperator::CreateXor(NewAnd, AndRHS);
199           }
200         }
201       }
202     }
203     break;
204
205   case Instruction::Shl: {
206     // We know that the AND will not produce any of the bits shifted in, so if
207     // the anded constant includes them, clear them now!
208     //
209     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
210     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
211     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
212     ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
213                                        AndRHS->getValue() & ShlMask);
214
215     if (CI->getValue() == ShlMask)
216       // Masking out bits that the shift already masks.
217       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
218
219     if (CI != AndRHS) {                  // Reducing bits set in and.
220       TheAnd.setOperand(1, CI);
221       return &TheAnd;
222     }
223     break;
224   }
225   case Instruction::LShr: {
226     // We know that the AND will not produce any of the bits shifted in, so if
227     // the anded constant includes them, clear them now!  This only applies to
228     // unsigned shifts, because a signed shr may bring in set bits!
229     //
230     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
231     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
232     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
233     ConstantInt *CI = ConstantInt::get(Op->getContext(),
234                                        AndRHS->getValue() & ShrMask);
235
236     if (CI->getValue() == ShrMask)
237       // Masking out bits that the shift already masks.
238       return ReplaceInstUsesWith(TheAnd, Op);
239
240     if (CI != AndRHS) {
241       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
242       return &TheAnd;
243     }
244     break;
245   }
246   case Instruction::AShr:
247     // Signed shr.
248     // See if this is shifting in some sign extension, then masking it out
249     // with an and.
250     if (Op->hasOneUse()) {
251       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
252       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
253       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
254       Constant *C = ConstantInt::get(Op->getContext(),
255                                      AndRHS->getValue() & ShrMask);
256       if (C == AndRHS) {          // Masking out bits shifted in.
257         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
258         // Make the argument unsigned.
259         Value *ShVal = Op->getOperand(0);
260         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
261         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
262       }
263     }
264     break;
265   }
266   return 0;
267 }
268
269
270 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
271 /// true, otherwise (V < Lo || V >= Hi).  In practice, we emit the more efficient
272 /// (V-Lo) \<u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
273 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
274 /// insert new instructions.
275 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
276                                      bool isSigned, bool Inside) {
277   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
278             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
279          "Lo is not <= Hi in range emission code!");
280
281   if (Inside) {
282     if (Lo == Hi)  // Trivially false.
283       return ConstantInt::getFalse(V->getContext());
284
285     // V >= Min && V < Hi --> V < Hi
286     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
287       ICmpInst::Predicate pred = (isSigned ?
288         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
289       return Builder->CreateICmp(pred, V, Hi);
290     }
291
292     // Emit V-Lo <u Hi-Lo
293     Constant *NegLo = ConstantExpr::getNeg(Lo);
294     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
295     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
296     return Builder->CreateICmpULT(Add, UpperBound);
297   }
298
299   if (Lo == Hi)  // Trivially true.
300     return ConstantInt::getTrue(V->getContext());
301
302   // V < Min || V >= Hi -> V > Hi-1
303   Hi = SubOne(cast<ConstantInt>(Hi));
304   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
305     ICmpInst::Predicate pred = (isSigned ?
306         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
307     return Builder->CreateICmp(pred, V, Hi);
308   }
309
310   // Emit V-Lo >u Hi-1-Lo
311   // Note that Hi has already had one subtracted from it, above.
312   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
313   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
314   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
315   return Builder->CreateICmpUGT(Add, LowerBound);
316 }
317
318 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
319 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
320 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
321 // not, since all 1s are not contiguous.
322 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
323   const APInt& V = Val->getValue();
324   uint32_t BitWidth = Val->getType()->getBitWidth();
325   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
326
327   // look for the first zero bit after the run of ones
328   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
329   // look for the first non-zero bit
330   ME = V.getActiveBits();
331   return true;
332 }
333
334 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
335 /// where isSub determines whether the operator is a sub.  If we can fold one of
336 /// the following xforms:
337 ///
338 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
339 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
340 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
341 ///
342 /// return (A +/- B).
343 ///
344 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
345                                         ConstantInt *Mask, bool isSub,
346                                         Instruction &I) {
347   Instruction *LHSI = dyn_cast<Instruction>(LHS);
348   if (!LHSI || LHSI->getNumOperands() != 2 ||
349       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
350
351   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
352
353   switch (LHSI->getOpcode()) {
354   default: return 0;
355   case Instruction::And:
356     if (ConstantExpr::getAnd(N, Mask) == Mask) {
357       // If the AndRHS is a power of two minus one (0+1+), this is simple.
358       if ((Mask->getValue().countLeadingZeros() +
359            Mask->getValue().countPopulation()) ==
360           Mask->getValue().getBitWidth())
361         break;
362
363       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
364       // part, we don't need any explicit masks to take them out of A.  If that
365       // is all N is, ignore it.
366       uint32_t MB = 0, ME = 0;
367       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
368         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
369         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
370         if (MaskedValueIsZero(RHS, Mask))
371           break;
372       }
373     }
374     return 0;
375   case Instruction::Or:
376   case Instruction::Xor:
377     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
378     if ((Mask->getValue().countLeadingZeros() +
379          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
380         && ConstantExpr::getAnd(N, Mask)->isNullValue())
381       break;
382     return 0;
383   }
384
385   if (isSub)
386     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
387   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
388 }
389
390 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
391 /// One of A and B is considered the mask, the other the value. This is
392 /// described as the "AMask" or "BMask" part of the enum. If the enum
393 /// contains only "Mask", then both A and B can be considered masks.
394 /// If A is the mask, then it was proven, that (A & C) == C. This
395 /// is trivial if C == A, or C == 0. If both A and C are constants, this
396 /// proof is also easy.
397 /// For the following explanations we assume that A is the mask.
398 /// The part "AllOnes" declares, that the comparison is true only
399 /// if (A & B) == A, or all bits of A are set in B.
400 ///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
401 /// The part "AllZeroes" declares, that the comparison is true only
402 /// if (A & B) == 0, or all bits of A are cleared in B.
403 ///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
404 /// The part "Mixed" declares, that (A & B) == C and C might or might not
405 /// contain any number of one bits and zero bits.
406 ///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
407 /// The Part "Not" means, that in above descriptions "==" should be replaced
408 /// by "!=".
409 ///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
410 /// If the mask A contains a single bit, then the following is equivalent:
411 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
412 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
413 enum MaskedICmpType {
414   FoldMskICmp_AMask_AllOnes           =     1,
415   FoldMskICmp_AMask_NotAllOnes        =     2,
416   FoldMskICmp_BMask_AllOnes           =     4,
417   FoldMskICmp_BMask_NotAllOnes        =     8,
418   FoldMskICmp_Mask_AllZeroes          =    16,
419   FoldMskICmp_Mask_NotAllZeroes       =    32,
420   FoldMskICmp_AMask_Mixed             =    64,
421   FoldMskICmp_AMask_NotMixed          =   128,
422   FoldMskICmp_BMask_Mixed             =   256,
423   FoldMskICmp_BMask_NotMixed          =   512
424 };
425
426 /// return the set of pattern classes (from MaskedICmpType)
427 /// that (icmp SCC (A & B), C) satisfies
428 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
429                                     ICmpInst::Predicate SCC)
430 {
431   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
432   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
433   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
434   bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
435   bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
436                     ACst->getValue().isPowerOf2());
437   bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
438                     BCst->getValue().isPowerOf2());
439   unsigned result = 0;
440   if (CCst != 0 && CCst->isZero()) {
441     // if C is zero, then both A and B qualify as mask
442     result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
443                           FoldMskICmp_Mask_AllZeroes |
444                           FoldMskICmp_AMask_Mixed |
445                           FoldMskICmp_BMask_Mixed)
446                        : (FoldMskICmp_Mask_NotAllZeroes |
447                           FoldMskICmp_Mask_NotAllZeroes |
448                           FoldMskICmp_AMask_NotMixed |
449                           FoldMskICmp_BMask_NotMixed));
450     if (icmp_abit)
451       result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
452                             FoldMskICmp_AMask_NotMixed)
453                          : (FoldMskICmp_AMask_AllOnes |
454                             FoldMskICmp_AMask_Mixed));
455     if (icmp_bbit)
456       result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
457                             FoldMskICmp_BMask_NotMixed)
458                          : (FoldMskICmp_BMask_AllOnes |
459                             FoldMskICmp_BMask_Mixed));
460     return result;
461   }
462   if (A == C) {
463     result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
464                           FoldMskICmp_AMask_Mixed)
465                        : (FoldMskICmp_AMask_NotAllOnes |
466                           FoldMskICmp_AMask_NotMixed));
467     if (icmp_abit)
468       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
469                             FoldMskICmp_AMask_NotMixed)
470                          : (FoldMskICmp_Mask_AllZeroes |
471                             FoldMskICmp_AMask_Mixed));
472   } else if (ACst != 0 && CCst != 0 &&
473              ConstantExpr::getAnd(ACst, CCst) == CCst) {
474     result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
475                        : FoldMskICmp_AMask_NotMixed);
476   }
477   if (B == C) {
478     result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
479                           FoldMskICmp_BMask_Mixed)
480                        : (FoldMskICmp_BMask_NotAllOnes |
481                           FoldMskICmp_BMask_NotMixed));
482     if (icmp_bbit)
483       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
484                             FoldMskICmp_BMask_NotMixed)
485                          : (FoldMskICmp_Mask_AllZeroes |
486                             FoldMskICmp_BMask_Mixed));
487   } else if (BCst != 0 && CCst != 0 &&
488              ConstantExpr::getAnd(BCst, CCst) == CCst) {
489     result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
490                        : FoldMskICmp_BMask_NotMixed);
491   }
492   return result;
493 }
494
495 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
496 /// if possible. The returned predicate is either == or !=. Returns false if
497 /// decomposition fails.
498 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
499                                  Value *&X, Value *&Y, Value *&Z) {
500   // X < 0 is equivalent to (X & SignBit) != 0.
501   if (I->getPredicate() == ICmpInst::ICMP_SLT)
502     if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
503       if (C->isZero()) {
504         X = I->getOperand(0);
505         Y = ConstantInt::get(I->getContext(),
506                              APInt::getSignBit(C->getBitWidth()));
507         Pred = ICmpInst::ICMP_NE;
508         Z = C;
509         return true;
510       }
511
512   // X > -1 is equivalent to (X & SignBit) == 0.
513   if (I->getPredicate() == ICmpInst::ICMP_SGT)
514     if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
515       if (C->isAllOnesValue()) {
516         X = I->getOperand(0);
517         Y = ConstantInt::get(I->getContext(),
518                              APInt::getSignBit(C->getBitWidth()));
519         Pred = ICmpInst::ICMP_EQ;
520         Z = ConstantInt::getNullValue(C->getType());
521         return true;
522       }
523
524   return false;
525 }
526
527 /// foldLogOpOfMaskedICmpsHelper:
528 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
529 /// return the set of pattern classes (from MaskedICmpType)
530 /// that both LHS and RHS satisfy
531 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
532                                              Value*& B, Value*& C,
533                                              Value*& D, Value*& E,
534                                              ICmpInst *LHS, ICmpInst *RHS,
535                                              ICmpInst::Predicate &LHSCC,
536                                              ICmpInst::Predicate &RHSCC) {
537   if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
538   // vectors are not (yet?) supported
539   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
540
541   // Here comes the tricky part:
542   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
543   // and L11 & L12 == L21 & L22. The same goes for RHS.
544   // Now we must find those components L** and R**, that are equal, so
545   // that we can extract the parameters A, B, C, D, and E for the canonical
546   // above.
547   Value *L1 = LHS->getOperand(0);
548   Value *L2 = LHS->getOperand(1);
549   Value *L11,*L12,*L21,*L22;
550   // Check whether the icmp can be decomposed into a bit test.
551   if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
552     L21 = L22 = L1 = 0;
553   } else {
554     // Look for ANDs in the LHS icmp.
555     if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
556       if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
557         L21 = L22 = 0;
558     } else {
559       if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
560         return 0;
561       std::swap(L1, L2);
562       L21 = L22 = 0;
563     }
564   }
565
566   // Bail if LHS was a icmp that can't be decomposed into an equality.
567   if (!ICmpInst::isEquality(LHSCC))
568     return 0;
569
570   Value *R1 = RHS->getOperand(0);
571   Value *R2 = RHS->getOperand(1);
572   Value *R11,*R12;
573   bool ok = false;
574   if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
575     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
576       A = R11; D = R12;
577     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
578       A = R12; D = R11;
579     } else {
580       return 0;
581     }
582     E = R2; R1 = 0; ok = true;
583   } else if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
584     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
585       A = R11; D = R12; E = R2; ok = true;
586     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
587       A = R12; D = R11; E = R2; ok = true;
588     }
589   }
590
591   // Bail if RHS was a icmp that can't be decomposed into an equality.
592   if (!ICmpInst::isEquality(RHSCC))
593     return 0;
594
595   // Look for ANDs in on the right side of the RHS icmp.
596   if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
597     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
598       A = R11; D = R12; E = R1; ok = true;
599     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
600       A = R12; D = R11; E = R1; ok = true;
601     } else {
602       return 0;
603     }
604   }
605   if (!ok)
606     return 0;
607
608   if (L11 == A) {
609     B = L12; C = L2;
610   } else if (L12 == A) {
611     B = L11; C = L2;
612   } else if (L21 == A) {
613     B = L22; C = L1;
614   } else if (L22 == A) {
615     B = L21; C = L1;
616   }
617
618   unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
619   unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
620   return left_type & right_type;
621 }
622 /// foldLogOpOfMaskedICmps:
623 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
624 /// into a single (icmp(A & X) ==/!= Y)
625 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
626                                      ICmpInst::Predicate NEWCC,
627                                      llvm::InstCombiner::BuilderTy* Builder) {
628   Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
629   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
630   unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
631                                                LHSCC, RHSCC);
632   if (mask == 0) return 0;
633   assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
634          "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
635
636   if (NEWCC == ICmpInst::ICMP_NE)
637     mask >>= 1; // treat "Not"-states as normal states
638
639   if (mask & FoldMskICmp_Mask_AllZeroes) {
640     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
641     // -> (icmp eq (A & (B|D)), 0)
642     Value* newOr = Builder->CreateOr(B, D);
643     Value* newAnd = Builder->CreateAnd(A, newOr);
644     // we can't use C as zero, because we might actually handle
645     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
646     // with B and D, having a single bit set
647     Value* zero = Constant::getNullValue(A->getType());
648     return Builder->CreateICmp(NEWCC, newAnd, zero);
649   }
650   if (mask & FoldMskICmp_BMask_AllOnes) {
651     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
652     // -> (icmp eq (A & (B|D)), (B|D))
653     Value* newOr = Builder->CreateOr(B, D);
654     Value* newAnd = Builder->CreateAnd(A, newOr);
655     return Builder->CreateICmp(NEWCC, newAnd, newOr);
656   }
657   if (mask & FoldMskICmp_AMask_AllOnes) {
658     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
659     // -> (icmp eq (A & (B&D)), A)
660     Value* newAnd1 = Builder->CreateAnd(B, D);
661     Value* newAnd = Builder->CreateAnd(A, newAnd1);
662     return Builder->CreateICmp(NEWCC, newAnd, A);
663   }
664   if (mask & FoldMskICmp_BMask_Mixed) {
665     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
666     // We already know that B & C == C && D & E == E.
667     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
668     // C and E, which are shared by both the mask B and the mask D, don't
669     // contradict, then we can transform to
670     // -> (icmp eq (A & (B|D)), (C|E))
671     // Currently, we only handle the case of B, C, D, and E being constant.
672     ConstantInt *BCst = dyn_cast<ConstantInt>(B);
673     if (BCst == 0) return 0;
674     ConstantInt *DCst = dyn_cast<ConstantInt>(D);
675     if (DCst == 0) return 0;
676     // we can't simply use C and E, because we might actually handle
677     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
678     // with B and D, having a single bit set
679
680     ConstantInt *CCst = dyn_cast<ConstantInt>(C);
681     if (CCst == 0) return 0;
682     if (LHSCC != NEWCC)
683       CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
684     ConstantInt *ECst = dyn_cast<ConstantInt>(E);
685     if (ECst == 0) return 0;
686     if (RHSCC != NEWCC)
687       ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
688     ConstantInt* MCst = dyn_cast<ConstantInt>(
689       ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
690                            ConstantExpr::getXor(CCst, ECst)) );
691     // if there is a conflict we should actually return a false for the
692     // whole construct
693     if (!MCst->isZero())
694       return 0;
695     Value *newOr1 = Builder->CreateOr(B, D);
696     Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
697     Value *newAnd = Builder->CreateAnd(A, newOr1);
698     return Builder->CreateICmp(NEWCC, newAnd, newOr2);
699   }
700   return 0;
701 }
702
703 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
704 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
705   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
706
707   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
708   if (PredicatesFoldable(LHSCC, RHSCC)) {
709     if (LHS->getOperand(0) == RHS->getOperand(1) &&
710         LHS->getOperand(1) == RHS->getOperand(0))
711       LHS->swapOperands();
712     if (LHS->getOperand(0) == RHS->getOperand(0) &&
713         LHS->getOperand(1) == RHS->getOperand(1)) {
714       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
715       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
716       bool isSigned = LHS->isSigned() || RHS->isSigned();
717       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
718     }
719   }
720
721   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
722   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
723     return V;
724
725   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
726   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
727   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
728   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
729   if (LHSCst == 0 || RHSCst == 0) return 0;
730
731   if (LHSCst == RHSCst && LHSCC == RHSCC) {
732     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
733     // where C is a power of 2
734     if (LHSCC == ICmpInst::ICMP_ULT &&
735         LHSCst->getValue().isPowerOf2()) {
736       Value *NewOr = Builder->CreateOr(Val, Val2);
737       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
738     }
739
740     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
741     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
742       Value *NewOr = Builder->CreateOr(Val, Val2);
743       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
744     }
745   }
746
747   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
748   // where CMAX is the all ones value for the truncated type,
749   // iff the lower bits of C2 and CA are zero.
750   if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
751       LHS->hasOneUse() && RHS->hasOneUse()) {
752     Value *V;
753     ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
754
755     // (trunc x) == C1 & (and x, CA) == C2
756     // (and x, CA) == C2 & (trunc x) == C1
757     if (match(Val2, m_Trunc(m_Value(V))) &&
758         match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
759       SmallCst = RHSCst;
760       BigCst = LHSCst;
761     } else if (match(Val, m_Trunc(m_Value(V))) &&
762                match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
763       SmallCst = LHSCst;
764       BigCst = RHSCst;
765     }
766
767     if (SmallCst && BigCst) {
768       unsigned BigBitSize = BigCst->getType()->getBitWidth();
769       unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
770
771       // Check that the low bits are zero.
772       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
773       if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
774         Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
775         APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
776         Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
777         return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
778       }
779     }
780   }
781
782   // From here on, we only handle:
783   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
784   if (Val != Val2) return 0;
785
786   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
787   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
788       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
789       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
790       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
791     return 0;
792
793   // Make a constant range that's the intersection of the two icmp ranges.
794   // If the intersection is empty, we know that the result is false.
795   ConstantRange LHSRange =
796     ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
797   ConstantRange RHSRange =
798     ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
799
800   if (LHSRange.intersectWith(RHSRange).isEmptySet())
801     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
802
803   // We can't fold (ugt x, C) & (sgt x, C2).
804   if (!PredicatesFoldable(LHSCC, RHSCC))
805     return 0;
806
807   // Ensure that the larger constant is on the RHS.
808   bool ShouldSwap;
809   if (CmpInst::isSigned(LHSCC) ||
810       (ICmpInst::isEquality(LHSCC) &&
811        CmpInst::isSigned(RHSCC)))
812     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
813   else
814     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
815
816   if (ShouldSwap) {
817     std::swap(LHS, RHS);
818     std::swap(LHSCst, RHSCst);
819     std::swap(LHSCC, RHSCC);
820   }
821
822   // At this point, we know we have two icmp instructions
823   // comparing a value against two constants and and'ing the result
824   // together.  Because of the above check, we know that we only have
825   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
826   // (from the icmp folding check above), that the two constants
827   // are not equal and that the larger constant is on the RHS
828   assert(LHSCst != RHSCst && "Compares not folded above?");
829
830   switch (LHSCC) {
831   default: llvm_unreachable("Unknown integer condition code!");
832   case ICmpInst::ICMP_EQ:
833     switch (RHSCC) {
834     default: llvm_unreachable("Unknown integer condition code!");
835     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
836     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
837     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
838       return LHS;
839     }
840   case ICmpInst::ICMP_NE:
841     switch (RHSCC) {
842     default: llvm_unreachable("Unknown integer condition code!");
843     case ICmpInst::ICMP_ULT:
844       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
845         return Builder->CreateICmpULT(Val, LHSCst);
846       break;                        // (X != 13 & X u< 15) -> no change
847     case ICmpInst::ICMP_SLT:
848       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
849         return Builder->CreateICmpSLT(Val, LHSCst);
850       break;                        // (X != 13 & X s< 15) -> no change
851     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
852     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
853     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
854       return RHS;
855     case ICmpInst::ICMP_NE:
856       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
857         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
858         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
859         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
860       }
861       break;                        // (X != 13 & X != 15) -> no change
862     }
863     break;
864   case ICmpInst::ICMP_ULT:
865     switch (RHSCC) {
866     default: llvm_unreachable("Unknown integer condition code!");
867     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
868     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
869       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
870     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
871       break;
872     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
873     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
874       return LHS;
875     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
876       break;
877     }
878     break;
879   case ICmpInst::ICMP_SLT:
880     switch (RHSCC) {
881     default: llvm_unreachable("Unknown integer condition code!");
882     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
883       break;
884     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
885     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
886       return LHS;
887     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
888       break;
889     }
890     break;
891   case ICmpInst::ICMP_UGT:
892     switch (RHSCC) {
893     default: llvm_unreachable("Unknown integer condition code!");
894     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
895     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
896       return RHS;
897     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
898       break;
899     case ICmpInst::ICMP_NE:
900       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
901         return Builder->CreateICmp(LHSCC, Val, RHSCst);
902       break;                        // (X u> 13 & X != 15) -> no change
903     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
904       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
905     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
906       break;
907     }
908     break;
909   case ICmpInst::ICMP_SGT:
910     switch (RHSCC) {
911     default: llvm_unreachable("Unknown integer condition code!");
912     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
913     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
914       return RHS;
915     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
916       break;
917     case ICmpInst::ICMP_NE:
918       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
919         return Builder->CreateICmp(LHSCC, Val, RHSCst);
920       break;                        // (X s> 13 & X != 15) -> no change
921     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
922       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
923     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
924       break;
925     }
926     break;
927   }
928
929   return 0;
930 }
931
932 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
933 /// instcombine, this returns a Value which should already be inserted into the
934 /// function.
935 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
936   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
937       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
938     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
939     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
940       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
941         // If either of the constants are nans, then the whole thing returns
942         // false.
943         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
944           return ConstantInt::getFalse(LHS->getContext());
945         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
946       }
947
948     // Handle vector zeros.  This occurs because the canonical form of
949     // "fcmp ord x,x" is "fcmp ord x, 0".
950     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
951         isa<ConstantAggregateZero>(RHS->getOperand(1)))
952       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
953     return 0;
954   }
955
956   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
957   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
958   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
959
960
961   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
962     // Swap RHS operands to match LHS.
963     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
964     std::swap(Op1LHS, Op1RHS);
965   }
966
967   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
968     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
969     if (Op0CC == Op1CC)
970       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
971     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
972       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
973     if (Op0CC == FCmpInst::FCMP_TRUE)
974       return RHS;
975     if (Op1CC == FCmpInst::FCMP_TRUE)
976       return LHS;
977
978     bool Op0Ordered;
979     bool Op1Ordered;
980     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
981     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
982     // uno && ord -> false
983     if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
984         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
985     if (Op1Pred == 0) {
986       std::swap(LHS, RHS);
987       std::swap(Op0Pred, Op1Pred);
988       std::swap(Op0Ordered, Op1Ordered);
989     }
990     if (Op0Pred == 0) {
991       // uno && ueq -> uno && (uno || eq) -> uno
992       // ord && olt -> ord && (ord && lt) -> olt
993       if (!Op0Ordered && (Op0Ordered == Op1Ordered))
994         return LHS;
995       if (Op0Ordered && (Op0Ordered == Op1Ordered))
996         return RHS;
997
998       // uno && oeq -> uno && (ord && eq) -> false
999       if (!Op0Ordered)
1000         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1001       // ord && ueq -> ord && (uno || eq) -> oeq
1002       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1003     }
1004   }
1005
1006   return 0;
1007 }
1008
1009
1010 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1011   bool Changed = SimplifyAssociativeOrCommutative(I);
1012   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1013
1014   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1015     return ReplaceInstUsesWith(I, V);
1016
1017   // (A|B)&(A|C) -> A|(B&C) etc
1018   if (Value *V = SimplifyUsingDistributiveLaws(I))
1019     return ReplaceInstUsesWith(I, V);
1020
1021   // See if we can simplify any instructions used by the instruction whose sole
1022   // purpose is to compute bits we don't care about.
1023   if (SimplifyDemandedInstructionBits(I))
1024     return &I;
1025
1026   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1027     const APInt &AndRHSMask = AndRHS->getValue();
1028
1029     // Optimize a variety of ((val OP C1) & C2) combinations...
1030     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1031       Value *Op0LHS = Op0I->getOperand(0);
1032       Value *Op0RHS = Op0I->getOperand(1);
1033       switch (Op0I->getOpcode()) {
1034       default: break;
1035       case Instruction::Xor:
1036       case Instruction::Or: {
1037         // If the mask is only needed on one incoming arm, push it up.
1038         if (!Op0I->hasOneUse()) break;
1039
1040         APInt NotAndRHS(~AndRHSMask);
1041         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1042           // Not masking anything out for the LHS, move to RHS.
1043           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1044                                              Op0RHS->getName()+".masked");
1045           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1046         }
1047         if (!isa<Constant>(Op0RHS) &&
1048             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1049           // Not masking anything out for the RHS, move to LHS.
1050           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1051                                              Op0LHS->getName()+".masked");
1052           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1053         }
1054
1055         break;
1056       }
1057       case Instruction::Add:
1058         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1059         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1060         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1061         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1062           return BinaryOperator::CreateAnd(V, AndRHS);
1063         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1064           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1065         break;
1066
1067       case Instruction::Sub:
1068         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1069         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1070         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1071         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1072           return BinaryOperator::CreateAnd(V, AndRHS);
1073
1074         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1075         // has 1's for all bits that the subtraction with A might affect.
1076         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1077           uint32_t BitWidth = AndRHSMask.getBitWidth();
1078           uint32_t Zeros = AndRHSMask.countLeadingZeros();
1079           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1080
1081           if (MaskedValueIsZero(Op0LHS, Mask)) {
1082             Value *NewNeg = Builder->CreateNeg(Op0RHS);
1083             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1084           }
1085         }
1086         break;
1087
1088       case Instruction::Shl:
1089       case Instruction::LShr:
1090         // (1 << x) & 1 --> zext(x == 0)
1091         // (1 >> x) & 1 --> zext(x == 0)
1092         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1093           Value *NewICmp =
1094             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1095           return new ZExtInst(NewICmp, I.getType());
1096         }
1097         break;
1098       }
1099
1100       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1101         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1102           return Res;
1103     }
1104
1105     // If this is an integer truncation, and if the source is an 'and' with
1106     // immediate, transform it.  This frequently occurs for bitfield accesses.
1107     {
1108       Value *X = 0; ConstantInt *YC = 0;
1109       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1110         // Change: and (trunc (and X, YC) to T), C2
1111         // into  : and (trunc X to T), trunc(YC) & C2
1112         // This will fold the two constants together, which may allow
1113         // other simplifications.
1114         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1115         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1116         C3 = ConstantExpr::getAnd(C3, AndRHS);
1117         return BinaryOperator::CreateAnd(NewCast, C3);
1118       }
1119     }
1120
1121     // Try to fold constant and into select arguments.
1122     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1123       if (Instruction *R = FoldOpIntoSelect(I, SI))
1124         return R;
1125     if (isa<PHINode>(Op0))
1126       if (Instruction *NV = FoldOpIntoPhi(I))
1127         return NV;
1128   }
1129
1130
1131   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1132   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1133     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1134       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1135         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1136                                       I.getName()+".demorgan");
1137         return BinaryOperator::CreateNot(Or);
1138       }
1139
1140   {
1141     Value *A = 0, *B = 0, *C = 0, *D = 0;
1142     // (A|B) & ~(A&B) -> A^B
1143     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1144         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1145         ((A == C && B == D) || (A == D && B == C)))
1146       return BinaryOperator::CreateXor(A, B);
1147
1148     // ~(A&B) & (A|B) -> A^B
1149     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1150         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1151         ((A == C && B == D) || (A == D && B == C)))
1152       return BinaryOperator::CreateXor(A, B);
1153
1154     // A&(A^B) => A & ~B
1155     {
1156       Value *tmpOp0 = Op0;
1157       Value *tmpOp1 = Op1;
1158       if (Op0->hasOneUse() &&
1159           match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1160         if (A == Op1 || B == Op1 ) {
1161           tmpOp1 = Op0;
1162           tmpOp0 = Op1;
1163           // Simplify below
1164         }
1165       }
1166
1167       if (tmpOp1->hasOneUse() &&
1168           match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1169         if (B == tmpOp0) {
1170           std::swap(A, B);
1171         }
1172         // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1173         // A is originally -1 (or a vector of -1 and undefs), then we enter
1174         // an endless loop. By checking that A is non-constant we ensure that
1175         // we will never get to the loop.
1176         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1177           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1178       }
1179     }
1180
1181     // (A&((~A)|B)) -> A&B
1182     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1183         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1184       return BinaryOperator::CreateAnd(A, Op1);
1185     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1186         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1187       return BinaryOperator::CreateAnd(A, Op0);
1188   }
1189
1190   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1191     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1192       if (Value *Res = FoldAndOfICmps(LHS, RHS))
1193         return ReplaceInstUsesWith(I, Res);
1194
1195   // If and'ing two fcmp, try combine them into one.
1196   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1197     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1198       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1199         return ReplaceInstUsesWith(I, Res);
1200
1201
1202   // fold (and (cast A), (cast B)) -> (cast (and A, B))
1203   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1204     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1205       Type *SrcTy = Op0C->getOperand(0)->getType();
1206       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1207           SrcTy == Op1C->getOperand(0)->getType() &&
1208           SrcTy->isIntOrIntVectorTy()) {
1209         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1210
1211         // Only do this if the casts both really cause code to be generated.
1212         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1213             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1214           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1215           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1216         }
1217
1218         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1219         // cast is otherwise not optimizable.  This happens for vector sexts.
1220         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1221           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1222             if (Value *Res = FoldAndOfICmps(LHS, RHS))
1223               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1224
1225         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1226         // cast is otherwise not optimizable.  This happens for vector sexts.
1227         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1228           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1229             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1230               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1231       }
1232     }
1233
1234   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
1235   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1236     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1237       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1238           SI0->getOperand(1) == SI1->getOperand(1) &&
1239           (SI0->hasOneUse() || SI1->hasOneUse())) {
1240         Value *NewOp =
1241           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1242                              SI0->getName());
1243         return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1244                                       SI1->getOperand(1));
1245       }
1246   }
1247
1248   return Changed ? &I : 0;
1249 }
1250
1251 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1252 /// capable of providing pieces of a bswap.  The subexpression provides pieces
1253 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1254 /// the expression came from the corresponding "byte swapped" byte in some other
1255 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
1256 /// we know that the expression deposits the low byte of %X into the high byte
1257 /// of the bswap result and that all other bytes are zero.  This expression is
1258 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1259 /// match.
1260 ///
1261 /// This function returns true if the match was unsuccessful and false if so.
1262 /// On entry to the function the "OverallLeftShift" is a signed integer value
1263 /// indicating the number of bytes that the subexpression is later shifted.  For
1264 /// example, if the expression is later right shifted by 16 bits, the
1265 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
1266 /// byte of ByteValues is actually being set.
1267 ///
1268 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1269 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
1270 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
1271 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
1272 /// always in the local (OverallLeftShift) coordinate space.
1273 ///
1274 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1275                               SmallVector<Value*, 8> &ByteValues) {
1276   if (Instruction *I = dyn_cast<Instruction>(V)) {
1277     // If this is an or instruction, it may be an inner node of the bswap.
1278     if (I->getOpcode() == Instruction::Or) {
1279       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1280                                ByteValues) ||
1281              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1282                                ByteValues);
1283     }
1284
1285     // If this is a logical shift by a constant multiple of 8, recurse with
1286     // OverallLeftShift and ByteMask adjusted.
1287     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1288       unsigned ShAmt =
1289         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1290       // Ensure the shift amount is defined and of a byte value.
1291       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1292         return true;
1293
1294       unsigned ByteShift = ShAmt >> 3;
1295       if (I->getOpcode() == Instruction::Shl) {
1296         // X << 2 -> collect(X, +2)
1297         OverallLeftShift += ByteShift;
1298         ByteMask >>= ByteShift;
1299       } else {
1300         // X >>u 2 -> collect(X, -2)
1301         OverallLeftShift -= ByteShift;
1302         ByteMask <<= ByteShift;
1303         ByteMask &= (~0U >> (32-ByteValues.size()));
1304       }
1305
1306       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1307       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1308
1309       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1310                                ByteValues);
1311     }
1312
1313     // If this is a logical 'and' with a mask that clears bytes, clear the
1314     // corresponding bytes in ByteMask.
1315     if (I->getOpcode() == Instruction::And &&
1316         isa<ConstantInt>(I->getOperand(1))) {
1317       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1318       unsigned NumBytes = ByteValues.size();
1319       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1320       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1321
1322       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1323         // If this byte is masked out by a later operation, we don't care what
1324         // the and mask is.
1325         if ((ByteMask & (1 << i)) == 0)
1326           continue;
1327
1328         // If the AndMask is all zeros for this byte, clear the bit.
1329         APInt MaskB = AndMask & Byte;
1330         if (MaskB == 0) {
1331           ByteMask &= ~(1U << i);
1332           continue;
1333         }
1334
1335         // If the AndMask is not all ones for this byte, it's not a bytezap.
1336         if (MaskB != Byte)
1337           return true;
1338
1339         // Otherwise, this byte is kept.
1340       }
1341
1342       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1343                                ByteValues);
1344     }
1345   }
1346
1347   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1348   // the input value to the bswap.  Some observations: 1) if more than one byte
1349   // is demanded from this input, then it could not be successfully assembled
1350   // into a byteswap.  At least one of the two bytes would not be aligned with
1351   // their ultimate destination.
1352   if (!isPowerOf2_32(ByteMask)) return true;
1353   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1354
1355   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1356   // is demanded, it needs to go into byte 0 of the result.  This means that the
1357   // byte needs to be shifted until it lands in the right byte bucket.  The
1358   // shift amount depends on the position: if the byte is coming from the high
1359   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1360   // low part, it must be shifted left.
1361   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1362   if (ByteValues.size()-1-DestByteNo != InputByteNo)
1363     return true;
1364
1365   // If the destination byte value is already defined, the values are or'd
1366   // together, which isn't a bswap (unless it's an or of the same bits).
1367   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1368     return true;
1369   ByteValues[DestByteNo] = V;
1370   return false;
1371 }
1372
1373 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1374 /// If so, insert the new bswap intrinsic and return it.
1375 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1376   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1377   if (!ITy || ITy->getBitWidth() % 16 ||
1378       // ByteMask only allows up to 32-byte values.
1379       ITy->getBitWidth() > 32*8)
1380     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1381
1382   /// ByteValues - For each byte of the result, we keep track of which value
1383   /// defines each byte.
1384   SmallVector<Value*, 8> ByteValues;
1385   ByteValues.resize(ITy->getBitWidth()/8);
1386
1387   // Try to find all the pieces corresponding to the bswap.
1388   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1389   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1390     return 0;
1391
1392   // Check to see if all of the bytes come from the same value.
1393   Value *V = ByteValues[0];
1394   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1395
1396   // Check to make sure that all of the bytes come from the same value.
1397   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1398     if (ByteValues[i] != V)
1399       return 0;
1400   Module *M = I.getParent()->getParent()->getParent();
1401   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1402   return CallInst::Create(F, V);
1403 }
1404
1405 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1406 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1407 /// we can simplify this expression to "cond ? C : D or B".
1408 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1409                                          Value *C, Value *D) {
1410   // If A is not a select of -1/0, this cannot match.
1411   Value *Cond = 0;
1412   if (!match(A, m_SExt(m_Value(Cond))) ||
1413       !Cond->getType()->isIntegerTy(1))
1414     return 0;
1415
1416   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1417   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1418     return SelectInst::Create(Cond, C, B);
1419   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1420     return SelectInst::Create(Cond, C, B);
1421
1422   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1423   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1424     return SelectInst::Create(Cond, C, D);
1425   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1426     return SelectInst::Create(Cond, C, D);
1427   return 0;
1428 }
1429
1430 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1431 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1432   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1433
1434   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1435   if (PredicatesFoldable(LHSCC, RHSCC)) {
1436     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1437         LHS->getOperand(1) == RHS->getOperand(0))
1438       LHS->swapOperands();
1439     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1440         LHS->getOperand(1) == RHS->getOperand(1)) {
1441       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1442       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1443       bool isSigned = LHS->isSigned() || RHS->isSigned();
1444       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1445     }
1446   }
1447
1448   // handle (roughly):
1449   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1450   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1451     return V;
1452
1453   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1454   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1455   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1456   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1457   if (LHSCst == 0 || RHSCst == 0) return 0;
1458
1459   if (LHSCst == RHSCst && LHSCC == RHSCC) {
1460     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1461     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1462       Value *NewOr = Builder->CreateOr(Val, Val2);
1463       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1464     }
1465   }
1466
1467   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1468   //   iff C2 + CA == C1.
1469   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1470     ConstantInt *AddCst;
1471     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1472       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1473         return Builder->CreateICmpULE(Val, LHSCst);
1474   }
1475
1476   // From here on, we only handle:
1477   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1478   if (Val != Val2) return 0;
1479
1480   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1481   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1482       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1483       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1484       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1485     return 0;
1486
1487   // We can't fold (ugt x, C) | (sgt x, C2).
1488   if (!PredicatesFoldable(LHSCC, RHSCC))
1489     return 0;
1490
1491   // Ensure that the larger constant is on the RHS.
1492   bool ShouldSwap;
1493   if (CmpInst::isSigned(LHSCC) ||
1494       (ICmpInst::isEquality(LHSCC) &&
1495        CmpInst::isSigned(RHSCC)))
1496     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1497   else
1498     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1499
1500   if (ShouldSwap) {
1501     std::swap(LHS, RHS);
1502     std::swap(LHSCst, RHSCst);
1503     std::swap(LHSCC, RHSCC);
1504   }
1505
1506   // At this point, we know we have two icmp instructions
1507   // comparing a value against two constants and or'ing the result
1508   // together.  Because of the above check, we know that we only have
1509   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1510   // icmp folding check above), that the two constants are not
1511   // equal.
1512   assert(LHSCst != RHSCst && "Compares not folded above?");
1513
1514   switch (LHSCC) {
1515   default: llvm_unreachable("Unknown integer condition code!");
1516   case ICmpInst::ICMP_EQ:
1517     switch (RHSCC) {
1518     default: llvm_unreachable("Unknown integer condition code!");
1519     case ICmpInst::ICMP_EQ:
1520       if (LHSCst == SubOne(RHSCst)) {
1521         // (X == 13 | X == 14) -> X-13 <u 2
1522         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1523         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1524         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1525         return Builder->CreateICmpULT(Add, AddCST);
1526       }
1527
1528       if (LHS->getOperand(0) == RHS->getOperand(0)) {
1529         // if LHSCst and RHSCst differ only by one bit:
1530         // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1531         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1532         if (Xor.isPowerOf2()) {
1533           Value *NegCst = Builder->getInt(~Xor);
1534           Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1535           return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1536         }
1537       }
1538
1539       break;                         // (X == 13 | X == 15) -> no change
1540     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1541     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1542       break;
1543     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1544     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1545     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1546       return RHS;
1547     }
1548     break;
1549   case ICmpInst::ICMP_NE:
1550     switch (RHSCC) {
1551     default: llvm_unreachable("Unknown integer condition code!");
1552     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1553     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1554     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1555       return LHS;
1556     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1557     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1558     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1559       return ConstantInt::getTrue(LHS->getContext());
1560     }
1561   case ICmpInst::ICMP_ULT:
1562     switch (RHSCC) {
1563     default: llvm_unreachable("Unknown integer condition code!");
1564     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1565       break;
1566     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1567       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1568       // this can cause overflow.
1569       if (RHSCst->isMaxValue(false))
1570         return LHS;
1571       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1572     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1573       break;
1574     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1575     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1576       return RHS;
1577     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1578       break;
1579     }
1580     break;
1581   case ICmpInst::ICMP_SLT:
1582     switch (RHSCC) {
1583     default: llvm_unreachable("Unknown integer condition code!");
1584     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1585       break;
1586     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1587       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1588       // this can cause overflow.
1589       if (RHSCst->isMaxValue(true))
1590         return LHS;
1591       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1592     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1593       break;
1594     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1595     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1596       return RHS;
1597     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1598       break;
1599     }
1600     break;
1601   case ICmpInst::ICMP_UGT:
1602     switch (RHSCC) {
1603     default: llvm_unreachable("Unknown integer condition code!");
1604     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1605     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1606       return LHS;
1607     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1608       break;
1609     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1610     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1611       return ConstantInt::getTrue(LHS->getContext());
1612     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1613       break;
1614     }
1615     break;
1616   case ICmpInst::ICMP_SGT:
1617     switch (RHSCC) {
1618     default: llvm_unreachable("Unknown integer condition code!");
1619     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1620     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1621       return LHS;
1622     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1623       break;
1624     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1625     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1626       return ConstantInt::getTrue(LHS->getContext());
1627     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1628       break;
1629     }
1630     break;
1631   }
1632   return 0;
1633 }
1634
1635 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1636 /// instcombine, this returns a Value which should already be inserted into the
1637 /// function.
1638 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1639   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1640       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1641       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1642     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1643       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1644         // If either of the constants are nans, then the whole thing returns
1645         // true.
1646         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1647           return ConstantInt::getTrue(LHS->getContext());
1648
1649         // Otherwise, no need to compare the two constants, compare the
1650         // rest.
1651         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1652       }
1653
1654     // Handle vector zeros.  This occurs because the canonical form of
1655     // "fcmp uno x,x" is "fcmp uno x, 0".
1656     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1657         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1658       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1659
1660     return 0;
1661   }
1662
1663   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1664   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1665   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1666
1667   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1668     // Swap RHS operands to match LHS.
1669     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1670     std::swap(Op1LHS, Op1RHS);
1671   }
1672   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1673     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1674     if (Op0CC == Op1CC)
1675       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1676     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1677       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1678     if (Op0CC == FCmpInst::FCMP_FALSE)
1679       return RHS;
1680     if (Op1CC == FCmpInst::FCMP_FALSE)
1681       return LHS;
1682     bool Op0Ordered;
1683     bool Op1Ordered;
1684     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1685     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1686     if (Op0Ordered == Op1Ordered) {
1687       // If both are ordered or unordered, return a new fcmp with
1688       // or'ed predicates.
1689       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1690     }
1691   }
1692   return 0;
1693 }
1694
1695 /// FoldOrWithConstants - This helper function folds:
1696 ///
1697 ///     ((A | B) & C1) | (B & C2)
1698 ///
1699 /// into:
1700 ///
1701 ///     (A & C1) | B
1702 ///
1703 /// when the XOR of the two constants is "all ones" (-1).
1704 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1705                                                Value *A, Value *B, Value *C) {
1706   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1707   if (!CI1) return 0;
1708
1709   Value *V1 = 0;
1710   ConstantInt *CI2 = 0;
1711   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1712
1713   APInt Xor = CI1->getValue() ^ CI2->getValue();
1714   if (!Xor.isAllOnesValue()) return 0;
1715
1716   if (V1 == A || V1 == B) {
1717     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1718     return BinaryOperator::CreateOr(NewOp, V1);
1719   }
1720
1721   return 0;
1722 }
1723
1724 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1725   bool Changed = SimplifyAssociativeOrCommutative(I);
1726   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1727
1728   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1729     return ReplaceInstUsesWith(I, V);
1730
1731   // (A&B)|(A&C) -> A&(B|C) etc
1732   if (Value *V = SimplifyUsingDistributiveLaws(I))
1733     return ReplaceInstUsesWith(I, V);
1734
1735   // See if we can simplify any instructions used by the instruction whose sole
1736   // purpose is to compute bits we don't care about.
1737   if (SimplifyDemandedInstructionBits(I))
1738     return &I;
1739
1740   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1741     ConstantInt *C1 = 0; Value *X = 0;
1742     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1743     // iff (C1 & C2) == 0.
1744     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1745         (RHS->getValue() & C1->getValue()) != 0 &&
1746         Op0->hasOneUse()) {
1747       Value *Or = Builder->CreateOr(X, RHS);
1748       Or->takeName(Op0);
1749       return BinaryOperator::CreateAnd(Or,
1750                          ConstantInt::get(I.getContext(),
1751                                           RHS->getValue() | C1->getValue()));
1752     }
1753
1754     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1755     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1756         Op0->hasOneUse()) {
1757       Value *Or = Builder->CreateOr(X, RHS);
1758       Or->takeName(Op0);
1759       return BinaryOperator::CreateXor(Or,
1760                  ConstantInt::get(I.getContext(),
1761                                   C1->getValue() & ~RHS->getValue()));
1762     }
1763
1764     // Try to fold constant and into select arguments.
1765     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1766       if (Instruction *R = FoldOpIntoSelect(I, SI))
1767         return R;
1768
1769     if (isa<PHINode>(Op0))
1770       if (Instruction *NV = FoldOpIntoPhi(I))
1771         return NV;
1772   }
1773
1774   Value *A = 0, *B = 0;
1775   ConstantInt *C1 = 0, *C2 = 0;
1776
1777   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1778   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1779   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1780       match(Op1, m_Or(m_Value(), m_Value())) ||
1781       (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1782        match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1783     if (Instruction *BSwap = MatchBSwap(I))
1784       return BSwap;
1785   }
1786
1787   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1788   if (Op0->hasOneUse() &&
1789       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1790       MaskedValueIsZero(Op1, C1->getValue())) {
1791     Value *NOr = Builder->CreateOr(A, Op1);
1792     NOr->takeName(Op0);
1793     return BinaryOperator::CreateXor(NOr, C1);
1794   }
1795
1796   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1797   if (Op1->hasOneUse() &&
1798       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1799       MaskedValueIsZero(Op0, C1->getValue())) {
1800     Value *NOr = Builder->CreateOr(A, Op0);
1801     NOr->takeName(Op0);
1802     return BinaryOperator::CreateXor(NOr, C1);
1803   }
1804
1805   // (A & C)|(B & D)
1806   Value *C = 0, *D = 0;
1807   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1808       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1809     Value *V1 = 0, *V2 = 0;
1810     C1 = dyn_cast<ConstantInt>(C);
1811     C2 = dyn_cast<ConstantInt>(D);
1812     if (C1 && C2) {  // (A & C1)|(B & C2)
1813       // If we have: ((V + N) & C1) | (V & C2)
1814       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1815       // replace with V+N.
1816       if (C1->getValue() == ~C2->getValue()) {
1817         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1818             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1819           // Add commutes, try both ways.
1820           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1821             return ReplaceInstUsesWith(I, A);
1822           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1823             return ReplaceInstUsesWith(I, A);
1824         }
1825         // Or commutes, try both ways.
1826         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1827             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1828           // Add commutes, try both ways.
1829           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1830             return ReplaceInstUsesWith(I, B);
1831           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1832             return ReplaceInstUsesWith(I, B);
1833         }
1834       }
1835
1836       if ((C1->getValue() & C2->getValue()) == 0) {
1837         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1838         // iff (C1&C2) == 0 and (N&~C1) == 0
1839         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1840             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1841              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1842           return BinaryOperator::CreateAnd(A,
1843                                ConstantInt::get(A->getContext(),
1844                                                 C1->getValue()|C2->getValue()));
1845         // Or commutes, try both ways.
1846         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1847             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1848              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1849           return BinaryOperator::CreateAnd(B,
1850                                ConstantInt::get(B->getContext(),
1851                                                 C1->getValue()|C2->getValue()));
1852
1853         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1854         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1855         ConstantInt *C3 = 0, *C4 = 0;
1856         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1857             (C3->getValue() & ~C1->getValue()) == 0 &&
1858             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1859             (C4->getValue() & ~C2->getValue()) == 0) {
1860           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1861           return BinaryOperator::CreateAnd(V2,
1862                                ConstantInt::get(B->getContext(),
1863                                                 C1->getValue()|C2->getValue()));
1864         }
1865       }
1866     }
1867
1868     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
1869     // Don't do this for vector select idioms, the code generator doesn't handle
1870     // them well yet.
1871     if (!I.getType()->isVectorTy()) {
1872       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1873         return Match;
1874       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1875         return Match;
1876       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1877         return Match;
1878       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1879         return Match;
1880     }
1881
1882     // ((A&~B)|(~A&B)) -> A^B
1883     if ((match(C, m_Not(m_Specific(D))) &&
1884          match(B, m_Not(m_Specific(A)))))
1885       return BinaryOperator::CreateXor(A, D);
1886     // ((~B&A)|(~A&B)) -> A^B
1887     if ((match(A, m_Not(m_Specific(D))) &&
1888          match(B, m_Not(m_Specific(C)))))
1889       return BinaryOperator::CreateXor(C, D);
1890     // ((A&~B)|(B&~A)) -> A^B
1891     if ((match(C, m_Not(m_Specific(B))) &&
1892          match(D, m_Not(m_Specific(A)))))
1893       return BinaryOperator::CreateXor(A, B);
1894     // ((~B&A)|(B&~A)) -> A^B
1895     if ((match(A, m_Not(m_Specific(B))) &&
1896          match(D, m_Not(m_Specific(C)))))
1897       return BinaryOperator::CreateXor(C, B);
1898
1899     // ((A|B)&1)|(B&-2) -> (A&1) | B
1900     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1901         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1902       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1903       if (Ret) return Ret;
1904     }
1905     // (B&-2)|((A|B)&1) -> (A&1) | B
1906     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1907         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1908       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1909       if (Ret) return Ret;
1910     }
1911   }
1912
1913   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1914   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1915     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1916       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1917           SI0->getOperand(1) == SI1->getOperand(1) &&
1918           (SI0->hasOneUse() || SI1->hasOneUse())) {
1919         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1920                                          SI0->getName());
1921         return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1922                                       SI1->getOperand(1));
1923       }
1924   }
1925
1926   // (~A | ~B) == (~(A & B)) - De Morgan's Law
1927   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1928     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1929       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1930         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1931                                         I.getName()+".demorgan");
1932         return BinaryOperator::CreateNot(And);
1933       }
1934
1935   // Canonicalize xor to the RHS.
1936   bool SwappedForXor = false;
1937   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
1938     std::swap(Op0, Op1);
1939     SwappedForXor = true;
1940   }
1941
1942   // A | ( A ^ B) -> A |  B
1943   // A | (~A ^ B) -> A | ~B
1944   // (A & B) | (A ^ B)
1945   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1946     if (Op0 == A || Op0 == B)
1947       return BinaryOperator::CreateOr(A, B);
1948
1949     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
1950         match(Op0, m_And(m_Specific(B), m_Specific(A))))
1951       return BinaryOperator::CreateOr(A, B);
1952
1953     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1954       Value *Not = Builder->CreateNot(B, B->getName()+".not");
1955       return BinaryOperator::CreateOr(Not, Op0);
1956     }
1957     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1958       Value *Not = Builder->CreateNot(A, A->getName()+".not");
1959       return BinaryOperator::CreateOr(Not, Op0);
1960     }
1961   }
1962
1963   // A | ~(A | B) -> A | ~B
1964   // A | ~(A ^ B) -> A | ~B
1965   if (match(Op1, m_Not(m_Value(A))))
1966     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
1967       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1968           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1969                                B->getOpcode() == Instruction::Xor)) {
1970         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1971                                                  B->getOperand(0);
1972         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
1973         return BinaryOperator::CreateOr(Not, Op0);
1974       }
1975
1976   if (SwappedForXor)
1977     std::swap(Op0, Op1);
1978
1979   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1980     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1981       if (Value *Res = FoldOrOfICmps(LHS, RHS))
1982         return ReplaceInstUsesWith(I, Res);
1983
1984   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
1985   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1986     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1987       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1988         return ReplaceInstUsesWith(I, Res);
1989
1990   // fold (or (cast A), (cast B)) -> (cast (or A, B))
1991   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1992     CastInst *Op1C = dyn_cast<CastInst>(Op1);
1993     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1994       Type *SrcTy = Op0C->getOperand(0)->getType();
1995       if (SrcTy == Op1C->getOperand(0)->getType() &&
1996           SrcTy->isIntOrIntVectorTy()) {
1997         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1998
1999         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2000             // Only do this if the casts both really cause code to be
2001             // generated.
2002             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2003             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2004           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2005           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2006         }
2007
2008         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2009         // cast is otherwise not optimizable.  This happens for vector sexts.
2010         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2011           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2012             if (Value *Res = FoldOrOfICmps(LHS, RHS))
2013               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2014
2015         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2016         // cast is otherwise not optimizable.  This happens for vector sexts.
2017         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2018           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2019             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2020               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2021       }
2022     }
2023   }
2024
2025   // or(sext(A), B) -> A ? -1 : B where A is an i1
2026   // or(A, sext(B)) -> B ? -1 : A where B is an i1
2027   if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2028     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2029   if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2030     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2031
2032   // Note: If we've gotten to the point of visiting the outer OR, then the
2033   // inner one couldn't be simplified.  If it was a constant, then it won't
2034   // be simplified by a later pass either, so we try swapping the inner/outer
2035   // ORs in the hopes that we'll be able to simplify it this way.
2036   // (X|C) | V --> (X|V) | C
2037   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2038       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2039     Value *Inner = Builder->CreateOr(A, Op1);
2040     Inner->takeName(Op0);
2041     return BinaryOperator::CreateOr(Inner, C1);
2042   }
2043
2044   return Changed ? &I : 0;
2045 }
2046
2047 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2048   bool Changed = SimplifyAssociativeOrCommutative(I);
2049   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2050
2051   if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2052     return ReplaceInstUsesWith(I, V);
2053
2054   // (A&B)^(A&C) -> A&(B^C) etc
2055   if (Value *V = SimplifyUsingDistributiveLaws(I))
2056     return ReplaceInstUsesWith(I, V);
2057
2058   // See if we can simplify any instructions used by the instruction whose sole
2059   // purpose is to compute bits we don't care about.
2060   if (SimplifyDemandedInstructionBits(I))
2061     return &I;
2062
2063   // Is this a ~ operation?
2064   if (Value *NotOp = dyn_castNotVal(&I)) {
2065     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2066       if (Op0I->getOpcode() == Instruction::And ||
2067           Op0I->getOpcode() == Instruction::Or) {
2068         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2069         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2070         if (dyn_castNotVal(Op0I->getOperand(1)))
2071           Op0I->swapOperands();
2072         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2073           Value *NotY =
2074             Builder->CreateNot(Op0I->getOperand(1),
2075                                Op0I->getOperand(1)->getName()+".not");
2076           if (Op0I->getOpcode() == Instruction::And)
2077             return BinaryOperator::CreateOr(Op0NotVal, NotY);
2078           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2079         }
2080
2081         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2082         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2083         if (isFreeToInvert(Op0I->getOperand(0)) &&
2084             isFreeToInvert(Op0I->getOperand(1))) {
2085           Value *NotX =
2086             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2087           Value *NotY =
2088             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2089           if (Op0I->getOpcode() == Instruction::And)
2090             return BinaryOperator::CreateOr(NotX, NotY);
2091           return BinaryOperator::CreateAnd(NotX, NotY);
2092         }
2093
2094       } else if (Op0I->getOpcode() == Instruction::AShr) {
2095         // ~(~X >>s Y) --> (X >>s Y)
2096         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2097           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2098       }
2099     }
2100   }
2101
2102
2103   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2104     if (RHS->isOne() && Op0->hasOneUse())
2105       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2106       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2107         return CmpInst::Create(CI->getOpcode(),
2108                                CI->getInversePredicate(),
2109                                CI->getOperand(0), CI->getOperand(1));
2110
2111     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2112     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2113       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2114         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2115           Instruction::CastOps Opcode = Op0C->getOpcode();
2116           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2117               (RHS == ConstantExpr::getCast(Opcode,
2118                                            ConstantInt::getTrue(I.getContext()),
2119                                             Op0C->getDestTy()))) {
2120             CI->setPredicate(CI->getInversePredicate());
2121             return CastInst::Create(Opcode, CI, Op0C->getType());
2122           }
2123         }
2124       }
2125     }
2126
2127     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2128       // ~(c-X) == X-c-1 == X+(-c-1)
2129       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2130         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2131           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2132           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2133                                       ConstantInt::get(I.getType(), 1));
2134           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2135         }
2136
2137       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2138         if (Op0I->getOpcode() == Instruction::Add) {
2139           // ~(X-c) --> (-c-1)-X
2140           if (RHS->isAllOnesValue()) {
2141             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2142             return BinaryOperator::CreateSub(
2143                            ConstantExpr::getSub(NegOp0CI,
2144                                       ConstantInt::get(I.getType(), 1)),
2145                                       Op0I->getOperand(0));
2146           } else if (RHS->getValue().isSignBit()) {
2147             // (X + C) ^ signbit -> (X + C + signbit)
2148             Constant *C = ConstantInt::get(I.getContext(),
2149                                            RHS->getValue() + Op0CI->getValue());
2150             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2151
2152           }
2153         } else if (Op0I->getOpcode() == Instruction::Or) {
2154           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2155           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2156             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2157             // Anything in both C1 and C2 is known to be zero, remove it from
2158             // NewRHS.
2159             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2160             NewRHS = ConstantExpr::getAnd(NewRHS,
2161                                        ConstantExpr::getNot(CommonBits));
2162             Worklist.Add(Op0I);
2163             I.setOperand(0, Op0I->getOperand(0));
2164             I.setOperand(1, NewRHS);
2165             return &I;
2166           }
2167         } else if (Op0I->getOpcode() == Instruction::LShr) {
2168           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2169           // E1 = "X ^ C1"
2170           BinaryOperator *E1;
2171           ConstantInt *C1;
2172           if (Op0I->hasOneUse() &&
2173               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2174               E1->getOpcode() == Instruction::Xor &&
2175               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2176             // fold (C1 >> C2) ^ C3
2177             ConstantInt *C2 = Op0CI, *C3 = RHS;
2178             APInt FoldConst = C1->getValue().lshr(C2->getValue());
2179             FoldConst ^= C3->getValue();
2180             // Prepare the two operands.
2181             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2182             Opnd0->takeName(Op0I);
2183             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2184             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2185
2186             return BinaryOperator::CreateXor(Opnd0, FoldVal);
2187           }
2188         }
2189       }
2190     }
2191
2192     // Try to fold constant and into select arguments.
2193     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2194       if (Instruction *R = FoldOpIntoSelect(I, SI))
2195         return R;
2196     if (isa<PHINode>(Op0))
2197       if (Instruction *NV = FoldOpIntoPhi(I))
2198         return NV;
2199   }
2200
2201   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2202   if (Op1I) {
2203     Value *A, *B;
2204     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2205       if (A == Op0) {              // B^(B|A) == (A|B)^B
2206         Op1I->swapOperands();
2207         I.swapOperands();
2208         std::swap(Op0, Op1);
2209       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2210         I.swapOperands();     // Simplified below.
2211         std::swap(Op0, Op1);
2212       }
2213     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2214                Op1I->hasOneUse()){
2215       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2216         Op1I->swapOperands();
2217         std::swap(A, B);
2218       }
2219       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2220         I.swapOperands();     // Simplified below.
2221         std::swap(Op0, Op1);
2222       }
2223     }
2224   }
2225
2226   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2227   if (Op0I) {
2228     Value *A, *B;
2229     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2230         Op0I->hasOneUse()) {
2231       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2232         std::swap(A, B);
2233       if (B == Op1)                                  // (A|B)^B == A & ~B
2234         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2235     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2236                Op0I->hasOneUse()){
2237       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2238         std::swap(A, B);
2239       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2240           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2241         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2242       }
2243     }
2244   }
2245
2246   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
2247   if (Op0I && Op1I && Op0I->isShift() &&
2248       Op0I->getOpcode() == Op1I->getOpcode() &&
2249       Op0I->getOperand(1) == Op1I->getOperand(1) &&
2250       (Op0I->hasOneUse() || Op1I->hasOneUse())) {
2251     Value *NewOp =
2252       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2253                          Op0I->getName());
2254     return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2255                                   Op1I->getOperand(1));
2256   }
2257
2258   if (Op0I && Op1I) {
2259     Value *A, *B, *C, *D;
2260     // (A & B)^(A | B) -> A ^ B
2261     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2262         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2263       if ((A == C && B == D) || (A == D && B == C))
2264         return BinaryOperator::CreateXor(A, B);
2265     }
2266     // (A | B)^(A & B) -> A ^ B
2267     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2268         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2269       if ((A == C && B == D) || (A == D && B == C))
2270         return BinaryOperator::CreateXor(A, B);
2271     }
2272   }
2273
2274   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2275   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2276     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2277       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2278         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2279             LHS->getOperand(1) == RHS->getOperand(0))
2280           LHS->swapOperands();
2281         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2282             LHS->getOperand(1) == RHS->getOperand(1)) {
2283           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2284           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2285           bool isSigned = LHS->isSigned() || RHS->isSigned();
2286           return ReplaceInstUsesWith(I,
2287                                getNewICmpValue(isSigned, Code, Op0, Op1,
2288                                                Builder));
2289         }
2290       }
2291
2292   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2293   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2294     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2295       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2296         Type *SrcTy = Op0C->getOperand(0)->getType();
2297         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2298             // Only do this if the casts both really cause code to be generated.
2299             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2300                                I.getType()) &&
2301             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2302                                I.getType())) {
2303           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2304                                             Op1C->getOperand(0), I.getName());
2305           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2306         }
2307       }
2308   }
2309
2310   return Changed ? &I : 0;
2311 }