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