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