cache another dereferenced iterator
[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   
477   // From here on, we only handle:
478   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
479   if (Val != Val2) return 0;
480   
481   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
482   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
483       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
484       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
485       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
486     return 0;
487   
488   // We can't fold (ugt x, C) & (sgt x, C2).
489   if (!PredicatesFoldable(LHSCC, RHSCC))
490     return 0;
491     
492   // Ensure that the larger constant is on the RHS.
493   bool ShouldSwap;
494   if (CmpInst::isSigned(LHSCC) ||
495       (ICmpInst::isEquality(LHSCC) && 
496        CmpInst::isSigned(RHSCC)))
497     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
498   else
499     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
500     
501   if (ShouldSwap) {
502     std::swap(LHS, RHS);
503     std::swap(LHSCst, RHSCst);
504     std::swap(LHSCC, RHSCC);
505   }
506
507   // At this point, we know we have two icmp instructions
508   // comparing a value against two constants and and'ing the result
509   // together.  Because of the above check, we know that we only have
510   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
511   // (from the icmp folding check above), that the two constants 
512   // are not equal and that the larger constant is on the RHS
513   assert(LHSCst != RHSCst && "Compares not folded above?");
514
515   switch (LHSCC) {
516   default: llvm_unreachable("Unknown integer condition code!");
517   case ICmpInst::ICMP_EQ:
518     switch (RHSCC) {
519     default: llvm_unreachable("Unknown integer condition code!");
520     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
521     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
522     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
523       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
524     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
525     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
526     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
527       return LHS;
528     }
529   case ICmpInst::ICMP_NE:
530     switch (RHSCC) {
531     default: llvm_unreachable("Unknown integer condition code!");
532     case ICmpInst::ICMP_ULT:
533       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
534         return Builder->CreateICmpULT(Val, LHSCst);
535       break;                        // (X != 13 & X u< 15) -> no change
536     case ICmpInst::ICMP_SLT:
537       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
538         return Builder->CreateICmpSLT(Val, LHSCst);
539       break;                        // (X != 13 & X s< 15) -> no change
540     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
541     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
542     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
543       return RHS;
544     case ICmpInst::ICMP_NE:
545       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
546         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
547         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
548         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
549       }
550       break;                        // (X != 13 & X != 15) -> no change
551     }
552     break;
553   case ICmpInst::ICMP_ULT:
554     switch (RHSCC) {
555     default: llvm_unreachable("Unknown integer condition code!");
556     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
557     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
558       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
559     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
560       break;
561     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
562     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
563       return LHS;
564     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
565       break;
566     }
567     break;
568   case ICmpInst::ICMP_SLT:
569     switch (RHSCC) {
570     default: llvm_unreachable("Unknown integer condition code!");
571     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
572     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
573       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
574     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
575       break;
576     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
577     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
578       return LHS;
579     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
580       break;
581     }
582     break;
583   case ICmpInst::ICMP_UGT:
584     switch (RHSCC) {
585     default: llvm_unreachable("Unknown integer condition code!");
586     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
587     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
588       return RHS;
589     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
590       break;
591     case ICmpInst::ICMP_NE:
592       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
593         return Builder->CreateICmp(LHSCC, Val, RHSCst);
594       break;                        // (X u> 13 & X != 15) -> no change
595     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
596       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
597     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
598       break;
599     }
600     break;
601   case ICmpInst::ICMP_SGT:
602     switch (RHSCC) {
603     default: llvm_unreachable("Unknown integer condition code!");
604     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
605     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
606       return RHS;
607     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
608       break;
609     case ICmpInst::ICMP_NE:
610       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
611         return Builder->CreateICmp(LHSCC, Val, RHSCst);
612       break;                        // (X s> 13 & X != 15) -> no change
613     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
614       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
615     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
616       break;
617     }
618     break;
619   }
620  
621   return 0;
622 }
623
624 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of
625 /// instcombine, this returns a Value which should already be inserted into the
626 /// function.
627 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
628   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
629       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
630     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
631     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
632       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
633         // If either of the constants are nans, then the whole thing returns
634         // false.
635         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
636           return ConstantInt::getFalse(LHS->getContext());
637         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
638       }
639     
640     // Handle vector zeros.  This occurs because the canonical form of
641     // "fcmp ord x,x" is "fcmp ord x, 0".
642     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
643         isa<ConstantAggregateZero>(RHS->getOperand(1)))
644       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
645     return 0;
646   }
647   
648   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
649   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
650   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
651   
652   
653   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
654     // Swap RHS operands to match LHS.
655     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
656     std::swap(Op1LHS, Op1RHS);
657   }
658   
659   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
660     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
661     if (Op0CC == Op1CC)
662       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
663     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
664       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
665     if (Op0CC == FCmpInst::FCMP_TRUE)
666       return RHS;
667     if (Op1CC == FCmpInst::FCMP_TRUE)
668       return LHS;
669     
670     bool Op0Ordered;
671     bool Op1Ordered;
672     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
673     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
674     if (Op1Pred == 0) {
675       std::swap(LHS, RHS);
676       std::swap(Op0Pred, Op1Pred);
677       std::swap(Op0Ordered, Op1Ordered);
678     }
679     if (Op0Pred == 0) {
680       // uno && ueq -> uno && (uno || eq) -> ueq
681       // ord && olt -> ord && (ord && lt) -> olt
682       if (Op0Ordered == Op1Ordered)
683         return RHS;
684       
685       // uno && oeq -> uno && (ord && eq) -> false
686       // uno && ord -> false
687       if (!Op0Ordered)
688         return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
689       // ord && ueq -> ord && (uno || eq) -> oeq
690       return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
691     }
692   }
693
694   return 0;
695 }
696
697
698 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
699   bool Changed = SimplifyCommutative(I);
700   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
701
702   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
703     return ReplaceInstUsesWith(I, V);
704
705   // See if we can simplify any instructions used by the instruction whose sole 
706   // purpose is to compute bits we don't care about.
707   if (SimplifyDemandedInstructionBits(I))
708     return &I;  
709
710   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
711     const APInt &AndRHSMask = AndRHS->getValue();
712     APInt NotAndRHS(~AndRHSMask);
713
714     // Optimize a variety of ((val OP C1) & C2) combinations...
715     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
716       Value *Op0LHS = Op0I->getOperand(0);
717       Value *Op0RHS = Op0I->getOperand(1);
718       switch (Op0I->getOpcode()) {
719       default: break;
720       case Instruction::Xor:
721       case Instruction::Or:
722         // If the mask is only needed on one incoming arm, push it up.
723         if (!Op0I->hasOneUse()) break;
724           
725         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
726           // Not masking anything out for the LHS, move to RHS.
727           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
728                                              Op0RHS->getName()+".masked");
729           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
730         }
731         if (!isa<Constant>(Op0RHS) &&
732             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
733           // Not masking anything out for the RHS, move to LHS.
734           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
735                                              Op0LHS->getName()+".masked");
736           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
737         }
738
739         break;
740       case Instruction::Add:
741         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
742         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
743         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
744         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
745           return BinaryOperator::CreateAnd(V, AndRHS);
746         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
747           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
748         break;
749
750       case Instruction::Sub:
751         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
752         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
753         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
754         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
755           return BinaryOperator::CreateAnd(V, AndRHS);
756
757         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
758         // has 1's for all bits that the subtraction with A might affect.
759         if (Op0I->hasOneUse()) {
760           uint32_t BitWidth = AndRHSMask.getBitWidth();
761           uint32_t Zeros = AndRHSMask.countLeadingZeros();
762           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
763
764           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
765           if (!(A && A->isZero()) &&               // avoid infinite recursion.
766               MaskedValueIsZero(Op0LHS, Mask)) {
767             Value *NewNeg = Builder->CreateNeg(Op0RHS);
768             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
769           }
770         }
771         break;
772
773       case Instruction::Shl:
774       case Instruction::LShr:
775         // (1 << x) & 1 --> zext(x == 0)
776         // (1 >> x) & 1 --> zext(x == 0)
777         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
778           Value *NewICmp =
779             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
780           return new ZExtInst(NewICmp, I.getType());
781         }
782         break;
783       }
784
785       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
786         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
787           return Res;
788     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
789       // If this is an integer truncation or change from signed-to-unsigned, and
790       // if the source is an and/or with immediate, transform it.  This
791       // frequently occurs for bitfield accesses.
792       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
793         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
794             CastOp->getNumOperands() == 2)
795           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
796             if (CastOp->getOpcode() == Instruction::And) {
797               // Change: and (cast (and X, C1) to T), C2
798               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
799               // This will fold the two constants together, which may allow 
800               // other simplifications.
801               Value *NewCast = Builder->CreateTruncOrBitCast(
802                 CastOp->getOperand(0), I.getType(), 
803                 CastOp->getName()+".shrunk");
804               // trunc_or_bitcast(C1)&C2
805               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
806               C3 = ConstantExpr::getAnd(C3, AndRHS);
807               return BinaryOperator::CreateAnd(NewCast, C3);
808             } else if (CastOp->getOpcode() == Instruction::Or) {
809               // Change: and (cast (or X, C1) to T), C2
810               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
811               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
812               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
813                 // trunc(C1)&C2
814                 return ReplaceInstUsesWith(I, AndRHS);
815             }
816           }
817       }
818     }
819
820     // Try to fold constant and into select arguments.
821     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
822       if (Instruction *R = FoldOpIntoSelect(I, SI))
823         return R;
824     if (isa<PHINode>(Op0))
825       if (Instruction *NV = FoldOpIntoPhi(I))
826         return NV;
827   }
828
829
830   // (~A & ~B) == (~(A | B)) - De Morgan's Law
831   if (Value *Op0NotVal = dyn_castNotVal(Op0))
832     if (Value *Op1NotVal = dyn_castNotVal(Op1))
833       if (Op0->hasOneUse() && Op1->hasOneUse()) {
834         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
835                                       I.getName()+".demorgan");
836         return BinaryOperator::CreateNot(Or);
837       }
838
839   {
840     Value *A = 0, *B = 0, *C = 0, *D = 0;
841     // (A|B) & ~(A&B) -> A^B
842     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
843         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
844         ((A == C && B == D) || (A == D && B == C)))
845       return BinaryOperator::CreateXor(A, B);
846     
847     // ~(A&B) & (A|B) -> A^B
848     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
849         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
850         ((A == C && B == D) || (A == D && B == C)))
851       return BinaryOperator::CreateXor(A, B);
852     
853     if (Op0->hasOneUse() &&
854         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
855       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
856         I.swapOperands();     // Simplify below
857         std::swap(Op0, Op1);
858       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
859         cast<BinaryOperator>(Op0)->swapOperands();
860         I.swapOperands();     // Simplify below
861         std::swap(Op0, Op1);
862       }
863     }
864
865     if (Op1->hasOneUse() &&
866         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
867       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
868         cast<BinaryOperator>(Op1)->swapOperands();
869         std::swap(A, B);
870       }
871       if (A == Op0)                                // A&(A^B) -> A & ~B
872         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
873     }
874
875     // (A&((~A)|B)) -> A&B
876     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
877         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
878       return BinaryOperator::CreateAnd(A, Op1);
879     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
880         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
881       return BinaryOperator::CreateAnd(A, Op0);
882   }
883   
884   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
885     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
886       if (Value *Res = FoldAndOfICmps(LHS, RHS))
887         return ReplaceInstUsesWith(I, Res);
888   
889   // If and'ing two fcmp, try combine them into one.
890   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
891     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
892       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
893         return ReplaceInstUsesWith(I, Res);
894   
895   
896   // fold (and (cast A), (cast B)) -> (cast (and A, B))
897   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
898     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
899       const Type *SrcTy = Op0C->getOperand(0)->getType();
900       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
901           SrcTy == Op1C->getOperand(0)->getType() &&
902           SrcTy->isIntOrIntVectorTy()) {
903         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
904         
905         // Only do this if the casts both really cause code to be generated.
906         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
907             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
908           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
909           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
910         }
911         
912         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
913         // cast is otherwise not optimizable.  This happens for vector sexts.
914         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
915           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
916             if (Value *Res = FoldAndOfICmps(LHS, RHS))
917               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
918         
919         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
920         // cast is otherwise not optimizable.  This happens for vector sexts.
921         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
922           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
923             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
924               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
925       }
926     }
927     
928   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
929   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
930     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
931       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
932           SI0->getOperand(1) == SI1->getOperand(1) &&
933           (SI0->hasOneUse() || SI1->hasOneUse())) {
934         Value *NewOp =
935           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
936                              SI0->getName());
937         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
938                                       SI1->getOperand(1));
939       }
940   }
941
942   return Changed ? &I : 0;
943 }
944
945 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
946 /// capable of providing pieces of a bswap.  The subexpression provides pieces
947 /// of a bswap if it is proven that each of the non-zero bytes in the output of
948 /// the expression came from the corresponding "byte swapped" byte in some other
949 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
950 /// we know that the expression deposits the low byte of %X into the high byte
951 /// of the bswap result and that all other bytes are zero.  This expression is
952 /// accepted, the high byte of ByteValues is set to X to indicate a correct
953 /// match.
954 ///
955 /// This function returns true if the match was unsuccessful and false if so.
956 /// On entry to the function the "OverallLeftShift" is a signed integer value
957 /// indicating the number of bytes that the subexpression is later shifted.  For
958 /// example, if the expression is later right shifted by 16 bits, the
959 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
960 /// byte of ByteValues is actually being set.
961 ///
962 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
963 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
964 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
965 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
966 /// always in the local (OverallLeftShift) coordinate space.
967 ///
968 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
969                               SmallVector<Value*, 8> &ByteValues) {
970   if (Instruction *I = dyn_cast<Instruction>(V)) {
971     // If this is an or instruction, it may be an inner node of the bswap.
972     if (I->getOpcode() == Instruction::Or) {
973       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
974                                ByteValues) ||
975              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
976                                ByteValues);
977     }
978   
979     // If this is a logical shift by a constant multiple of 8, recurse with
980     // OverallLeftShift and ByteMask adjusted.
981     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
982       unsigned ShAmt = 
983         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
984       // Ensure the shift amount is defined and of a byte value.
985       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
986         return true;
987
988       unsigned ByteShift = ShAmt >> 3;
989       if (I->getOpcode() == Instruction::Shl) {
990         // X << 2 -> collect(X, +2)
991         OverallLeftShift += ByteShift;
992         ByteMask >>= ByteShift;
993       } else {
994         // X >>u 2 -> collect(X, -2)
995         OverallLeftShift -= ByteShift;
996         ByteMask <<= ByteShift;
997         ByteMask &= (~0U >> (32-ByteValues.size()));
998       }
999
1000       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1001       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1002
1003       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1004                                ByteValues);
1005     }
1006
1007     // If this is a logical 'and' with a mask that clears bytes, clear the
1008     // corresponding bytes in ByteMask.
1009     if (I->getOpcode() == Instruction::And &&
1010         isa<ConstantInt>(I->getOperand(1))) {
1011       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1012       unsigned NumBytes = ByteValues.size();
1013       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1014       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1015       
1016       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1017         // If this byte is masked out by a later operation, we don't care what
1018         // the and mask is.
1019         if ((ByteMask & (1 << i)) == 0)
1020           continue;
1021         
1022         // If the AndMask is all zeros for this byte, clear the bit.
1023         APInt MaskB = AndMask & Byte;
1024         if (MaskB == 0) {
1025           ByteMask &= ~(1U << i);
1026           continue;
1027         }
1028         
1029         // If the AndMask is not all ones for this byte, it's not a bytezap.
1030         if (MaskB != Byte)
1031           return true;
1032
1033         // Otherwise, this byte is kept.
1034       }
1035
1036       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1037                                ByteValues);
1038     }
1039   }
1040   
1041   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1042   // the input value to the bswap.  Some observations: 1) if more than one byte
1043   // is demanded from this input, then it could not be successfully assembled
1044   // into a byteswap.  At least one of the two bytes would not be aligned with
1045   // their ultimate destination.
1046   if (!isPowerOf2_32(ByteMask)) return true;
1047   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1048   
1049   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1050   // is demanded, it needs to go into byte 0 of the result.  This means that the
1051   // byte needs to be shifted until it lands in the right byte bucket.  The
1052   // shift amount depends on the position: if the byte is coming from the high
1053   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1054   // low part, it must be shifted left.
1055   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1056   if (InputByteNo < ByteValues.size()/2) {
1057     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1058       return true;
1059   } else {
1060     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1061       return true;
1062   }
1063   
1064   // If the destination byte value is already defined, the values are or'd
1065   // together, which isn't a bswap (unless it's an or of the same bits).
1066   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1067     return true;
1068   ByteValues[DestByteNo] = V;
1069   return false;
1070 }
1071
1072 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1073 /// If so, insert the new bswap intrinsic and return it.
1074 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1075   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1076   if (!ITy || ITy->getBitWidth() % 16 || 
1077       // ByteMask only allows up to 32-byte values.
1078       ITy->getBitWidth() > 32*8) 
1079     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1080   
1081   /// ByteValues - For each byte of the result, we keep track of which value
1082   /// defines each byte.
1083   SmallVector<Value*, 8> ByteValues;
1084   ByteValues.resize(ITy->getBitWidth()/8);
1085     
1086   // Try to find all the pieces corresponding to the bswap.
1087   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1088   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1089     return 0;
1090   
1091   // Check to see if all of the bytes come from the same value.
1092   Value *V = ByteValues[0];
1093   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1094   
1095   // Check to make sure that all of the bytes come from the same value.
1096   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1097     if (ByteValues[i] != V)
1098       return 0;
1099   const Type *Tys[] = { ITy };
1100   Module *M = I.getParent()->getParent()->getParent();
1101   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1102   return CallInst::Create(F, V);
1103 }
1104
1105 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1106 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1107 /// we can simplify this expression to "cond ? C : D or B".
1108 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1109                                          Value *C, Value *D) {
1110   // If A is not a select of -1/0, this cannot match.
1111   Value *Cond = 0;
1112   if (!match(A, m_SExt(m_Value(Cond))) ||
1113       !Cond->getType()->isIntegerTy(1))
1114     return 0;
1115
1116   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1117   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1118     return SelectInst::Create(Cond, C, B);
1119   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1120     return SelectInst::Create(Cond, C, B);
1121   
1122   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1123   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1124     return SelectInst::Create(Cond, C, D);
1125   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1126     return SelectInst::Create(Cond, C, D);
1127   return 0;
1128 }
1129
1130 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1131 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1132   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1133
1134   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1135   if (PredicatesFoldable(LHSCC, RHSCC)) {
1136     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1137         LHS->getOperand(1) == RHS->getOperand(0))
1138       LHS->swapOperands();
1139     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1140         LHS->getOperand(1) == RHS->getOperand(1)) {
1141       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1142       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1143       bool isSigned = LHS->isSigned() || RHS->isSigned();
1144       return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1145     }
1146   }
1147   
1148   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1149   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1150   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1151   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1152   if (LHSCst == 0 || RHSCst == 0) return 0;
1153
1154   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1155   if (LHSCst == RHSCst && LHSCC == RHSCC &&
1156       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1157     Value *NewOr = Builder->CreateOr(Val, Val2);
1158     return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1159   }
1160   
1161   // From here on, we only handle:
1162   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1163   if (Val != Val2) return 0;
1164   
1165   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1166   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1167       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1168       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1169       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1170     return 0;
1171   
1172   // We can't fold (ugt x, C) | (sgt x, C2).
1173   if (!PredicatesFoldable(LHSCC, RHSCC))
1174     return 0;
1175   
1176   // Ensure that the larger constant is on the RHS.
1177   bool ShouldSwap;
1178   if (CmpInst::isSigned(LHSCC) ||
1179       (ICmpInst::isEquality(LHSCC) && 
1180        CmpInst::isSigned(RHSCC)))
1181     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1182   else
1183     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1184   
1185   if (ShouldSwap) {
1186     std::swap(LHS, RHS);
1187     std::swap(LHSCst, RHSCst);
1188     std::swap(LHSCC, RHSCC);
1189   }
1190   
1191   // At this point, we know we have two icmp instructions
1192   // comparing a value against two constants and or'ing the result
1193   // together.  Because of the above check, we know that we only have
1194   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1195   // icmp folding check above), that the two constants are not
1196   // equal.
1197   assert(LHSCst != RHSCst && "Compares not folded above?");
1198
1199   switch (LHSCC) {
1200   default: llvm_unreachable("Unknown integer condition code!");
1201   case ICmpInst::ICMP_EQ:
1202     switch (RHSCC) {
1203     default: llvm_unreachable("Unknown integer condition code!");
1204     case ICmpInst::ICMP_EQ:
1205       if (LHSCst == SubOne(RHSCst)) {
1206         // (X == 13 | X == 14) -> X-13 <u 2
1207         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1208         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1209         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1210         return Builder->CreateICmpULT(Add, AddCST);
1211       }
1212       break;                         // (X == 13 | X == 15) -> no change
1213     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1214     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1215       break;
1216     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1217     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1218     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1219       return RHS;
1220     }
1221     break;
1222   case ICmpInst::ICMP_NE:
1223     switch (RHSCC) {
1224     default: llvm_unreachable("Unknown integer condition code!");
1225     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1226     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1227     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1228       return LHS;
1229     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1230     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1231     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1232       return ConstantInt::getTrue(LHS->getContext());
1233     }
1234     break;
1235   case ICmpInst::ICMP_ULT:
1236     switch (RHSCC) {
1237     default: llvm_unreachable("Unknown integer condition code!");
1238     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1239       break;
1240     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1241       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1242       // this can cause overflow.
1243       if (RHSCst->isMaxValue(false))
1244         return LHS;
1245       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1246     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1247       break;
1248     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1249     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1250       return RHS;
1251     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1252       break;
1253     }
1254     break;
1255   case ICmpInst::ICMP_SLT:
1256     switch (RHSCC) {
1257     default: llvm_unreachable("Unknown integer condition code!");
1258     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1259       break;
1260     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1261       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1262       // this can cause overflow.
1263       if (RHSCst->isMaxValue(true))
1264         return LHS;
1265       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1266     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1267       break;
1268     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1269     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1270       return RHS;
1271     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1272       break;
1273     }
1274     break;
1275   case ICmpInst::ICMP_UGT:
1276     switch (RHSCC) {
1277     default: llvm_unreachable("Unknown integer condition code!");
1278     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1279     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1280       return LHS;
1281     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1282       break;
1283     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1284     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1285       return ConstantInt::getTrue(LHS->getContext());
1286     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1287       break;
1288     }
1289     break;
1290   case ICmpInst::ICMP_SGT:
1291     switch (RHSCC) {
1292     default: llvm_unreachable("Unknown integer condition code!");
1293     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1294     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1295       return LHS;
1296     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1297       break;
1298     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1299     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1300       return ConstantInt::getTrue(LHS->getContext());
1301     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1302       break;
1303     }
1304     break;
1305   }
1306   return 0;
1307 }
1308
1309 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1310 /// instcombine, this returns a Value which should already be inserted into the
1311 /// function.
1312 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1313   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1314       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
1315       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1316     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1317       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1318         // If either of the constants are nans, then the whole thing returns
1319         // true.
1320         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1321           return ConstantInt::getTrue(LHS->getContext());
1322         
1323         // Otherwise, no need to compare the two constants, compare the
1324         // rest.
1325         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1326       }
1327     
1328     // Handle vector zeros.  This occurs because the canonical form of
1329     // "fcmp uno x,x" is "fcmp uno x, 0".
1330     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1331         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1332       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1333     
1334     return 0;
1335   }
1336   
1337   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1338   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1339   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1340   
1341   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1342     // Swap RHS operands to match LHS.
1343     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1344     std::swap(Op1LHS, Op1RHS);
1345   }
1346   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1347     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1348     if (Op0CC == Op1CC)
1349       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1350     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1351       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1352     if (Op0CC == FCmpInst::FCMP_FALSE)
1353       return RHS;
1354     if (Op1CC == FCmpInst::FCMP_FALSE)
1355       return LHS;
1356     bool Op0Ordered;
1357     bool Op1Ordered;
1358     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1359     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1360     if (Op0Ordered == Op1Ordered) {
1361       // If both are ordered or unordered, return a new fcmp with
1362       // or'ed predicates.
1363       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1364     }
1365   }
1366   return 0;
1367 }
1368
1369 /// FoldOrWithConstants - This helper function folds:
1370 ///
1371 ///     ((A | B) & C1) | (B & C2)
1372 ///
1373 /// into:
1374 /// 
1375 ///     (A & C1) | B
1376 ///
1377 /// when the XOR of the two constants is "all ones" (-1).
1378 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1379                                                Value *A, Value *B, Value *C) {
1380   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1381   if (!CI1) return 0;
1382
1383   Value *V1 = 0;
1384   ConstantInt *CI2 = 0;
1385   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1386
1387   APInt Xor = CI1->getValue() ^ CI2->getValue();
1388   if (!Xor.isAllOnesValue()) return 0;
1389
1390   if (V1 == A || V1 == B) {
1391     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1392     return BinaryOperator::CreateOr(NewOp, V1);
1393   }
1394
1395   return 0;
1396 }
1397
1398 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1399   bool Changed = SimplifyCommutative(I);
1400   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1401
1402   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1403     return ReplaceInstUsesWith(I, V);
1404
1405   // See if we can simplify any instructions used by the instruction whose sole 
1406   // purpose is to compute bits we don't care about.
1407   if (SimplifyDemandedInstructionBits(I))
1408     return &I;
1409
1410   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1411     ConstantInt *C1 = 0; Value *X = 0;
1412     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1413     // iff (C1 & C2) == 0.
1414     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1415         (RHS->getValue() & C1->getValue()) != 0 &&
1416         Op0->hasOneUse()) {
1417       Value *Or = Builder->CreateOr(X, RHS);
1418       Or->takeName(Op0);
1419       return BinaryOperator::CreateAnd(Or, 
1420                          ConstantInt::get(I.getContext(),
1421                                           RHS->getValue() | C1->getValue()));
1422     }
1423
1424     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1425     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1426         Op0->hasOneUse()) {
1427       Value *Or = Builder->CreateOr(X, RHS);
1428       Or->takeName(Op0);
1429       return BinaryOperator::CreateXor(Or,
1430                  ConstantInt::get(I.getContext(),
1431                                   C1->getValue() & ~RHS->getValue()));
1432     }
1433
1434     // Try to fold constant and into select arguments.
1435     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1436       if (Instruction *R = FoldOpIntoSelect(I, SI))
1437         return R;
1438
1439     if (isa<PHINode>(Op0))
1440       if (Instruction *NV = FoldOpIntoPhi(I))
1441         return NV;
1442   }
1443
1444   Value *A = 0, *B = 0;
1445   ConstantInt *C1 = 0, *C2 = 0;
1446
1447   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1448   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1449   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1450       match(Op1, m_Or(m_Value(), m_Value())) ||
1451       (match(Op0, m_Shift(m_Value(), m_Value())) &&
1452        match(Op1, m_Shift(m_Value(), m_Value())))) {
1453     if (Instruction *BSwap = MatchBSwap(I))
1454       return BSwap;
1455   }
1456   
1457   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1458   if (Op0->hasOneUse() &&
1459       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1460       MaskedValueIsZero(Op1, C1->getValue())) {
1461     Value *NOr = Builder->CreateOr(A, Op1);
1462     NOr->takeName(Op0);
1463     return BinaryOperator::CreateXor(NOr, C1);
1464   }
1465
1466   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1467   if (Op1->hasOneUse() &&
1468       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1469       MaskedValueIsZero(Op0, C1->getValue())) {
1470     Value *NOr = Builder->CreateOr(A, Op0);
1471     NOr->takeName(Op0);
1472     return BinaryOperator::CreateXor(NOr, C1);
1473   }
1474
1475   // (A & C)|(B & D)
1476   Value *C = 0, *D = 0;
1477   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1478       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1479     Value *V1 = 0, *V2 = 0, *V3 = 0;
1480     C1 = dyn_cast<ConstantInt>(C);
1481     C2 = dyn_cast<ConstantInt>(D);
1482     if (C1 && C2) {  // (A & C1)|(B & C2)
1483       // If we have: ((V + N) & C1) | (V & C2)
1484       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1485       // replace with V+N.
1486       if (C1->getValue() == ~C2->getValue()) {
1487         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1488             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1489           // Add commutes, try both ways.
1490           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1491             return ReplaceInstUsesWith(I, A);
1492           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1493             return ReplaceInstUsesWith(I, A);
1494         }
1495         // Or commutes, try both ways.
1496         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1497             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1498           // Add commutes, try both ways.
1499           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1500             return ReplaceInstUsesWith(I, B);
1501           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1502             return ReplaceInstUsesWith(I, B);
1503         }
1504       }
1505       
1506       if ((C1->getValue() & C2->getValue()) == 0) {
1507         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1508         // iff (C1&C2) == 0 and (N&~C1) == 0
1509         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1510             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1511              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1512           return BinaryOperator::CreateAnd(A,
1513                                ConstantInt::get(A->getContext(),
1514                                                 C1->getValue()|C2->getValue()));
1515         // Or commutes, try both ways.
1516         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1517             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1518              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1519           return BinaryOperator::CreateAnd(B,
1520                                ConstantInt::get(B->getContext(),
1521                                                 C1->getValue()|C2->getValue()));
1522         
1523         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1524         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1525         ConstantInt *C3 = 0, *C4 = 0;
1526         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1527             (C3->getValue() & ~C1->getValue()) == 0 &&
1528             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1529             (C4->getValue() & ~C2->getValue()) == 0) {
1530           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1531           return BinaryOperator::CreateAnd(V2,
1532                                ConstantInt::get(B->getContext(),
1533                                                 C1->getValue()|C2->getValue()));
1534         }
1535       }
1536     }
1537     
1538     // Check to see if we have any common things being and'ed.  If so, find the
1539     // terms for V1 & (V2|V3).
1540     if (Op0->hasOneUse() || Op1->hasOneUse()) {
1541       V1 = 0;
1542       if (A == B)      // (A & C)|(A & D) == A & (C|D)
1543         V1 = A, V2 = C, V3 = D;
1544       else if (A == D) // (A & C)|(B & A) == A & (B|C)
1545         V1 = A, V2 = B, V3 = C;
1546       else if (C == B) // (A & C)|(C & D) == C & (A|D)
1547         V1 = C, V2 = A, V3 = D;
1548       else if (C == D) // (A & C)|(B & C) == C & (A|B)
1549         V1 = C, V2 = A, V3 = B;
1550       
1551       if (V1) {
1552         Value *Or = Builder->CreateOr(V2, V3, "tmp");
1553         return BinaryOperator::CreateAnd(V1, Or);
1554       }
1555     }
1556
1557     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
1558     // Don't do this for vector select idioms, the code generator doesn't handle
1559     // them well yet.
1560     if (!I.getType()->isVectorTy()) {
1561       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1562         return Match;
1563       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1564         return Match;
1565       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1566         return Match;
1567       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1568         return Match;
1569     }
1570
1571     // ((A&~B)|(~A&B)) -> A^B
1572     if ((match(C, m_Not(m_Specific(D))) &&
1573          match(B, m_Not(m_Specific(A)))))
1574       return BinaryOperator::CreateXor(A, D);
1575     // ((~B&A)|(~A&B)) -> A^B
1576     if ((match(A, m_Not(m_Specific(D))) &&
1577          match(B, m_Not(m_Specific(C)))))
1578       return BinaryOperator::CreateXor(C, D);
1579     // ((A&~B)|(B&~A)) -> A^B
1580     if ((match(C, m_Not(m_Specific(B))) &&
1581          match(D, m_Not(m_Specific(A)))))
1582       return BinaryOperator::CreateXor(A, B);
1583     // ((~B&A)|(B&~A)) -> A^B
1584     if ((match(A, m_Not(m_Specific(B))) &&
1585          match(D, m_Not(m_Specific(C)))))
1586       return BinaryOperator::CreateXor(C, B);
1587
1588     // ((A|B)&1)|(B&-2) -> (A&1) | B
1589     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1590         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1591       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1592       if (Ret) return Ret;
1593     }
1594     // (B&-2)|((A|B)&1) -> (A&1) | B
1595     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1596         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1597       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1598       if (Ret) return Ret;
1599     }
1600   }
1601   
1602   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1603   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1604     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1605       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1606           SI0->getOperand(1) == SI1->getOperand(1) &&
1607           (SI0->hasOneUse() || SI1->hasOneUse())) {
1608         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1609                                          SI0->getName());
1610         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1611                                       SI1->getOperand(1));
1612       }
1613   }
1614
1615   // (~A | ~B) == (~(A & B)) - De Morgan's Law
1616   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1617     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1618       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1619         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1620                                         I.getName()+".demorgan");
1621         return BinaryOperator::CreateNot(And);
1622       }
1623
1624   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1625     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1626       if (Value *Res = FoldOrOfICmps(LHS, RHS))
1627         return ReplaceInstUsesWith(I, Res);
1628     
1629   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
1630   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1631     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1632       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1633         return ReplaceInstUsesWith(I, Res);
1634   
1635   // fold (or (cast A), (cast B)) -> (cast (or A, B))
1636   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1637     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1638       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1639         const Type *SrcTy = Op0C->getOperand(0)->getType();
1640         if (SrcTy == Op1C->getOperand(0)->getType() &&
1641             SrcTy->isIntOrIntVectorTy()) {
1642           Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1643
1644           if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1645               // Only do this if the casts both really cause code to be
1646               // generated.
1647               ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1648               ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1649             Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1650             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1651           }
1652           
1653           // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1654           // cast is otherwise not optimizable.  This happens for vector sexts.
1655           if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1656             if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1657               if (Value *Res = FoldOrOfICmps(LHS, RHS))
1658                 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1659           
1660           // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1661           // cast is otherwise not optimizable.  This happens for vector sexts.
1662           if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1663             if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1664               if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1665                 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1666         }
1667       }
1668   }
1669   
1670   return Changed ? &I : 0;
1671 }
1672
1673 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1674   bool Changed = SimplifyCommutative(I);
1675   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1676
1677   if (isa<UndefValue>(Op1)) {
1678     if (isa<UndefValue>(Op0))
1679       // Handle undef ^ undef -> 0 special case. This is a common
1680       // idiom (misuse).
1681       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1682     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
1683   }
1684
1685   // xor X, X = 0
1686   if (Op0 == Op1)
1687     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1688   
1689   // See if we can simplify any instructions used by the instruction whose sole 
1690   // purpose is to compute bits we don't care about.
1691   if (SimplifyDemandedInstructionBits(I))
1692     return &I;
1693   if (I.getType()->isVectorTy())
1694     if (isa<ConstantAggregateZero>(Op1))
1695       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
1696
1697   // Is this a ~ operation?
1698   if (Value *NotOp = dyn_castNotVal(&I)) {
1699     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1700       if (Op0I->getOpcode() == Instruction::And || 
1701           Op0I->getOpcode() == Instruction::Or) {
1702         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1703         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1704         if (dyn_castNotVal(Op0I->getOperand(1)))
1705           Op0I->swapOperands();
1706         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1707           Value *NotY =
1708             Builder->CreateNot(Op0I->getOperand(1),
1709                                Op0I->getOperand(1)->getName()+".not");
1710           if (Op0I->getOpcode() == Instruction::And)
1711             return BinaryOperator::CreateOr(Op0NotVal, NotY);
1712           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1713         }
1714         
1715         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1716         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1717         if (isFreeToInvert(Op0I->getOperand(0)) && 
1718             isFreeToInvert(Op0I->getOperand(1))) {
1719           Value *NotX =
1720             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1721           Value *NotY =
1722             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1723           if (Op0I->getOpcode() == Instruction::And)
1724             return BinaryOperator::CreateOr(NotX, NotY);
1725           return BinaryOperator::CreateAnd(NotX, NotY);
1726         }
1727
1728       } else if (Op0I->getOpcode() == Instruction::AShr) {
1729         // ~(~X >>s Y) --> (X >>s Y)
1730         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1731           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
1732       }
1733     }
1734   }
1735   
1736   
1737   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1738     if (RHS->isOne() && Op0->hasOneUse())
1739       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
1740       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
1741         return CmpInst::Create(CI->getOpcode(),
1742                                CI->getInversePredicate(),
1743                                CI->getOperand(0), CI->getOperand(1));
1744
1745     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1746     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1747       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1748         if (CI->hasOneUse() && Op0C->hasOneUse()) {
1749           Instruction::CastOps Opcode = Op0C->getOpcode();
1750           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1751               (RHS == ConstantExpr::getCast(Opcode, 
1752                                            ConstantInt::getTrue(I.getContext()),
1753                                             Op0C->getDestTy()))) {
1754             CI->setPredicate(CI->getInversePredicate());
1755             return CastInst::Create(Opcode, CI, Op0C->getType());
1756           }
1757         }
1758       }
1759     }
1760
1761     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1762       // ~(c-X) == X-c-1 == X+(-c-1)
1763       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1764         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1765           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1766           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1767                                       ConstantInt::get(I.getType(), 1));
1768           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1769         }
1770           
1771       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1772         if (Op0I->getOpcode() == Instruction::Add) {
1773           // ~(X-c) --> (-c-1)-X
1774           if (RHS->isAllOnesValue()) {
1775             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1776             return BinaryOperator::CreateSub(
1777                            ConstantExpr::getSub(NegOp0CI,
1778                                       ConstantInt::get(I.getType(), 1)),
1779                                       Op0I->getOperand(0));
1780           } else if (RHS->getValue().isSignBit()) {
1781             // (X + C) ^ signbit -> (X + C + signbit)
1782             Constant *C = ConstantInt::get(I.getContext(),
1783                                            RHS->getValue() + Op0CI->getValue());
1784             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1785
1786           }
1787         } else if (Op0I->getOpcode() == Instruction::Or) {
1788           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1789           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1790             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1791             // Anything in both C1 and C2 is known to be zero, remove it from
1792             // NewRHS.
1793             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1794             NewRHS = ConstantExpr::getAnd(NewRHS, 
1795                                        ConstantExpr::getNot(CommonBits));
1796             Worklist.Add(Op0I);
1797             I.setOperand(0, Op0I->getOperand(0));
1798             I.setOperand(1, NewRHS);
1799             return &I;
1800           }
1801         }
1802       }
1803     }
1804
1805     // Try to fold constant and into select arguments.
1806     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1807       if (Instruction *R = FoldOpIntoSelect(I, SI))
1808         return R;
1809     if (isa<PHINode>(Op0))
1810       if (Instruction *NV = FoldOpIntoPhi(I))
1811         return NV;
1812   }
1813
1814   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1815     if (X == Op1)
1816       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1817
1818   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1819     if (X == Op0)
1820       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1821
1822   
1823   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1824   if (Op1I) {
1825     Value *A, *B;
1826     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1827       if (A == Op0) {              // B^(B|A) == (A|B)^B
1828         Op1I->swapOperands();
1829         I.swapOperands();
1830         std::swap(Op0, Op1);
1831       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
1832         I.swapOperands();     // Simplified below.
1833         std::swap(Op0, Op1);
1834       }
1835     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1836       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
1837     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1838       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
1839     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
1840                Op1I->hasOneUse()){
1841       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
1842         Op1I->swapOperands();
1843         std::swap(A, B);
1844       }
1845       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
1846         I.swapOperands();     // Simplified below.
1847         std::swap(Op0, Op1);
1848       }
1849     }
1850   }
1851   
1852   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1853   if (Op0I) {
1854     Value *A, *B;
1855     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1856         Op0I->hasOneUse()) {
1857       if (A == Op1)                                  // (B|A)^B == (A|B)^B
1858         std::swap(A, B);
1859       if (B == Op1)                                  // (A|B)^B == A & ~B
1860         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1861     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1862       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
1863     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1864       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
1865     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
1866                Op0I->hasOneUse()){
1867       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
1868         std::swap(A, B);
1869       if (B == Op1 &&                                      // (B&A)^A == ~B & A
1870           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
1871         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1872       }
1873     }
1874   }
1875   
1876   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
1877   if (Op0I && Op1I && Op0I->isShift() && 
1878       Op0I->getOpcode() == Op1I->getOpcode() && 
1879       Op0I->getOperand(1) == Op1I->getOperand(1) &&
1880       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
1881     Value *NewOp =
1882       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1883                          Op0I->getName());
1884     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
1885                                   Op1I->getOperand(1));
1886   }
1887     
1888   if (Op0I && Op1I) {
1889     Value *A, *B, *C, *D;
1890     // (A & B)^(A | B) -> A ^ B
1891     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1892         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1893       if ((A == C && B == D) || (A == D && B == C)) 
1894         return BinaryOperator::CreateXor(A, B);
1895     }
1896     // (A | B)^(A & B) -> A ^ B
1897     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1898         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1899       if ((A == C && B == D) || (A == D && B == C)) 
1900         return BinaryOperator::CreateXor(A, B);
1901     }
1902     
1903     // (A & B)^(C & D)
1904     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1905         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1906         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1907       // (X & Y)^(X & Y) -> (Y^Z) & X
1908       Value *X = 0, *Y = 0, *Z = 0;
1909       if (A == C)
1910         X = A, Y = B, Z = D;
1911       else if (A == D)
1912         X = A, Y = B, Z = C;
1913       else if (B == C)
1914         X = B, Y = A, Z = D;
1915       else if (B == D)
1916         X = B, Y = A, Z = C;
1917       
1918       if (X) {
1919         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1920         return BinaryOperator::CreateAnd(NewOp, X);
1921       }
1922     }
1923   }
1924     
1925   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1926   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1927     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1928       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1929         if (LHS->getOperand(0) == RHS->getOperand(1) &&
1930             LHS->getOperand(1) == RHS->getOperand(0))
1931           LHS->swapOperands();
1932         if (LHS->getOperand(0) == RHS->getOperand(0) &&
1933             LHS->getOperand(1) == RHS->getOperand(1)) {
1934           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1935           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1936           bool isSigned = LHS->isSigned() || RHS->isSigned();
1937           return ReplaceInstUsesWith(I, 
1938                                getICmpValue(isSigned, Code, Op0, Op1, Builder));
1939         }
1940       }
1941
1942   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1943   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1944     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1945       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1946         const Type *SrcTy = Op0C->getOperand(0)->getType();
1947         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
1948             // Only do this if the casts both really cause code to be generated.
1949             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0), 
1950                                I.getType()) &&
1951             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0), 
1952                                I.getType())) {
1953           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1954                                             Op1C->getOperand(0), I.getName());
1955           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1956         }
1957       }
1958   }
1959
1960   return Changed ? &I : 0;
1961 }