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