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