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