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