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