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