OSDN Git Service

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