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