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