tidy up a bit.
[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       if (A == Op0)                                // A&(A^B) -> A & ~B
1144         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
1145     }
1146
1147     // (A&((~A)|B)) -> A&B
1148     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1149         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1150       return BinaryOperator::CreateAnd(A, Op1);
1151     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1152         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1153       return BinaryOperator::CreateAnd(A, Op0);
1154   }
1155   
1156   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1157     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1158       if (Value *Res = FoldAndOfICmps(LHS, RHS))
1159         return ReplaceInstUsesWith(I, Res);
1160   
1161   // If and'ing two fcmp, try combine them into one.
1162   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1163     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1164       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1165         return ReplaceInstUsesWith(I, Res);
1166   
1167   
1168   // fold (and (cast A), (cast B)) -> (cast (and A, B))
1169   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1170     if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1171       const Type *SrcTy = Op0C->getOperand(0)->getType();
1172       if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1173           SrcTy == Op1C->getOperand(0)->getType() &&
1174           SrcTy->isIntOrIntVectorTy()) {
1175         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1176         
1177         // Only do this if the casts both really cause code to be generated.
1178         if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1179             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1180           Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1181           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1182         }
1183         
1184         // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1185         // cast is otherwise not optimizable.  This happens for vector sexts.
1186         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1187           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1188             if (Value *Res = FoldAndOfICmps(LHS, RHS))
1189               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1190         
1191         // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1192         // cast is otherwise not optimizable.  This happens for vector sexts.
1193         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1194           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1195             if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1196               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1197       }
1198     }
1199     
1200   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
1201   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1202     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1203       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1204           SI0->getOperand(1) == SI1->getOperand(1) &&
1205           (SI0->hasOneUse() || SI1->hasOneUse())) {
1206         Value *NewOp =
1207           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1208                              SI0->getName());
1209         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1210                                       SI1->getOperand(1));
1211       }
1212   }
1213
1214   return Changed ? &I : 0;
1215 }
1216
1217 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1218 /// capable of providing pieces of a bswap.  The subexpression provides pieces
1219 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1220 /// the expression came from the corresponding "byte swapped" byte in some other
1221 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
1222 /// we know that the expression deposits the low byte of %X into the high byte
1223 /// of the bswap result and that all other bytes are zero.  This expression is
1224 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1225 /// match.
1226 ///
1227 /// This function returns true if the match was unsuccessful and false if so.
1228 /// On entry to the function the "OverallLeftShift" is a signed integer value
1229 /// indicating the number of bytes that the subexpression is later shifted.  For
1230 /// example, if the expression is later right shifted by 16 bits, the
1231 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
1232 /// byte of ByteValues is actually being set.
1233 ///
1234 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1235 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
1236 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
1237 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
1238 /// always in the local (OverallLeftShift) coordinate space.
1239 ///
1240 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1241                               SmallVector<Value*, 8> &ByteValues) {
1242   if (Instruction *I = dyn_cast<Instruction>(V)) {
1243     // If this is an or instruction, it may be an inner node of the bswap.
1244     if (I->getOpcode() == Instruction::Or) {
1245       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1246                                ByteValues) ||
1247              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1248                                ByteValues);
1249     }
1250   
1251     // If this is a logical shift by a constant multiple of 8, recurse with
1252     // OverallLeftShift and ByteMask adjusted.
1253     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1254       unsigned ShAmt = 
1255         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1256       // Ensure the shift amount is defined and of a byte value.
1257       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1258         return true;
1259
1260       unsigned ByteShift = ShAmt >> 3;
1261       if (I->getOpcode() == Instruction::Shl) {
1262         // X << 2 -> collect(X, +2)
1263         OverallLeftShift += ByteShift;
1264         ByteMask >>= ByteShift;
1265       } else {
1266         // X >>u 2 -> collect(X, -2)
1267         OverallLeftShift -= ByteShift;
1268         ByteMask <<= ByteShift;
1269         ByteMask &= (~0U >> (32-ByteValues.size()));
1270       }
1271
1272       if (OverallLeftShift >= (int)ByteValues.size()) return true;
1273       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1274
1275       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1276                                ByteValues);
1277     }
1278
1279     // If this is a logical 'and' with a mask that clears bytes, clear the
1280     // corresponding bytes in ByteMask.
1281     if (I->getOpcode() == Instruction::And &&
1282         isa<ConstantInt>(I->getOperand(1))) {
1283       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1284       unsigned NumBytes = ByteValues.size();
1285       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1286       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1287       
1288       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1289         // If this byte is masked out by a later operation, we don't care what
1290         // the and mask is.
1291         if ((ByteMask & (1 << i)) == 0)
1292           continue;
1293         
1294         // If the AndMask is all zeros for this byte, clear the bit.
1295         APInt MaskB = AndMask & Byte;
1296         if (MaskB == 0) {
1297           ByteMask &= ~(1U << i);
1298           continue;
1299         }
1300         
1301         // If the AndMask is not all ones for this byte, it's not a bytezap.
1302         if (MaskB != Byte)
1303           return true;
1304
1305         // Otherwise, this byte is kept.
1306       }
1307
1308       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
1309                                ByteValues);
1310     }
1311   }
1312   
1313   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
1314   // the input value to the bswap.  Some observations: 1) if more than one byte
1315   // is demanded from this input, then it could not be successfully assembled
1316   // into a byteswap.  At least one of the two bytes would not be aligned with
1317   // their ultimate destination.
1318   if (!isPowerOf2_32(ByteMask)) return true;
1319   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1320   
1321   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1322   // is demanded, it needs to go into byte 0 of the result.  This means that the
1323   // byte needs to be shifted until it lands in the right byte bucket.  The
1324   // shift amount depends on the position: if the byte is coming from the high
1325   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
1326   // low part, it must be shifted left.
1327   unsigned DestByteNo = InputByteNo + OverallLeftShift;
1328   if (InputByteNo < ByteValues.size()/2) {
1329     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1330       return true;
1331   } else {
1332     if (ByteValues.size()-1-DestByteNo != InputByteNo)
1333       return true;
1334   }
1335   
1336   // If the destination byte value is already defined, the values are or'd
1337   // together, which isn't a bswap (unless it's an or of the same bits).
1338   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1339     return true;
1340   ByteValues[DestByteNo] = V;
1341   return false;
1342 }
1343
1344 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1345 /// If so, insert the new bswap intrinsic and return it.
1346 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1347   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1348   if (!ITy || ITy->getBitWidth() % 16 || 
1349       // ByteMask only allows up to 32-byte values.
1350       ITy->getBitWidth() > 32*8) 
1351     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
1352   
1353   /// ByteValues - For each byte of the result, we keep track of which value
1354   /// defines each byte.
1355   SmallVector<Value*, 8> ByteValues;
1356   ByteValues.resize(ITy->getBitWidth()/8);
1357     
1358   // Try to find all the pieces corresponding to the bswap.
1359   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1360   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1361     return 0;
1362   
1363   // Check to see if all of the bytes come from the same value.
1364   Value *V = ByteValues[0];
1365   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
1366   
1367   // Check to make sure that all of the bytes come from the same value.
1368   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1369     if (ByteValues[i] != V)
1370       return 0;
1371   const Type *Tys[] = { ITy };
1372   Module *M = I.getParent()->getParent()->getParent();
1373   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1374   return CallInst::Create(F, V);
1375 }
1376
1377 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
1378 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1379 /// we can simplify this expression to "cond ? C : D or B".
1380 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1381                                          Value *C, Value *D) {
1382   // If A is not a select of -1/0, this cannot match.
1383   Value *Cond = 0;
1384   if (!match(A, m_SExt(m_Value(Cond))) ||
1385       !Cond->getType()->isIntegerTy(1))
1386     return 0;
1387
1388   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1389   if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1390     return SelectInst::Create(Cond, C, B);
1391   if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1392     return SelectInst::Create(Cond, C, B);
1393   
1394   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1395   if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1396     return SelectInst::Create(Cond, C, D);
1397   if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1398     return SelectInst::Create(Cond, C, D);
1399   return 0;
1400 }
1401
1402 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1403 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1404   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1405
1406   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1407   if (PredicatesFoldable(LHSCC, RHSCC)) {
1408     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1409         LHS->getOperand(1) == RHS->getOperand(0))
1410       LHS->swapOperands();
1411     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1412         LHS->getOperand(1) == RHS->getOperand(1)) {
1413       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1414       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1415       bool isSigned = LHS->isSigned() || RHS->isSigned();
1416       return getICmpValue(isSigned, Code, Op0, Op1, Builder);
1417     }
1418   }
1419
1420   // handle (roughly):
1421   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1422   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1423     return V;
1424
1425   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1426   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1427   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1428   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1429   if (LHSCst == 0 || RHSCst == 0) return 0;
1430
1431   if (LHSCst == RHSCst && LHSCC == RHSCC) {
1432     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1433     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1434       Value *NewOr = Builder->CreateOr(Val, Val2);
1435       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1436     }
1437   }
1438
1439   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1440   //   iff C2 + CA == C1.
1441   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1442     ConstantInt *AddCst;
1443     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1444       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1445         return Builder->CreateICmpULE(Val, LHSCst);
1446   }
1447
1448   // From here on, we only handle:
1449   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1450   if (Val != Val2) return 0;
1451   
1452   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1453   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1454       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1455       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1456       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1457     return 0;
1458   
1459   // We can't fold (ugt x, C) | (sgt x, C2).
1460   if (!PredicatesFoldable(LHSCC, RHSCC))
1461     return 0;
1462   
1463   // Ensure that the larger constant is on the RHS.
1464   bool ShouldSwap;
1465   if (CmpInst::isSigned(LHSCC) ||
1466       (ICmpInst::isEquality(LHSCC) && 
1467        CmpInst::isSigned(RHSCC)))
1468     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1469   else
1470     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1471   
1472   if (ShouldSwap) {
1473     std::swap(LHS, RHS);
1474     std::swap(LHSCst, RHSCst);
1475     std::swap(LHSCC, RHSCC);
1476   }
1477   
1478   // At this point, we know we have two icmp instructions
1479   // comparing a value against two constants and or'ing the result
1480   // together.  Because of the above check, we know that we only have
1481   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1482   // icmp folding check above), that the two constants are not
1483   // equal.
1484   assert(LHSCst != RHSCst && "Compares not folded above?");
1485
1486   switch (LHSCC) {
1487   default: llvm_unreachable("Unknown integer condition code!");
1488   case ICmpInst::ICMP_EQ:
1489     switch (RHSCC) {
1490     default: llvm_unreachable("Unknown integer condition code!");
1491     case ICmpInst::ICMP_EQ:
1492       if (LHSCst == SubOne(RHSCst)) {
1493         // (X == 13 | X == 14) -> X-13 <u 2
1494         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1495         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1496         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1497         return Builder->CreateICmpULT(Add, AddCST);
1498       }
1499       break;                         // (X == 13 | X == 15) -> no change
1500     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1501     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1502       break;
1503     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1504     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1505     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1506       return RHS;
1507     }
1508     break;
1509   case ICmpInst::ICMP_NE:
1510     switch (RHSCC) {
1511     default: llvm_unreachable("Unknown integer condition code!");
1512     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1513     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1514     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1515       return LHS;
1516     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1517     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1518     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1519       return ConstantInt::getTrue(LHS->getContext());
1520     }
1521     break;
1522   case ICmpInst::ICMP_ULT:
1523     switch (RHSCC) {
1524     default: llvm_unreachable("Unknown integer condition code!");
1525     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1526       break;
1527     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1528       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1529       // this can cause overflow.
1530       if (RHSCst->isMaxValue(false))
1531         return LHS;
1532       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1533     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1534       break;
1535     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1536     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1537       return RHS;
1538     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1539       break;
1540     }
1541     break;
1542   case ICmpInst::ICMP_SLT:
1543     switch (RHSCC) {
1544     default: llvm_unreachable("Unknown integer condition code!");
1545     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1546       break;
1547     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1548       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1549       // this can cause overflow.
1550       if (RHSCst->isMaxValue(true))
1551         return LHS;
1552       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1553     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1554       break;
1555     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1556     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1557       return RHS;
1558     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1559       break;
1560     }
1561     break;
1562   case ICmpInst::ICMP_UGT:
1563     switch (RHSCC) {
1564     default: llvm_unreachable("Unknown integer condition code!");
1565     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1566     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1567       return LHS;
1568     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1569       break;
1570     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1571     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1572       return ConstantInt::getTrue(LHS->getContext());
1573     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1574       break;
1575     }
1576     break;
1577   case ICmpInst::ICMP_SGT:
1578     switch (RHSCC) {
1579     default: llvm_unreachable("Unknown integer condition code!");
1580     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1581     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1582       return LHS;
1583     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1584       break;
1585     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
1586     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
1587       return ConstantInt::getTrue(LHS->getContext());
1588     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
1589       break;
1590     }
1591     break;
1592   }
1593   return 0;
1594 }
1595
1596 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of
1597 /// instcombine, this returns a Value which should already be inserted into the
1598 /// function.
1599 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1600   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1601       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
1602       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1603     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1604       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1605         // If either of the constants are nans, then the whole thing returns
1606         // true.
1607         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1608           return ConstantInt::getTrue(LHS->getContext());
1609         
1610         // Otherwise, no need to compare the two constants, compare the
1611         // rest.
1612         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1613       }
1614     
1615     // Handle vector zeros.  This occurs because the canonical form of
1616     // "fcmp uno x,x" is "fcmp uno x, 0".
1617     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1618         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1619       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1620     
1621     return 0;
1622   }
1623   
1624   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1625   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1626   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1627   
1628   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1629     // Swap RHS operands to match LHS.
1630     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1631     std::swap(Op1LHS, Op1RHS);
1632   }
1633   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1634     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1635     if (Op0CC == Op1CC)
1636       return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1637     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1638       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1639     if (Op0CC == FCmpInst::FCMP_FALSE)
1640       return RHS;
1641     if (Op1CC == FCmpInst::FCMP_FALSE)
1642       return LHS;
1643     bool Op0Ordered;
1644     bool Op1Ordered;
1645     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1646     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1647     if (Op0Ordered == Op1Ordered) {
1648       // If both are ordered or unordered, return a new fcmp with
1649       // or'ed predicates.
1650       return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1651     }
1652   }
1653   return 0;
1654 }
1655
1656 /// FoldOrWithConstants - This helper function folds:
1657 ///
1658 ///     ((A | B) & C1) | (B & C2)
1659 ///
1660 /// into:
1661 /// 
1662 ///     (A & C1) | B
1663 ///
1664 /// when the XOR of the two constants is "all ones" (-1).
1665 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1666                                                Value *A, Value *B, Value *C) {
1667   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1668   if (!CI1) return 0;
1669
1670   Value *V1 = 0;
1671   ConstantInt *CI2 = 0;
1672   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1673
1674   APInt Xor = CI1->getValue() ^ CI2->getValue();
1675   if (!Xor.isAllOnesValue()) return 0;
1676
1677   if (V1 == A || V1 == B) {
1678     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1679     return BinaryOperator::CreateOr(NewOp, V1);
1680   }
1681
1682   return 0;
1683 }
1684
1685 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1686   bool Changed = SimplifyAssociativeOrCommutative(I);
1687   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1688
1689   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1690     return ReplaceInstUsesWith(I, V);
1691
1692   // (A&B)|(A&C) -> A&(B|C) etc
1693   if (Value *V = SimplifyUsingDistributiveLaws(I))
1694     return ReplaceInstUsesWith(I, V);
1695
1696   // See if we can simplify any instructions used by the instruction whose sole 
1697   // purpose is to compute bits we don't care about.
1698   if (SimplifyDemandedInstructionBits(I))
1699     return &I;
1700
1701   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1702     ConstantInt *C1 = 0; Value *X = 0;
1703     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1704     // iff (C1 & C2) == 0.
1705     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1706         (RHS->getValue() & C1->getValue()) != 0 &&
1707         Op0->hasOneUse()) {
1708       Value *Or = Builder->CreateOr(X, RHS);
1709       Or->takeName(Op0);
1710       return BinaryOperator::CreateAnd(Or, 
1711                          ConstantInt::get(I.getContext(),
1712                                           RHS->getValue() | C1->getValue()));
1713     }
1714
1715     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1716     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1717         Op0->hasOneUse()) {
1718       Value *Or = Builder->CreateOr(X, RHS);
1719       Or->takeName(Op0);
1720       return BinaryOperator::CreateXor(Or,
1721                  ConstantInt::get(I.getContext(),
1722                                   C1->getValue() & ~RHS->getValue()));
1723     }
1724
1725     // Try to fold constant and into select arguments.
1726     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1727       if (Instruction *R = FoldOpIntoSelect(I, SI))
1728         return R;
1729
1730     if (isa<PHINode>(Op0))
1731       if (Instruction *NV = FoldOpIntoPhi(I))
1732         return NV;
1733   }
1734
1735   Value *A = 0, *B = 0;
1736   ConstantInt *C1 = 0, *C2 = 0;
1737
1738   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1739   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1740   if (match(Op0, m_Or(m_Value(), m_Value())) ||
1741       match(Op1, m_Or(m_Value(), m_Value())) ||
1742       (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1743        match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1744     if (Instruction *BSwap = MatchBSwap(I))
1745       return BSwap;
1746   }
1747   
1748   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1749   if (Op0->hasOneUse() &&
1750       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1751       MaskedValueIsZero(Op1, C1->getValue())) {
1752     Value *NOr = Builder->CreateOr(A, Op1);
1753     NOr->takeName(Op0);
1754     return BinaryOperator::CreateXor(NOr, C1);
1755   }
1756
1757   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1758   if (Op1->hasOneUse() &&
1759       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1760       MaskedValueIsZero(Op0, C1->getValue())) {
1761     Value *NOr = Builder->CreateOr(A, Op0);
1762     NOr->takeName(Op0);
1763     return BinaryOperator::CreateXor(NOr, C1);
1764   }
1765
1766   // (A & C)|(B & D)
1767   Value *C = 0, *D = 0;
1768   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1769       match(Op1, m_And(m_Value(B), m_Value(D)))) {
1770     Value *V1 = 0, *V2 = 0;
1771     C1 = dyn_cast<ConstantInt>(C);
1772     C2 = dyn_cast<ConstantInt>(D);
1773     if (C1 && C2) {  // (A & C1)|(B & C2)
1774       // If we have: ((V + N) & C1) | (V & C2)
1775       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1776       // replace with V+N.
1777       if (C1->getValue() == ~C2->getValue()) {
1778         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1779             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1780           // Add commutes, try both ways.
1781           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1782             return ReplaceInstUsesWith(I, A);
1783           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1784             return ReplaceInstUsesWith(I, A);
1785         }
1786         // Or commutes, try both ways.
1787         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1788             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1789           // Add commutes, try both ways.
1790           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1791             return ReplaceInstUsesWith(I, B);
1792           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1793             return ReplaceInstUsesWith(I, B);
1794         }
1795       }
1796       
1797       if ((C1->getValue() & C2->getValue()) == 0) {
1798         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1799         // iff (C1&C2) == 0 and (N&~C1) == 0
1800         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1801             ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) ||  // (V|N)
1802              (V2 == B && MaskedValueIsZero(V1, ~C1->getValue()))))   // (N|V)
1803           return BinaryOperator::CreateAnd(A,
1804                                ConstantInt::get(A->getContext(),
1805                                                 C1->getValue()|C2->getValue()));
1806         // Or commutes, try both ways.
1807         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1808             ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) ||  // (V|N)
1809              (V2 == A && MaskedValueIsZero(V1, ~C2->getValue()))))   // (N|V)
1810           return BinaryOperator::CreateAnd(B,
1811                                ConstantInt::get(B->getContext(),
1812                                                 C1->getValue()|C2->getValue()));
1813         
1814         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1815         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1816         ConstantInt *C3 = 0, *C4 = 0;
1817         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1818             (C3->getValue() & ~C1->getValue()) == 0 &&
1819             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1820             (C4->getValue() & ~C2->getValue()) == 0) {
1821           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1822           return BinaryOperator::CreateAnd(V2,
1823                                ConstantInt::get(B->getContext(),
1824                                                 C1->getValue()|C2->getValue()));
1825         }
1826       }
1827     }
1828
1829     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants.
1830     // Don't do this for vector select idioms, the code generator doesn't handle
1831     // them well yet.
1832     if (!I.getType()->isVectorTy()) {
1833       if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1834         return Match;
1835       if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1836         return Match;
1837       if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1838         return Match;
1839       if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1840         return Match;
1841     }
1842
1843     // ((A&~B)|(~A&B)) -> A^B
1844     if ((match(C, m_Not(m_Specific(D))) &&
1845          match(B, m_Not(m_Specific(A)))))
1846       return BinaryOperator::CreateXor(A, D);
1847     // ((~B&A)|(~A&B)) -> A^B
1848     if ((match(A, m_Not(m_Specific(D))) &&
1849          match(B, m_Not(m_Specific(C)))))
1850       return BinaryOperator::CreateXor(C, D);
1851     // ((A&~B)|(B&~A)) -> A^B
1852     if ((match(C, m_Not(m_Specific(B))) &&
1853          match(D, m_Not(m_Specific(A)))))
1854       return BinaryOperator::CreateXor(A, B);
1855     // ((~B&A)|(B&~A)) -> A^B
1856     if ((match(A, m_Not(m_Specific(B))) &&
1857          match(D, m_Not(m_Specific(C)))))
1858       return BinaryOperator::CreateXor(C, B);
1859
1860     // ((A|B)&1)|(B&-2) -> (A&1) | B
1861     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1862         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1863       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1864       if (Ret) return Ret;
1865     }
1866     // (B&-2)|((A|B)&1) -> (A&1) | B
1867     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1868         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1869       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1870       if (Ret) return Ret;
1871     }
1872   }
1873   
1874   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
1875   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1876     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1877       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
1878           SI0->getOperand(1) == SI1->getOperand(1) &&
1879           (SI0->hasOneUse() || SI1->hasOneUse())) {
1880         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1881                                          SI0->getName());
1882         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
1883                                       SI1->getOperand(1));
1884       }
1885   }
1886
1887   // (~A | ~B) == (~(A & B)) - De Morgan's Law
1888   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1889     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1890       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1891         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1892                                         I.getName()+".demorgan");
1893         return BinaryOperator::CreateNot(And);
1894       }
1895
1896   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1897     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1898       if (Value *Res = FoldOrOfICmps(LHS, RHS))
1899         return ReplaceInstUsesWith(I, Res);
1900     
1901   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
1902   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1903     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1904       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1905         return ReplaceInstUsesWith(I, Res);
1906   
1907   // fold (or (cast A), (cast B)) -> (cast (or A, B))
1908   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1909     CastInst *Op1C = dyn_cast<CastInst>(Op1);
1910     if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1911       const Type *SrcTy = Op0C->getOperand(0)->getType();
1912       if (SrcTy == Op1C->getOperand(0)->getType() &&
1913           SrcTy->isIntOrIntVectorTy()) {
1914         Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1915
1916         if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
1917             // Only do this if the casts both really cause code to be
1918             // generated.
1919             ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1920             ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1921           Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
1922           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1923         }
1924         
1925         // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1926         // cast is otherwise not optimizable.  This happens for vector sexts.
1927         if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1928           if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1929             if (Value *Res = FoldOrOfICmps(LHS, RHS))
1930               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1931         
1932         // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1933         // cast is otherwise not optimizable.  This happens for vector sexts.
1934         if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1935           if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1936             if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1937               return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1938       }
1939     }
1940   }
1941   
1942   // Note: If we've gotten to the point of visiting the outer OR, then the
1943   // inner one couldn't be simplified.  If it was a constant, then it won't
1944   // be simplified by a later pass either, so we try swapping the inner/outer
1945   // ORs in the hopes that we'll be able to simplify it this way.
1946   // (X|C) | V --> (X|V) | C
1947   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
1948       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
1949     Value *Inner = Builder->CreateOr(A, Op1);
1950     Inner->takeName(Op0);
1951     return BinaryOperator::CreateOr(Inner, C1);
1952   }
1953   
1954   return Changed ? &I : 0;
1955 }
1956
1957 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1958   bool Changed = SimplifyAssociativeOrCommutative(I);
1959   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1960
1961   if (Value *V = SimplifyXorInst(Op0, Op1, TD))
1962     return ReplaceInstUsesWith(I, V);
1963
1964   // (A&B)^(A&C) -> A&(B^C) etc
1965   if (Value *V = SimplifyUsingDistributiveLaws(I))
1966     return ReplaceInstUsesWith(I, V);
1967
1968   // See if we can simplify any instructions used by the instruction whose sole 
1969   // purpose is to compute bits we don't care about.
1970   if (SimplifyDemandedInstructionBits(I))
1971     return &I;
1972
1973   // Is this a ~ operation?
1974   if (Value *NotOp = dyn_castNotVal(&I)) {
1975     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1976       if (Op0I->getOpcode() == Instruction::And || 
1977           Op0I->getOpcode() == Instruction::Or) {
1978         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1979         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1980         if (dyn_castNotVal(Op0I->getOperand(1)))
1981           Op0I->swapOperands();
1982         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1983           Value *NotY =
1984             Builder->CreateNot(Op0I->getOperand(1),
1985                                Op0I->getOperand(1)->getName()+".not");
1986           if (Op0I->getOpcode() == Instruction::And)
1987             return BinaryOperator::CreateOr(Op0NotVal, NotY);
1988           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1989         }
1990         
1991         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1992         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1993         if (isFreeToInvert(Op0I->getOperand(0)) && 
1994             isFreeToInvert(Op0I->getOperand(1))) {
1995           Value *NotX =
1996             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1997           Value *NotY =
1998             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1999           if (Op0I->getOpcode() == Instruction::And)
2000             return BinaryOperator::CreateOr(NotX, NotY);
2001           return BinaryOperator::CreateAnd(NotX, NotY);
2002         }
2003
2004       } else if (Op0I->getOpcode() == Instruction::AShr) {
2005         // ~(~X >>s Y) --> (X >>s Y)
2006         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2007           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2008       }
2009     }
2010   }
2011   
2012   
2013   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2014     if (RHS->isOne() && Op0->hasOneUse())
2015       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2016       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2017         return CmpInst::Create(CI->getOpcode(),
2018                                CI->getInversePredicate(),
2019                                CI->getOperand(0), CI->getOperand(1));
2020
2021     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2022     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2023       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2024         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2025           Instruction::CastOps Opcode = Op0C->getOpcode();
2026           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2027               (RHS == ConstantExpr::getCast(Opcode, 
2028                                            ConstantInt::getTrue(I.getContext()),
2029                                             Op0C->getDestTy()))) {
2030             CI->setPredicate(CI->getInversePredicate());
2031             return CastInst::Create(Opcode, CI, Op0C->getType());
2032           }
2033         }
2034       }
2035     }
2036
2037     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2038       // ~(c-X) == X-c-1 == X+(-c-1)
2039       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2040         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2041           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2042           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2043                                       ConstantInt::get(I.getType(), 1));
2044           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2045         }
2046           
2047       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2048         if (Op0I->getOpcode() == Instruction::Add) {
2049           // ~(X-c) --> (-c-1)-X
2050           if (RHS->isAllOnesValue()) {
2051             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2052             return BinaryOperator::CreateSub(
2053                            ConstantExpr::getSub(NegOp0CI,
2054                                       ConstantInt::get(I.getType(), 1)),
2055                                       Op0I->getOperand(0));
2056           } else if (RHS->getValue().isSignBit()) {
2057             // (X + C) ^ signbit -> (X + C + signbit)
2058             Constant *C = ConstantInt::get(I.getContext(),
2059                                            RHS->getValue() + Op0CI->getValue());
2060             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2061
2062           }
2063         } else if (Op0I->getOpcode() == Instruction::Or) {
2064           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2065           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2066             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2067             // Anything in both C1 and C2 is known to be zero, remove it from
2068             // NewRHS.
2069             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2070             NewRHS = ConstantExpr::getAnd(NewRHS, 
2071                                        ConstantExpr::getNot(CommonBits));
2072             Worklist.Add(Op0I);
2073             I.setOperand(0, Op0I->getOperand(0));
2074             I.setOperand(1, NewRHS);
2075             return &I;
2076           }
2077         }
2078       }
2079     }
2080
2081     // Try to fold constant and into select arguments.
2082     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2083       if (Instruction *R = FoldOpIntoSelect(I, SI))
2084         return R;
2085     if (isa<PHINode>(Op0))
2086       if (Instruction *NV = FoldOpIntoPhi(I))
2087         return NV;
2088   }
2089
2090   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2091   if (Op1I) {
2092     Value *A, *B;
2093     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2094       if (A == Op0) {              // B^(B|A) == (A|B)^B
2095         Op1I->swapOperands();
2096         I.swapOperands();
2097         std::swap(Op0, Op1);
2098       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2099         I.swapOperands();     // Simplified below.
2100         std::swap(Op0, Op1);
2101       }
2102     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
2103                Op1I->hasOneUse()){
2104       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2105         Op1I->swapOperands();
2106         std::swap(A, B);
2107       }
2108       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2109         I.swapOperands();     // Simplified below.
2110         std::swap(Op0, Op1);
2111       }
2112     }
2113   }
2114   
2115   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2116   if (Op0I) {
2117     Value *A, *B;
2118     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2119         Op0I->hasOneUse()) {
2120       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2121         std::swap(A, B);
2122       if (B == Op1)                                  // (A|B)^B == A & ~B
2123         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
2124     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
2125                Op0I->hasOneUse()){
2126       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2127         std::swap(A, B);
2128       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2129           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2130         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
2131       }
2132     }
2133   }
2134   
2135   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
2136   if (Op0I && Op1I && Op0I->isShift() && 
2137       Op0I->getOpcode() == Op1I->getOpcode() && 
2138       Op0I->getOperand(1) == Op1I->getOperand(1) &&
2139       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
2140     Value *NewOp =
2141       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2142                          Op0I->getName());
2143     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
2144                                   Op1I->getOperand(1));
2145   }
2146     
2147   if (Op0I && Op1I) {
2148     Value *A, *B, *C, *D;
2149     // (A & B)^(A | B) -> A ^ B
2150     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2151         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2152       if ((A == C && B == D) || (A == D && B == C)) 
2153         return BinaryOperator::CreateXor(A, B);
2154     }
2155     // (A | B)^(A & B) -> A ^ B
2156     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2157         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2158       if ((A == C && B == D) || (A == D && B == C)) 
2159         return BinaryOperator::CreateXor(A, B);
2160     }
2161   }
2162
2163   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2164   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2165     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2166       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2167         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2168             LHS->getOperand(1) == RHS->getOperand(0))
2169           LHS->swapOperands();
2170         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2171             LHS->getOperand(1) == RHS->getOperand(1)) {
2172           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2173           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2174           bool isSigned = LHS->isSigned() || RHS->isSigned();
2175           return ReplaceInstUsesWith(I, 
2176                                getICmpValue(isSigned, Code, Op0, Op1, Builder));
2177         }
2178       }
2179
2180   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2181   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2182     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2183       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2184         const Type *SrcTy = Op0C->getOperand(0)->getType();
2185         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2186             // Only do this if the casts both really cause code to be generated.
2187             ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0), 
2188                                I.getType()) &&
2189             ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0), 
2190                                I.getType())) {
2191           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2192                                             Op1C->getOperand(0), I.getName());
2193           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2194         }
2195       }
2196   }
2197
2198   return Changed ? &I : 0;
2199 }