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