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