1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitAnd, visitOr, and visitXor functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/Analysis/CmpInstAnalysis.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/InstCombine/InstCombiner.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
28 /// a four bit mask.
29 static unsigned getFCmpCode(FCmpInst::Predicate CC) {
30   assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
31          "Unexpected FCmp predicate!");
32   // Take advantage of the bit pattern of FCmpInst::Predicate here.
33   //                                                 U L G E
34   static_assert(FCmpInst::FCMP_FALSE ==  0, "");  // 0 0 0 0
35   static_assert(FCmpInst::FCMP_OEQ   ==  1, "");  // 0 0 0 1
36   static_assert(FCmpInst::FCMP_OGT   ==  2, "");  // 0 0 1 0
37   static_assert(FCmpInst::FCMP_OGE   ==  3, "");  // 0 0 1 1
38   static_assert(FCmpInst::FCMP_OLT   ==  4, "");  // 0 1 0 0
39   static_assert(FCmpInst::FCMP_OLE   ==  5, "");  // 0 1 0 1
40   static_assert(FCmpInst::FCMP_ONE   ==  6, "");  // 0 1 1 0
41   static_assert(FCmpInst::FCMP_ORD   ==  7, "");  // 0 1 1 1
42   static_assert(FCmpInst::FCMP_UNO   ==  8, "");  // 1 0 0 0
43   static_assert(FCmpInst::FCMP_UEQ   ==  9, "");  // 1 0 0 1
44   static_assert(FCmpInst::FCMP_UGT   == 10, "");  // 1 0 1 0
45   static_assert(FCmpInst::FCMP_UGE   == 11, "");  // 1 0 1 1
46   static_assert(FCmpInst::FCMP_ULT   == 12, "");  // 1 1 0 0
47   static_assert(FCmpInst::FCMP_ULE   == 13, "");  // 1 1 0 1
48   static_assert(FCmpInst::FCMP_UNE   == 14, "");  // 1 1 1 0
49   static_assert(FCmpInst::FCMP_TRUE  == 15, "");  // 1 1 1 1
50   return CC;
51 }
52 
53 /// This is the complement of getICmpCode, which turns an opcode and two
54 /// operands into either a constant true or false, or a brand new ICmp
55 /// instruction. The sign is passed in to determine which kind of predicate to
56 /// use in the new icmp instruction.
57 static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
58                               InstCombiner::BuilderTy &Builder) {
59   ICmpInst::Predicate NewPred;
60   if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
61     return TorF;
62   return Builder.CreateICmp(NewPred, LHS, RHS);
63 }
64 
65 /// This is the complement of getFCmpCode, which turns an opcode and two
66 /// operands into either a FCmp instruction, or a true/false constant.
67 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
68                            InstCombiner::BuilderTy &Builder) {
69   const auto Pred = static_cast<FCmpInst::Predicate>(Code);
70   assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
71          "Unexpected FCmp predicate!");
72   if (Pred == FCmpInst::FCMP_FALSE)
73     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
74   if (Pred == FCmpInst::FCMP_TRUE)
75     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
76   return Builder.CreateFCmp(Pred, LHS, RHS);
77 }
78 
79 /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or
80 /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B))
81 /// \param I Binary operator to transform.
82 /// \return Pointer to node that must replace the original binary operator, or
83 ///         null pointer if no transformation was made.
84 static Value *SimplifyBSwap(BinaryOperator &I,
85                             InstCombiner::BuilderTy &Builder) {
86   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
87 
88   Value *OldLHS = I.getOperand(0);
89   Value *OldRHS = I.getOperand(1);
90 
91   Value *NewLHS;
92   if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
93     return nullptr;
94 
95   Value *NewRHS;
96   const APInt *C;
97 
98   if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
99     // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
100     if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
101       return nullptr;
102     // NewRHS initialized by the matcher.
103   } else if (match(OldRHS, m_APInt(C))) {
104     // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
105     if (!OldLHS->hasOneUse())
106       return nullptr;
107     NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
108   } else
109     return nullptr;
110 
111   Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
112   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
113                                           I.getType());
114   return Builder.CreateCall(F, BinOp);
115 }
116 
117 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
118 /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
119 /// whether to treat V, Lo, and Hi as signed or not.
120 Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
121                                          const APInt &Hi, bool isSigned,
122                                          bool Inside) {
123   assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
124          "Lo is not < Hi in range emission code!");
125 
126   Type *Ty = V->getType();
127 
128   // V >= Min && V <  Hi --> V <  Hi
129   // V <  Min || V >= Hi --> V >= Hi
130   ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
131   if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
132     Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
133     return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
134   }
135 
136   // V >= Lo && V <  Hi --> V - Lo u<  Hi - Lo
137   // V <  Lo || V >= Hi --> V - Lo u>= Hi - Lo
138   Value *VMinusLo =
139       Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
140   Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
141   return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
142 }
143 
144 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
145 /// that can be simplified.
146 /// One of A and B is considered the mask. The other is the value. This is
147 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
148 /// only "Mask", then both A and B can be considered masks. If A is the mask,
149 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
150 /// If both A and C are constants, this proof is also easy.
151 /// For the following explanations, we assume that A is the mask.
152 ///
153 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
154 /// bits of A are set in B.
155 ///   Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
156 ///
157 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
158 /// bits of A are cleared in B.
159 ///   Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
160 ///
161 /// "Mixed" declares that (A & B) == C and C might or might not contain any
162 /// number of one bits and zero bits.
163 ///   Example: (icmp eq (A & 3), 1) -> AMask_Mixed
164 ///
165 /// "Not" means that in above descriptions "==" should be replaced by "!=".
166 ///   Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
167 ///
168 /// If the mask A contains a single bit, then the following is equivalent:
169 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
170 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
171 enum MaskedICmpType {
172   AMask_AllOnes           =     1,
173   AMask_NotAllOnes        =     2,
174   BMask_AllOnes           =     4,
175   BMask_NotAllOnes        =     8,
176   Mask_AllZeros           =    16,
177   Mask_NotAllZeros        =    32,
178   AMask_Mixed             =    64,
179   AMask_NotMixed          =   128,
180   BMask_Mixed             =   256,
181   BMask_NotMixed          =   512
182 };
183 
184 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
185 /// satisfies.
186 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
187                                   ICmpInst::Predicate Pred) {
188   const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
189   match(A, m_APInt(ConstA));
190   match(B, m_APInt(ConstB));
191   match(C, m_APInt(ConstC));
192   bool IsEq = (Pred == ICmpInst::ICMP_EQ);
193   bool IsAPow2 = ConstA && ConstA->isPowerOf2();
194   bool IsBPow2 = ConstB && ConstB->isPowerOf2();
195   unsigned MaskVal = 0;
196   if (ConstC && ConstC->isZero()) {
197     // if C is zero, then both A and B qualify as mask
198     MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
199                      : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
200     if (IsAPow2)
201       MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
202                        : (AMask_AllOnes | AMask_Mixed));
203     if (IsBPow2)
204       MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
205                        : (BMask_AllOnes | BMask_Mixed));
206     return MaskVal;
207   }
208 
209   if (A == C) {
210     MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
211                      : (AMask_NotAllOnes | AMask_NotMixed));
212     if (IsAPow2)
213       MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
214                        : (Mask_AllZeros | AMask_Mixed));
215   } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
216     MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
217   }
218 
219   if (B == C) {
220     MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
221                      : (BMask_NotAllOnes | BMask_NotMixed));
222     if (IsBPow2)
223       MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
224                        : (Mask_AllZeros | BMask_Mixed));
225   } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
226     MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
227   }
228 
229   return MaskVal;
230 }
231 
232 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
233 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
234 /// is adjacent to the corresponding normal flag (recording ==), this just
235 /// involves swapping those bits over.
236 static unsigned conjugateICmpMask(unsigned Mask) {
237   unsigned NewMask;
238   NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
239                      AMask_Mixed | BMask_Mixed))
240             << 1;
241 
242   NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
243                       AMask_NotMixed | BMask_NotMixed))
244              >> 1;
245 
246   return NewMask;
247 }
248 
249 // Adapts the external decomposeBitTestICmp for local use.
250 static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
251                                  Value *&X, Value *&Y, Value *&Z) {
252   APInt Mask;
253   if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
254     return false;
255 
256   Y = ConstantInt::get(X->getType(), Mask);
257   Z = ConstantInt::get(X->getType(), 0);
258   return true;
259 }
260 
261 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
262 /// Return the pattern classes (from MaskedICmpType) for the left hand side and
263 /// the right hand side as a pair.
264 /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
265 /// and PredR are their predicates, respectively.
266 static
267 Optional<std::pair<unsigned, unsigned>>
268 getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
269                          Value *&D, Value *&E, ICmpInst *LHS,
270                          ICmpInst *RHS,
271                          ICmpInst::Predicate &PredL,
272                          ICmpInst::Predicate &PredR) {
273   // Don't allow pointers. Splat vectors are fine.
274   if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
275       !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
276     return None;
277 
278   // Here comes the tricky part:
279   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
280   // and L11 & L12 == L21 & L22. The same goes for RHS.
281   // Now we must find those components L** and R**, that are equal, so
282   // that we can extract the parameters A, B, C, D, and E for the canonical
283   // above.
284   Value *L1 = LHS->getOperand(0);
285   Value *L2 = LHS->getOperand(1);
286   Value *L11, *L12, *L21, *L22;
287   // Check whether the icmp can be decomposed into a bit test.
288   if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
289     L21 = L22 = L1 = nullptr;
290   } else {
291     // Look for ANDs in the LHS icmp.
292     if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
293       // Any icmp can be viewed as being trivially masked; if it allows us to
294       // remove one, it's worth it.
295       L11 = L1;
296       L12 = Constant::getAllOnesValue(L1->getType());
297     }
298 
299     if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
300       L21 = L2;
301       L22 = Constant::getAllOnesValue(L2->getType());
302     }
303   }
304 
305   // Bail if LHS was a icmp that can't be decomposed into an equality.
306   if (!ICmpInst::isEquality(PredL))
307     return None;
308 
309   Value *R1 = RHS->getOperand(0);
310   Value *R2 = RHS->getOperand(1);
311   Value *R11, *R12;
312   bool Ok = false;
313   if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
314     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
315       A = R11;
316       D = R12;
317     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
318       A = R12;
319       D = R11;
320     } else {
321       return None;
322     }
323     E = R2;
324     R1 = nullptr;
325     Ok = true;
326   } else {
327     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
328       // As before, model no mask as a trivial mask if it'll let us do an
329       // optimization.
330       R11 = R1;
331       R12 = Constant::getAllOnesValue(R1->getType());
332     }
333 
334     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
335       A = R11;
336       D = R12;
337       E = R2;
338       Ok = true;
339     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
340       A = R12;
341       D = R11;
342       E = R2;
343       Ok = true;
344     }
345   }
346 
347   // Bail if RHS was a icmp that can't be decomposed into an equality.
348   if (!ICmpInst::isEquality(PredR))
349     return None;
350 
351   // Look for ANDs on the right side of the RHS icmp.
352   if (!Ok) {
353     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
354       R11 = R2;
355       R12 = Constant::getAllOnesValue(R2->getType());
356     }
357 
358     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
359       A = R11;
360       D = R12;
361       E = R1;
362       Ok = true;
363     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
364       A = R12;
365       D = R11;
366       E = R1;
367       Ok = true;
368     } else {
369       return None;
370     }
371 
372     assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
373   }
374 
375   if (L11 == A) {
376     B = L12;
377     C = L2;
378   } else if (L12 == A) {
379     B = L11;
380     C = L2;
381   } else if (L21 == A) {
382     B = L22;
383     C = L1;
384   } else if (L22 == A) {
385     B = L21;
386     C = L1;
387   }
388 
389   unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
390   unsigned RightType = getMaskedICmpType(A, D, E, PredR);
391   return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType));
392 }
393 
394 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
395 /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
396 /// and the right hand side is of type BMask_Mixed. For example,
397 /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
398 static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
399     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
400     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
401     InstCombiner::BuilderTy &Builder) {
402   // We are given the canonical form:
403   //   (icmp ne (A & B), 0) & (icmp eq (A & D), E).
404   // where D & E == E.
405   //
406   // If IsAnd is false, we get it in negated form:
407   //   (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
408   //      !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
409   //
410   // We currently handle the case of B, C, D, E are constant.
411   //
412   ConstantInt *BCst, *CCst, *DCst, *ECst;
413   if (!match(B, m_ConstantInt(BCst)) || !match(C, m_ConstantInt(CCst)) ||
414       !match(D, m_ConstantInt(DCst)) || !match(E, m_ConstantInt(ECst)))
415     return nullptr;
416 
417   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
418 
419   // Update E to the canonical form when D is a power of two and RHS is
420   // canonicalized as,
421   // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
422   // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
423   if (PredR != NewCC)
424     ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
425 
426   // If B or D is zero, skip because if LHS or RHS can be trivially folded by
427   // other folding rules and this pattern won't apply any more.
428   if (BCst->getValue() == 0 || DCst->getValue() == 0)
429     return nullptr;
430 
431   // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
432   // deduce anything from it.
433   // For example,
434   // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
435   if ((BCst->getValue() & DCst->getValue()) == 0)
436     return nullptr;
437 
438   // If the following two conditions are met:
439   //
440   // 1. mask B covers only a single bit that's not covered by mask D, that is,
441   // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
442   // B and D has only one bit set) and,
443   //
444   // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
445   // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
446   //
447   // then that single bit in B must be one and thus the whole expression can be
448   // folded to
449   //   (A & (B | D)) == (B & (B ^ D)) | E.
450   //
451   // For example,
452   // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
453   // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
454   if ((((BCst->getValue() & DCst->getValue()) & ECst->getValue()) == 0) &&
455       (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())).isPowerOf2()) {
456     APInt BorD = BCst->getValue() | DCst->getValue();
457     APInt BandBxorDorE = (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())) |
458         ECst->getValue();
459     Value *NewMask = ConstantInt::get(BCst->getType(), BorD);
460     Value *NewMaskedValue = ConstantInt::get(BCst->getType(), BandBxorDorE);
461     Value *NewAnd = Builder.CreateAnd(A, NewMask);
462     return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
463   }
464 
465   auto IsSubSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
466     return (C1->getValue() & C2->getValue()) == C1->getValue();
467   };
468   auto IsSuperSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) {
469     return (C1->getValue() & C2->getValue()) == C2->getValue();
470   };
471 
472   // In the following, we consider only the cases where B is a superset of D, B
473   // is a subset of D, or B == D because otherwise there's at least one bit
474   // covered by B but not D, in which case we can't deduce much from it, so
475   // no folding (aside from the single must-be-one bit case right above.)
476   // For example,
477   // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
478   if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
479     return nullptr;
480 
481   // At this point, either B is a superset of D, B is a subset of D or B == D.
482 
483   // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
484   // and the whole expression becomes false (or true if negated), otherwise, no
485   // folding.
486   // For example,
487   // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
488   // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
489   if (ECst->isZero()) {
490     if (IsSubSetOrEqual(BCst, DCst))
491       return ConstantInt::get(LHS->getType(), !IsAnd);
492     return nullptr;
493   }
494 
495   // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
496   // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
497   // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
498   // RHS. For example,
499   // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
500   // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
501   if (IsSuperSetOrEqual(BCst, DCst))
502     return RHS;
503   // Otherwise, B is a subset of D. If B and E have a common bit set,
504   // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
505   // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
506   assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
507   if ((BCst->getValue() & ECst->getValue()) != 0)
508     return RHS;
509   // Otherwise, LHS and RHS contradict and the whole expression becomes false
510   // (or true if negated.) For example,
511   // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
512   // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
513   return ConstantInt::get(LHS->getType(), !IsAnd);
514 }
515 
516 /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
517 /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
518 /// aren't of the common mask pattern type.
519 static Value *foldLogOpOfMaskedICmpsAsymmetric(
520     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
521     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
522     unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
523   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
524          "Expected equality predicates for masked type of icmps.");
525   // Handle Mask_NotAllZeros-BMask_Mixed cases.
526   // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
527   // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
528   //    which gets swapped to
529   //    (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
530   if (!IsAnd) {
531     LHSMask = conjugateICmpMask(LHSMask);
532     RHSMask = conjugateICmpMask(RHSMask);
533   }
534   if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
535     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
536             LHS, RHS, IsAnd, A, B, C, D, E,
537             PredL, PredR, Builder)) {
538       return V;
539     }
540   } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
541     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
542             RHS, LHS, IsAnd, A, D, E, B, C,
543             PredR, PredL, Builder)) {
544       return V;
545     }
546   }
547   return nullptr;
548 }
549 
550 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
551 /// into a single (icmp(A & X) ==/!= Y).
552 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
553                                      InstCombiner::BuilderTy &Builder) {
554   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
555   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
556   Optional<std::pair<unsigned, unsigned>> MaskPair =
557       getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
558   if (!MaskPair)
559     return nullptr;
560   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
561          "Expected equality predicates for masked type of icmps.");
562   unsigned LHSMask = MaskPair->first;
563   unsigned RHSMask = MaskPair->second;
564   unsigned Mask = LHSMask & RHSMask;
565   if (Mask == 0) {
566     // Even if the two sides don't share a common pattern, check if folding can
567     // still happen.
568     if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
569             LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
570             Builder))
571       return V;
572     return nullptr;
573   }
574 
575   // In full generality:
576   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
577   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
578   //
579   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
580   // equivalent to (icmp (A & X) !Op Y).
581   //
582   // Therefore, we can pretend for the rest of this function that we're dealing
583   // with the conjunction, provided we flip the sense of any comparisons (both
584   // input and output).
585 
586   // In most cases we're going to produce an EQ for the "&&" case.
587   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
588   if (!IsAnd) {
589     // Convert the masking analysis into its equivalent with negated
590     // comparisons.
591     Mask = conjugateICmpMask(Mask);
592   }
593 
594   if (Mask & Mask_AllZeros) {
595     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
596     // -> (icmp eq (A & (B|D)), 0)
597     Value *NewOr = Builder.CreateOr(B, D);
598     Value *NewAnd = Builder.CreateAnd(A, NewOr);
599     // We can't use C as zero because we might actually handle
600     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
601     // with B and D, having a single bit set.
602     Value *Zero = Constant::getNullValue(A->getType());
603     return Builder.CreateICmp(NewCC, NewAnd, Zero);
604   }
605   if (Mask & BMask_AllOnes) {
606     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
607     // -> (icmp eq (A & (B|D)), (B|D))
608     Value *NewOr = Builder.CreateOr(B, D);
609     Value *NewAnd = Builder.CreateAnd(A, NewOr);
610     return Builder.CreateICmp(NewCC, NewAnd, NewOr);
611   }
612   if (Mask & AMask_AllOnes) {
613     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
614     // -> (icmp eq (A & (B&D)), A)
615     Value *NewAnd1 = Builder.CreateAnd(B, D);
616     Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
617     return Builder.CreateICmp(NewCC, NewAnd2, A);
618   }
619 
620   // Remaining cases assume at least that B and D are constant, and depend on
621   // their actual values. This isn't strictly necessary, just a "handle the
622   // easy cases for now" decision.
623   const APInt *ConstB, *ConstD;
624   if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
625     return nullptr;
626 
627   if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
628     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
629     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
630     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
631     // Only valid if one of the masks is a superset of the other (check "B&D" is
632     // the same as either B or D).
633     APInt NewMask = *ConstB & *ConstD;
634     if (NewMask == *ConstB)
635       return LHS;
636     else if (NewMask == *ConstD)
637       return RHS;
638   }
639 
640   if (Mask & AMask_NotAllOnes) {
641     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
642     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
643     // Only valid if one of the masks is a superset of the other (check "B|D" is
644     // the same as either B or D).
645     APInt NewMask = *ConstB | *ConstD;
646     if (NewMask == *ConstB)
647       return LHS;
648     else if (NewMask == *ConstD)
649       return RHS;
650   }
651 
652   if (Mask & BMask_Mixed) {
653     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
654     // We already know that B & C == C && D & E == E.
655     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
656     // C and E, which are shared by both the mask B and the mask D, don't
657     // contradict, then we can transform to
658     // -> (icmp eq (A & (B|D)), (C|E))
659     // Currently, we only handle the case of B, C, D, and E being constant.
660     // We can't simply use C and E because we might actually handle
661     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
662     // with B and D, having a single bit set.
663     const APInt *OldConstC, *OldConstE;
664     if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
665       return nullptr;
666 
667     const APInt ConstC = PredL != NewCC ? *ConstB ^ *OldConstC : *OldConstC;
668     const APInt ConstE = PredR != NewCC ? *ConstD ^ *OldConstE : *OldConstE;
669 
670     // If there is a conflict, we should actually return a false for the
671     // whole construct.
672     if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
673       return ConstantInt::get(LHS->getType(), !IsAnd);
674 
675     Value *NewOr1 = Builder.CreateOr(B, D);
676     Value *NewAnd = Builder.CreateAnd(A, NewOr1);
677     Constant *NewOr2 = ConstantInt::get(A->getType(), ConstC | ConstE);
678     return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
679   }
680 
681   return nullptr;
682 }
683 
684 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
685 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
686 /// If \p Inverted is true then the check is for the inverted range, e.g.
687 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
688 Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
689                                             bool Inverted) {
690   // Check the lower range comparison, e.g. x >= 0
691   // InstCombine already ensured that if there is a constant it's on the RHS.
692   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
693   if (!RangeStart)
694     return nullptr;
695 
696   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
697                                Cmp0->getPredicate());
698 
699   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
700   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
701         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
702     return nullptr;
703 
704   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
705                                Cmp1->getPredicate());
706 
707   Value *Input = Cmp0->getOperand(0);
708   Value *RangeEnd;
709   if (Cmp1->getOperand(0) == Input) {
710     // For the upper range compare we have: icmp x, n
711     RangeEnd = Cmp1->getOperand(1);
712   } else if (Cmp1->getOperand(1) == Input) {
713     // For the upper range compare we have: icmp n, x
714     RangeEnd = Cmp1->getOperand(0);
715     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
716   } else {
717     return nullptr;
718   }
719 
720   // Check the upper range comparison, e.g. x < n
721   ICmpInst::Predicate NewPred;
722   switch (Pred1) {
723     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
724     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
725     default: return nullptr;
726   }
727 
728   // This simplification is only valid if the upper range is not negative.
729   KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
730   if (!Known.isNonNegative())
731     return nullptr;
732 
733   if (Inverted)
734     NewPred = ICmpInst::getInversePredicate(NewPred);
735 
736   return Builder.CreateICmp(NewPred, Input, RangeEnd);
737 }
738 
739 static Value *
740 foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
741                                      bool JoinedByAnd,
742                                      InstCombiner::BuilderTy &Builder) {
743   Value *X = LHS->getOperand(0);
744   if (X != RHS->getOperand(0))
745     return nullptr;
746 
747   const APInt *C1, *C2;
748   if (!match(LHS->getOperand(1), m_APInt(C1)) ||
749       !match(RHS->getOperand(1), m_APInt(C2)))
750     return nullptr;
751 
752   // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
753   ICmpInst::Predicate Pred = LHS->getPredicate();
754   if (Pred !=  RHS->getPredicate())
755     return nullptr;
756   if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
757     return nullptr;
758   if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
759     return nullptr;
760 
761   // The larger unsigned constant goes on the right.
762   if (C1->ugt(*C2))
763     std::swap(C1, C2);
764 
765   APInt Xor = *C1 ^ *C2;
766   if (Xor.isPowerOf2()) {
767     // If LHSC and RHSC differ by only one bit, then set that bit in X and
768     // compare against the larger constant:
769     // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
770     // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
771     // We choose an 'or' with a Pow2 constant rather than the inverse mask with
772     // 'and' because that may lead to smaller codegen from a smaller constant.
773     Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor));
774     return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
775   }
776 
777   // Special case: get the ordering right when the values wrap around zero.
778   // Ie, we assumed the constants were unsigned when swapping earlier.
779   if (C1->isZero() && C2->isAllOnes())
780     std::swap(C1, C2);
781 
782   if (*C1 == *C2 - 1) {
783     // (X == 13 || X == 14) --> X - 13 <=u 1
784     // (X != 13 && X != 14) --> X - 13  >u 1
785     // An 'add' is the canonical IR form, so favor that over a 'sub'.
786     Value *Add = Builder.CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
787     auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
788     return Builder.CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
789   }
790 
791   return nullptr;
792 }
793 
794 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
795 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
796 Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
797                                                        ICmpInst *RHS,
798                                                        Instruction *CxtI,
799                                                        bool IsAnd,
800                                                        bool IsLogical) {
801   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
802   if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
803     return nullptr;
804 
805   if (!match(LHS->getOperand(1), m_Zero()) ||
806       !match(RHS->getOperand(1), m_Zero()))
807     return nullptr;
808 
809   Value *L1, *L2, *R1, *R2;
810   if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
811       match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
812     if (L1 == R2 || L2 == R2)
813       std::swap(R1, R2);
814     if (L2 == R1)
815       std::swap(L1, L2);
816 
817     if (L1 == R1 &&
818         isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
819         isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
820       // If this is a logical and/or, then we must prevent propagation of a
821       // poison value from the RHS by inserting freeze.
822       if (IsLogical)
823         R2 = Builder.CreateFreeze(R2);
824       Value *Mask = Builder.CreateOr(L2, R2);
825       Value *Masked = Builder.CreateAnd(L1, Mask);
826       auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
827       return Builder.CreateICmp(NewPred, Masked, Mask);
828     }
829   }
830 
831   return nullptr;
832 }
833 
834 /// General pattern:
835 ///   X & Y
836 ///
837 /// Where Y is checking that all the high bits (covered by a mask 4294967168)
838 /// are uniform, i.e.  %arg & 4294967168  can be either  4294967168  or  0
839 /// Pattern can be one of:
840 ///   %t = add        i32 %arg,    128
841 ///   %r = icmp   ult i32 %t,      256
842 /// Or
843 ///   %t0 = shl       i32 %arg,    24
844 ///   %t1 = ashr      i32 %t0,     24
845 ///   %r  = icmp  eq  i32 %t1,     %arg
846 /// Or
847 ///   %t0 = trunc     i32 %arg  to i8
848 ///   %t1 = sext      i8  %t0   to i32
849 ///   %r  = icmp  eq  i32 %t1,     %arg
850 /// This pattern is a signed truncation check.
851 ///
852 /// And X is checking that some bit in that same mask is zero.
853 /// I.e. can be one of:
854 ///   %r = icmp sgt i32   %arg,    -1
855 /// Or
856 ///   %t = and      i32   %arg,    2147483648
857 ///   %r = icmp eq  i32   %t,      0
858 ///
859 /// Since we are checking that all the bits in that mask are the same,
860 /// and a particular bit is zero, what we are really checking is that all the
861 /// masked bits are zero.
862 /// So this should be transformed to:
863 ///   %r = icmp ult i32 %arg, 128
864 static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
865                                         Instruction &CxtI,
866                                         InstCombiner::BuilderTy &Builder) {
867   assert(CxtI.getOpcode() == Instruction::And);
868 
869   // Match  icmp ult (add %arg, C01), C1   (C1 == C01 << 1; powers of two)
870   auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
871                                             APInt &SignBitMask) -> bool {
872     CmpInst::Predicate Pred;
873     const APInt *I01, *I1; // powers of two; I1 == I01 << 1
874     if (!(match(ICmp,
875                 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
876           Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
877       return false;
878     // Which bit is the new sign bit as per the 'signed truncation' pattern?
879     SignBitMask = *I01;
880     return true;
881   };
882 
883   // One icmp needs to be 'signed truncation check'.
884   // We need to match this first, else we will mismatch commutative cases.
885   Value *X1;
886   APInt HighestBit;
887   ICmpInst *OtherICmp;
888   if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
889     OtherICmp = ICmp0;
890   else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
891     OtherICmp = ICmp1;
892   else
893     return nullptr;
894 
895   assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
896 
897   // Try to match/decompose into:  icmp eq (X & Mask), 0
898   auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
899                            APInt &UnsetBitsMask) -> bool {
900     CmpInst::Predicate Pred = ICmp->getPredicate();
901     // Can it be decomposed into  icmp eq (X & Mask), 0  ?
902     if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
903                                    Pred, X, UnsetBitsMask,
904                                    /*LookThroughTrunc=*/false) &&
905         Pred == ICmpInst::ICMP_EQ)
906       return true;
907     // Is it  icmp eq (X & Mask), 0  already?
908     const APInt *Mask;
909     if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
910         Pred == ICmpInst::ICMP_EQ) {
911       UnsetBitsMask = *Mask;
912       return true;
913     }
914     return false;
915   };
916 
917   // And the other icmp needs to be decomposable into a bit test.
918   Value *X0;
919   APInt UnsetBitsMask;
920   if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
921     return nullptr;
922 
923   assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
924 
925   // Are they working on the same value?
926   Value *X;
927   if (X1 == X0) {
928     // Ok as is.
929     X = X1;
930   } else if (match(X0, m_Trunc(m_Specific(X1)))) {
931     UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
932     X = X1;
933   } else
934     return nullptr;
935 
936   // So which bits should be uniform as per the 'signed truncation check'?
937   // (all the bits starting with (i.e. including) HighestBit)
938   APInt SignBitsMask = ~(HighestBit - 1U);
939 
940   // UnsetBitsMask must have some common bits with SignBitsMask,
941   if (!UnsetBitsMask.intersects(SignBitsMask))
942     return nullptr;
943 
944   // Does UnsetBitsMask contain any bits outside of SignBitsMask?
945   if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
946     APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
947     if (!OtherHighestBit.isPowerOf2())
948       return nullptr;
949     HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
950   }
951   // Else, if it does not, then all is ok as-is.
952 
953   // %r = icmp ult %X, SignBit
954   return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
955                                CxtI.getName() + ".simplified");
956 }
957 
958 /// Reduce a pair of compares that check if a value has exactly 1 bit set.
959 static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
960                              InstCombiner::BuilderTy &Builder) {
961   // Handle 'and' / 'or' commutation: make the equality check the first operand.
962   if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
963     std::swap(Cmp0, Cmp1);
964   else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
965     std::swap(Cmp0, Cmp1);
966 
967   // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
968   CmpInst::Predicate Pred0, Pred1;
969   Value *X;
970   if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
971       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
972                          m_SpecificInt(2))) &&
973       Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
974     Value *CtPop = Cmp1->getOperand(0);
975     return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
976   }
977   // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
978   if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
979       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
980                          m_SpecificInt(1))) &&
981       Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
982     Value *CtPop = Cmp1->getOperand(0);
983     return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
984   }
985   return nullptr;
986 }
987 
988 /// Commuted variants are assumed to be handled by calling this function again
989 /// with the parameters swapped.
990 static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
991                                          ICmpInst *UnsignedICmp, bool IsAnd,
992                                          const SimplifyQuery &Q,
993                                          InstCombiner::BuilderTy &Builder) {
994   Value *ZeroCmpOp;
995   ICmpInst::Predicate EqPred;
996   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
997       !ICmpInst::isEquality(EqPred))
998     return nullptr;
999 
1000   auto IsKnownNonZero = [&](Value *V) {
1001     return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1002   };
1003 
1004   ICmpInst::Predicate UnsignedPred;
1005 
1006   Value *A, *B;
1007   if (match(UnsignedICmp,
1008             m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
1009       match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
1010       (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
1011     auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
1012       if (!IsKnownNonZero(NonZero))
1013         std::swap(NonZero, Other);
1014       return IsKnownNonZero(NonZero);
1015     };
1016 
1017     // Given  ZeroCmpOp = (A + B)
1018     //   ZeroCmpOp <= A && ZeroCmpOp != 0  -->  (0-B) <  A
1019     //   ZeroCmpOp >  A || ZeroCmpOp == 0  -->  (0-B) >= A
1020     //
1021     //   ZeroCmpOp <  A && ZeroCmpOp != 0  -->  (0-X) <  Y  iff
1022     //   ZeroCmpOp >= A || ZeroCmpOp == 0  -->  (0-X) >= Y  iff
1023     //     with X being the value (A/B) that is known to be non-zero,
1024     //     and Y being remaining value.
1025     if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1026         IsAnd)
1027       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
1028     if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
1029         IsAnd && GetKnownNonZeroAndOther(B, A))
1030       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
1031     if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1032         !IsAnd)
1033       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
1034     if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
1035         !IsAnd && GetKnownNonZeroAndOther(B, A))
1036       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
1037   }
1038 
1039   Value *Base, *Offset;
1040   if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset))))
1041     return nullptr;
1042 
1043   if (!match(UnsignedICmp,
1044              m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) ||
1045       !ICmpInst::isUnsigned(UnsignedPred))
1046     return nullptr;
1047 
1048   // Base >=/> Offset && (Base - Offset) != 0  <-->  Base > Offset
1049   // (no overflow and not null)
1050   if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1051        UnsignedPred == ICmpInst::ICMP_UGT) &&
1052       EqPred == ICmpInst::ICMP_NE && IsAnd)
1053     return Builder.CreateICmpUGT(Base, Offset);
1054 
1055   // Base <=/< Offset || (Base - Offset) == 0  <-->  Base <= Offset
1056   // (overflow or null)
1057   if ((UnsignedPred == ICmpInst::ICMP_ULE ||
1058        UnsignedPred == ICmpInst::ICMP_ULT) &&
1059       EqPred == ICmpInst::ICMP_EQ && !IsAnd)
1060     return Builder.CreateICmpULE(Base, Offset);
1061 
1062   // Base <= Offset && (Base - Offset) != 0  -->  Base < Offset
1063   if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1064       IsAnd)
1065     return Builder.CreateICmpULT(Base, Offset);
1066 
1067   // Base > Offset || (Base - Offset) == 0  -->  Base >= Offset
1068   if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1069       !IsAnd)
1070     return Builder.CreateICmpUGE(Base, Offset);
1071 
1072   return nullptr;
1073 }
1074 
1075 struct IntPart {
1076   Value *From;
1077   unsigned StartBit;
1078   unsigned NumBits;
1079 };
1080 
1081 /// Match an extraction of bits from an integer.
1082 static Optional<IntPart> matchIntPart(Value *V) {
1083   Value *X;
1084   if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
1085     return None;
1086 
1087   unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1088   unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1089   Value *Y;
1090   const APInt *Shift;
1091   // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1092   // from Y, not any shifted-in zeroes.
1093   if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
1094       Shift->ule(NumOriginalBits - NumExtractedBits))
1095     return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
1096   return {{X, 0, NumExtractedBits}};
1097 }
1098 
1099 /// Materialize an extraction of bits from an integer in IR.
1100 static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1101   Value *V = P.From;
1102   if (P.StartBit)
1103     V = Builder.CreateLShr(V, P.StartBit);
1104   Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
1105   if (TruncTy != V->getType())
1106     V = Builder.CreateTrunc(V, TruncTy);
1107   return V;
1108 }
1109 
1110 /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1111 /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1112 /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
1113 Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
1114                                        bool IsAnd) {
1115   if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1116     return nullptr;
1117 
1118   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
1119   if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred)
1120     return nullptr;
1121 
1122   Optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0));
1123   Optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1));
1124   Optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0));
1125   Optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1));
1126   if (!L0 || !R0 || !L1 || !R1)
1127     return nullptr;
1128 
1129   // Make sure the LHS/RHS compare a part of the same value, possibly after
1130   // an operand swap.
1131   if (L0->From != L1->From || R0->From != R1->From) {
1132     if (L0->From != R1->From || R0->From != L1->From)
1133       return nullptr;
1134     std::swap(L1, R1);
1135   }
1136 
1137   // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1138   // the low part and L1/R1 being the high part.
1139   if (L0->StartBit + L0->NumBits != L1->StartBit ||
1140       R0->StartBit + R0->NumBits != R1->StartBit) {
1141     if (L1->StartBit + L1->NumBits != L0->StartBit ||
1142         R1->StartBit + R1->NumBits != R0->StartBit)
1143       return nullptr;
1144     std::swap(L0, L1);
1145     std::swap(R0, R1);
1146   }
1147 
1148   // We can simplify to a comparison of these larger parts of the integers.
1149   IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
1150   IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
1151   Value *LValue = extractIntPart(L, Builder);
1152   Value *RValue = extractIntPart(R, Builder);
1153   return Builder.CreateICmp(Pred, LValue, RValue);
1154 }
1155 
1156 /// Reduce logic-of-compares with equality to a constant by substituting a
1157 /// common operand with the constant. Callers are expected to call this with
1158 /// Cmp0/Cmp1 switched to handle logic op commutativity.
1159 static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1160                                           BinaryOperator &Logic,
1161                                           InstCombiner::BuilderTy &Builder,
1162                                           const SimplifyQuery &Q) {
1163   bool IsAnd = Logic.getOpcode() == Instruction::And;
1164   assert((IsAnd || Logic.getOpcode() == Instruction::Or) && "Wrong logic op");
1165 
1166   // Match an equality compare with a non-poison constant as Cmp0.
1167   // Also, give up if the compare can be constant-folded to avoid looping.
1168   ICmpInst::Predicate Pred0;
1169   Value *X;
1170   Constant *C;
1171   if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1172       !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
1173     return nullptr;
1174   if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
1175       (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
1176     return nullptr;
1177 
1178   // The other compare must include a common operand (X). Canonicalize the
1179   // common operand as operand 1 (Pred1 is swapped if the common operand was
1180   // operand 0).
1181   Value *Y;
1182   ICmpInst::Predicate Pred1;
1183   if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
1184     return nullptr;
1185 
1186   // Replace variable with constant value equivalence to remove a variable use:
1187   // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
1188   // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
1189   // Can think of the 'or' substitution with the 'and' bool equivalent:
1190   // A || B --> A || (!A && B)
1191   Value *SubstituteCmp = SimplifyICmpInst(Pred1, Y, C, Q);
1192   if (!SubstituteCmp) {
1193     // If we need to create a new instruction, require that the old compare can
1194     // be removed.
1195     if (!Cmp1->hasOneUse())
1196       return nullptr;
1197     SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
1198   }
1199   return Builder.CreateBinOp(Logic.getOpcode(), Cmp0, SubstituteCmp);
1200 }
1201 
1202 /// Fold (icmp)&(icmp) if possible.
1203 Value *InstCombinerImpl::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1204                                         BinaryOperator &And) {
1205   const SimplifyQuery Q = SQ.getWithInstruction(&And);
1206 
1207   // Fold (!iszero(A & K1) & !iszero(A & K2)) ->  (A & (K1 | K2)) == (K1 | K2)
1208   // if K1 and K2 are a one-bit mask.
1209   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &And,
1210                                                /* IsAnd */ true))
1211     return V;
1212 
1213   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1214 
1215   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
1216   if (predicatesFoldable(PredL, PredR)) {
1217     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1218         LHS->getOperand(1) == RHS->getOperand(0))
1219       LHS->swapOperands();
1220     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1221         LHS->getOperand(1) == RHS->getOperand(1)) {
1222       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1223       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
1224       bool IsSigned = LHS->isSigned() || RHS->isSigned();
1225       return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
1226     }
1227   }
1228 
1229   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
1230   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
1231     return V;
1232 
1233   if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, And, Builder, Q))
1234     return V;
1235   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, And, Builder, Q))
1236     return V;
1237 
1238   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
1239   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
1240     return V;
1241 
1242   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
1243   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
1244     return V;
1245 
1246   if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
1247     return V;
1248 
1249   if (Value *V = foldSignedTruncationCheck(LHS, RHS, And, Builder))
1250     return V;
1251 
1252   if (Value *V = foldIsPowerOf2(LHS, RHS, true /* JoinedByAnd */, Builder))
1253     return V;
1254 
1255   if (Value *X =
1256           foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/true, Q, Builder))
1257     return X;
1258   if (Value *X =
1259           foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/true, Q, Builder))
1260     return X;
1261 
1262   if (Value *X = foldEqOfParts(LHS, RHS, /*IsAnd=*/true))
1263     return X;
1264 
1265   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
1266   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
1267 
1268   ConstantInt *LHSC, *RHSC;
1269   if (!match(LHS->getOperand(1), m_ConstantInt(LHSC)) ||
1270       !match(RHS->getOperand(1), m_ConstantInt(RHSC)))
1271     return nullptr;
1272 
1273   if (LHSC == RHSC && PredL == PredR) {
1274     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
1275     // where C is a power of 2 or
1276     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
1277     if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
1278         (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
1279       Value *NewOr = Builder.CreateOr(LHS0, RHS0);
1280       return Builder.CreateICmp(PredL, NewOr, LHSC);
1281     }
1282   }
1283 
1284   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
1285   // where CMAX is the all ones value for the truncated type,
1286   // iff the lower bits of C2 and CA are zero.
1287   if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
1288       RHS->hasOneUse()) {
1289     Value *V;
1290     ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
1291 
1292     // (trunc x) == C1 & (and x, CA) == C2
1293     // (and x, CA) == C2 & (trunc x) == C1
1294     if (match(RHS0, m_Trunc(m_Value(V))) &&
1295         match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
1296       SmallC = RHSC;
1297       BigC = LHSC;
1298     } else if (match(LHS0, m_Trunc(m_Value(V))) &&
1299                match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
1300       SmallC = LHSC;
1301       BigC = RHSC;
1302     }
1303 
1304     if (SmallC && BigC) {
1305       unsigned BigBitSize = BigC->getType()->getBitWidth();
1306       unsigned SmallBitSize = SmallC->getType()->getBitWidth();
1307 
1308       // Check that the low bits are zero.
1309       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
1310       if ((Low & AndC->getValue()).isZero() &&
1311           (Low & BigC->getValue()).isZero()) {
1312         Value *NewAnd = Builder.CreateAnd(V, Low | AndC->getValue());
1313         APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
1314         Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
1315         return Builder.CreateICmp(PredL, NewAnd, NewVal);
1316       }
1317     }
1318   }
1319 
1320   // From here on, we only handle:
1321   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
1322   if (LHS0 != RHS0)
1323     return nullptr;
1324 
1325   // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1326   if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1327       PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1328       PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1329       PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
1330     return nullptr;
1331 
1332   // We can't fold (ugt x, C) & (sgt x, C2).
1333   if (!predicatesFoldable(PredL, PredR))
1334     return nullptr;
1335 
1336   // Ensure that the larger constant is on the RHS.
1337   bool ShouldSwap;
1338   if (CmpInst::isSigned(PredL) ||
1339       (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
1340     ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
1341   else
1342     ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
1343 
1344   if (ShouldSwap) {
1345     std::swap(LHS, RHS);
1346     std::swap(LHSC, RHSC);
1347     std::swap(PredL, PredR);
1348   }
1349 
1350   // At this point, we know we have two icmp instructions
1351   // comparing a value against two constants and and'ing the result
1352   // together.  Because of the above check, we know that we only have
1353   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
1354   // (from the icmp folding check above), that the two constants
1355   // are not equal and that the larger constant is on the RHS
1356   assert(LHSC != RHSC && "Compares not folded above?");
1357 
1358   switch (PredL) {
1359   default:
1360     llvm_unreachable("Unknown integer condition code!");
1361   case ICmpInst::ICMP_NE:
1362     switch (PredR) {
1363     default:
1364       llvm_unreachable("Unknown integer condition code!");
1365     case ICmpInst::ICMP_ULT:
1366       // (X != 13 & X u< 14) -> X < 13
1367       if (LHSC->getValue() == (RHSC->getValue() - 1))
1368         return Builder.CreateICmpULT(LHS0, LHSC);
1369       if (LHSC->isZero()) // (X != 0 & X u< C) -> X-1 u< C-1
1370         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1371                                false, true);
1372       break; // (X != 13 & X u< 15) -> no change
1373     case ICmpInst::ICMP_SLT:
1374       // (X != 13 & X s< 14) -> X < 13
1375       if (LHSC->getValue() == (RHSC->getValue() - 1))
1376         return Builder.CreateICmpSLT(LHS0, LHSC);
1377       // (X != INT_MIN & X s< C) -> X-(INT_MIN+1) u< (C-(INT_MIN+1))
1378       if (LHSC->isMinValue(true))
1379         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1380                                true, true);
1381       break; // (X != 13 & X s< 15) -> no change
1382     case ICmpInst::ICMP_NE:
1383       // Potential folds for this case should already be handled.
1384       break;
1385     }
1386     break;
1387   case ICmpInst::ICMP_UGT:
1388     switch (PredR) {
1389     default:
1390       llvm_unreachable("Unknown integer condition code!");
1391     case ICmpInst::ICMP_NE:
1392       // (X u> 13 & X != 14) -> X u> 14
1393       if (RHSC->getValue() == (LHSC->getValue() + 1))
1394         return Builder.CreateICmp(PredL, LHS0, RHSC);
1395       // X u> C & X != UINT_MAX -> (X-(C+1)) u< UINT_MAX-(C+1)
1396       if (RHSC->isMaxValue(false))
1397         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1398                                false, true);
1399       break;                 // (X u> 13 & X != 15) -> no change
1400     case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) u< 1
1401       return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1402                              false, true);
1403     }
1404     break;
1405   case ICmpInst::ICMP_SGT:
1406     switch (PredR) {
1407     default:
1408       llvm_unreachable("Unknown integer condition code!");
1409     case ICmpInst::ICMP_NE:
1410       // (X s> 13 & X != 14) -> X s> 14
1411       if (RHSC->getValue() == (LHSC->getValue() + 1))
1412         return Builder.CreateICmp(PredL, LHS0, RHSC);
1413       // X s> C & X != INT_MAX -> (X-(C+1)) u< INT_MAX-(C+1)
1414       if (RHSC->isMaxValue(true))
1415         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
1416                                true, true);
1417       break;                 // (X s> 13 & X != 15) -> no change
1418     case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) u< 1
1419       return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
1420                              true);
1421     }
1422     break;
1423   }
1424 
1425   return nullptr;
1426 }
1427 
1428 Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
1429                                           bool IsAnd) {
1430   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1431   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1432   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1433 
1434   if (LHS0 == RHS1 && RHS0 == LHS1) {
1435     // Swap RHS operands to match LHS.
1436     PredR = FCmpInst::getSwappedPredicate(PredR);
1437     std::swap(RHS0, RHS1);
1438   }
1439 
1440   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1441   // Suppose the relation between x and y is R, where R is one of
1442   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1443   // testing the desired relations.
1444   //
1445   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1446   //    bool(R & CC0) && bool(R & CC1)
1447   //  = bool((R & CC0) & (R & CC1))
1448   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1449   //
1450   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1451   //    bool(R & CC0) || bool(R & CC1)
1452   //  = bool((R & CC0) | (R & CC1))
1453   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1454   if (LHS0 == RHS0 && LHS1 == RHS1) {
1455     unsigned FCmpCodeL = getFCmpCode(PredL);
1456     unsigned FCmpCodeR = getFCmpCode(PredR);
1457     unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
1458     return getFCmpValue(NewPred, LHS0, LHS1, Builder);
1459   }
1460 
1461   if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1462       (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1463     if (LHS0->getType() != RHS0->getType())
1464       return nullptr;
1465 
1466     // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
1467     // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
1468     if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
1469       // Ignore the constants because they are obviously not NANs:
1470       // (fcmp ord x, 0.0) & (fcmp ord y, 0.0)  -> (fcmp ord x, y)
1471       // (fcmp uno x, 0.0) | (fcmp uno y, 0.0)  -> (fcmp uno x, y)
1472       return Builder.CreateFCmp(PredL, LHS0, RHS0);
1473   }
1474 
1475   return nullptr;
1476 }
1477 
1478 /// This a limited reassociation for a special case (see above) where we are
1479 /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
1480 /// This could be handled more generally in '-reassociation', but it seems like
1481 /// an unlikely pattern for a large number of logic ops and fcmps.
1482 static Instruction *reassociateFCmps(BinaryOperator &BO,
1483                                      InstCombiner::BuilderTy &Builder) {
1484   Instruction::BinaryOps Opcode = BO.getOpcode();
1485   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1486          "Expecting and/or op for fcmp transform");
1487 
1488   // There are 4 commuted variants of the pattern. Canonicalize operands of this
1489   // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
1490   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
1491   FCmpInst::Predicate Pred;
1492   if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
1493     std::swap(Op0, Op1);
1494 
1495   // Match inner binop and the predicate for combining 2 NAN checks into 1.
1496   BinaryOperator *BO1;
1497   FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
1498                                                            : FCmpInst::FCMP_UNO;
1499   if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
1500       !match(Op1, m_BinOp(BO1)) || BO1->getOpcode() != Opcode)
1501     return nullptr;
1502 
1503   // The inner logic op must have a matching fcmp operand.
1504   Value *BO10 = BO1->getOperand(0), *BO11 = BO1->getOperand(1), *Y;
1505   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1506       Pred != NanPred || X->getType() != Y->getType())
1507     std::swap(BO10, BO11);
1508 
1509   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
1510       Pred != NanPred || X->getType() != Y->getType())
1511     return nullptr;
1512 
1513   // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
1514   // or  (fcmp uno X, 0), (or  (fcmp uno Y, 0), Z) --> or  (fcmp uno X, Y), Z
1515   Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
1516   if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
1517     // Intersect FMF from the 2 source fcmps.
1518     NewFCmpInst->copyIRFlags(Op0);
1519     NewFCmpInst->andIRFlags(BO10);
1520   }
1521   return BinaryOperator::Create(Opcode, NewFCmp, BO11);
1522 }
1523 
1524 /// Match variations of De Morgan's Laws:
1525 /// (~A & ~B) == (~(A | B))
1526 /// (~A | ~B) == (~(A & B))
1527 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1528                                        InstCombiner::BuilderTy &Builder) {
1529   const Instruction::BinaryOps Opcode = I.getOpcode();
1530   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1531          "Trying to match De Morgan's Laws with something other than and/or");
1532 
1533   // Flip the logic operation.
1534   const Instruction::BinaryOps FlippedOpcode =
1535       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1536 
1537   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1538   Value *A, *B;
1539   if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
1540       match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
1541       !InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
1542       !InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
1543     Value *AndOr =
1544         Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
1545     return BinaryOperator::CreateNot(AndOr);
1546   }
1547 
1548   // The 'not' ops may require reassociation.
1549   // (A & ~B) & ~C --> A & ~(B | C)
1550   // (~B & A) & ~C --> A & ~(B | C)
1551   // (A | ~B) | ~C --> A | ~(B & C)
1552   // (~B | A) | ~C --> A | ~(B & C)
1553   BinaryOperator *BO;
1554   if (match(Op0, m_OneUse(m_BinOp(BO))) && BO->getOpcode() == Opcode) {
1555     Value *C;
1556     if (match(BO, m_c_BinOp(m_Value(A), m_Not(m_Value(B)))) &&
1557         match(Op1, m_Not(m_Value(C)))) {
1558       Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C);
1559       return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO));
1560     }
1561   }
1562 
1563   return nullptr;
1564 }
1565 
1566 bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
1567   Value *CastSrc = CI->getOperand(0);
1568 
1569   // Noop casts and casts of constants should be eliminated trivially.
1570   if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1571     return false;
1572 
1573   // If this cast is paired with another cast that can be eliminated, we prefer
1574   // to have it eliminated.
1575   if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1576     if (isEliminableCastPair(PrecedingCI, CI))
1577       return false;
1578 
1579   return true;
1580 }
1581 
1582 /// Fold {and,or,xor} (cast X), C.
1583 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1584                                           InstCombiner::BuilderTy &Builder) {
1585   Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
1586   if (!C)
1587     return nullptr;
1588 
1589   auto LogicOpc = Logic.getOpcode();
1590   Type *DestTy = Logic.getType();
1591   Type *SrcTy = Cast->getSrcTy();
1592 
1593   // Move the logic operation ahead of a zext or sext if the constant is
1594   // unchanged in the smaller source type. Performing the logic in a smaller
1595   // type may provide more information to later folds, and the smaller logic
1596   // instruction may be cheaper (particularly in the case of vectors).
1597   Value *X;
1598   if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1599     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1600     Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1601     if (ZextTruncC == C) {
1602       // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1603       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1604       return new ZExtInst(NewOp, DestTy);
1605     }
1606   }
1607 
1608   if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
1609     Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1610     Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
1611     if (SextTruncC == C) {
1612       // LogicOpc (sext X), C --> sext (LogicOpc X, C)
1613       Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
1614       return new SExtInst(NewOp, DestTy);
1615     }
1616   }
1617 
1618   return nullptr;
1619 }
1620 
1621 /// Fold {and,or,xor} (cast X), Y.
1622 Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
1623   auto LogicOpc = I.getOpcode();
1624   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1625 
1626   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1627   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1628   if (!Cast0)
1629     return nullptr;
1630 
1631   // This must be a cast from an integer or integer vector source type to allow
1632   // transformation of the logic operation to the source type.
1633   Type *DestTy = I.getType();
1634   Type *SrcTy = Cast0->getSrcTy();
1635   if (!SrcTy->isIntOrIntVectorTy())
1636     return nullptr;
1637 
1638   if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1639     return Ret;
1640 
1641   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1642   if (!Cast1)
1643     return nullptr;
1644 
1645   // Both operands of the logic operation are casts. The casts must be of the
1646   // same type for reduction.
1647   auto CastOpcode = Cast0->getOpcode();
1648   if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1649     return nullptr;
1650 
1651   Value *Cast0Src = Cast0->getOperand(0);
1652   Value *Cast1Src = Cast1->getOperand(0);
1653 
1654   // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1655   if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1656     Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1657                                         I.getName());
1658     return CastInst::Create(CastOpcode, NewOp, DestTy);
1659   }
1660 
1661   // For now, only 'and'/'or' have optimizations after this.
1662   if (LogicOpc == Instruction::Xor)
1663     return nullptr;
1664 
1665   // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1666   // cast is otherwise not optimizable.  This happens for vector sexts.
1667   ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1668   ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1669   if (ICmp0 && ICmp1) {
1670     Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
1671                                               : foldOrOfICmps(ICmp0, ICmp1, I);
1672     if (Res)
1673       return CastInst::Create(CastOpcode, Res, DestTy);
1674     return nullptr;
1675   }
1676 
1677   // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1678   // cast is otherwise not optimizable.  This happens for vector sexts.
1679   FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1680   FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1681   if (FCmp0 && FCmp1)
1682     if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
1683       return CastInst::Create(CastOpcode, R, DestTy);
1684 
1685   return nullptr;
1686 }
1687 
1688 static Instruction *foldAndToXor(BinaryOperator &I,
1689                                  InstCombiner::BuilderTy &Builder) {
1690   assert(I.getOpcode() == Instruction::And);
1691   Value *Op0 = I.getOperand(0);
1692   Value *Op1 = I.getOperand(1);
1693   Value *A, *B;
1694 
1695   // Operand complexity canonicalization guarantees that the 'or' is Op0.
1696   // (A | B) & ~(A & B) --> A ^ B
1697   // (A | B) & ~(B & A) --> A ^ B
1698   if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
1699                         m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
1700     return BinaryOperator::CreateXor(A, B);
1701 
1702   // (A | ~B) & (~A | B) --> ~(A ^ B)
1703   // (A | ~B) & (B | ~A) --> ~(A ^ B)
1704   // (~B | A) & (~A | B) --> ~(A ^ B)
1705   // (~B | A) & (B | ~A) --> ~(A ^ B)
1706   if (Op0->hasOneUse() || Op1->hasOneUse())
1707     if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
1708                           m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
1709       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1710 
1711   return nullptr;
1712 }
1713 
1714 static Instruction *foldOrToXor(BinaryOperator &I,
1715                                 InstCombiner::BuilderTy &Builder) {
1716   assert(I.getOpcode() == Instruction::Or);
1717   Value *Op0 = I.getOperand(0);
1718   Value *Op1 = I.getOperand(1);
1719   Value *A, *B;
1720 
1721   // Operand complexity canonicalization guarantees that the 'and' is Op0.
1722   // (A & B) | ~(A | B) --> ~(A ^ B)
1723   // (A & B) | ~(B | A) --> ~(A ^ B)
1724   if (Op0->hasOneUse() || Op1->hasOneUse())
1725     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1726         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1727       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1728 
1729   // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1730   // (A ^ B) | ~(A | B) --> ~(A & B)
1731   // (A ^ B) | ~(B | A) --> ~(A & B)
1732   if (Op0->hasOneUse() || Op1->hasOneUse())
1733     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1734         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1735       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
1736 
1737   // (A & ~B) | (~A & B) --> A ^ B
1738   // (A & ~B) | (B & ~A) --> A ^ B
1739   // (~B & A) | (~A & B) --> A ^ B
1740   // (~B & A) | (B & ~A) --> A ^ B
1741   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1742       match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1743     return BinaryOperator::CreateXor(A, B);
1744 
1745   return nullptr;
1746 }
1747 
1748 /// Return true if a constant shift amount is always less than the specified
1749 /// bit-width. If not, the shift could create poison in the narrower type.
1750 static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1751   APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1752   return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
1753 }
1754 
1755 /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
1756 /// a common zext operand: and (binop (zext X), C), (zext X).
1757 Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
1758   // This transform could also apply to {or, and, xor}, but there are better
1759   // folds for those cases, so we don't expect those patterns here. AShr is not
1760   // handled because it should always be transformed to LShr in this sequence.
1761   // The subtract transform is different because it has a constant on the left.
1762   // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
1763   Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
1764   Constant *C;
1765   if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
1766       !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
1767       !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
1768       !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
1769       !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
1770     return nullptr;
1771 
1772   Value *X;
1773   if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
1774     return nullptr;
1775 
1776   Type *Ty = And.getType();
1777   if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
1778     return nullptr;
1779 
1780   // If we're narrowing a shift, the shift amount must be safe (less than the
1781   // width) in the narrower type. If the shift amount is greater, instsimplify
1782   // usually handles that case, but we can't guarantee/assert it.
1783   Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
1784   if (Opc == Instruction::LShr || Opc == Instruction::Shl)
1785     if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
1786       return nullptr;
1787 
1788   // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
1789   // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
1790   Value *NewC = ConstantExpr::getTrunc(C, X->getType());
1791   Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
1792                                          : Builder.CreateBinOp(Opc, X, NewC);
1793   return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
1794 }
1795 
1796 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1797 // here. We should standardize that construct where it is needed or choose some
1798 // other way to ensure that commutated variants of patterns are not missed.
1799 Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
1800   Type *Ty = I.getType();
1801 
1802   if (Value *V = SimplifyAndInst(I.getOperand(0), I.getOperand(1),
1803                                  SQ.getWithInstruction(&I)))
1804     return replaceInstUsesWith(I, V);
1805 
1806   if (SimplifyAssociativeOrCommutative(I))
1807     return &I;
1808 
1809   if (Instruction *X = foldVectorBinop(I))
1810     return X;
1811 
1812   // See if we can simplify any instructions used by the instruction whose sole
1813   // purpose is to compute bits we don't care about.
1814   if (SimplifyDemandedInstructionBits(I))
1815     return &I;
1816 
1817   // Do this before using distributive laws to catch simple and/or/not patterns.
1818   if (Instruction *Xor = foldAndToXor(I, Builder))
1819     return Xor;
1820 
1821   // (A|B)&(A|C) -> A|(B&C) etc
1822   if (Value *V = SimplifyUsingDistributiveLaws(I))
1823     return replaceInstUsesWith(I, V);
1824 
1825   if (Value *V = SimplifyBSwap(I, Builder))
1826     return replaceInstUsesWith(I, V);
1827 
1828   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1829 
1830   Value *X, *Y;
1831   if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
1832       match(Op1, m_One())) {
1833     // (1 << X) & 1 --> zext(X == 0)
1834     // (1 >> X) & 1 --> zext(X == 0)
1835     Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
1836     return new ZExtInst(IsZero, Ty);
1837   }
1838 
1839   const APInt *C;
1840   if (match(Op1, m_APInt(C))) {
1841     const APInt *XorC;
1842     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
1843       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1844       Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
1845       Value *And = Builder.CreateAnd(X, Op1);
1846       And->takeName(Op0);
1847       return BinaryOperator::CreateXor(And, NewC);
1848     }
1849 
1850     const APInt *OrC;
1851     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
1852       // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
1853       // NOTE: This reduces the number of bits set in the & mask, which
1854       // can expose opportunities for store narrowing for scalars.
1855       // NOTE: SimplifyDemandedBits should have already removed bits from C1
1856       // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
1857       // above, but this feels safer.
1858       APInt Together = *C & *OrC;
1859       Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
1860       And->takeName(Op0);
1861       return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
1862     }
1863 
1864     // If the mask is only needed on one incoming arm, push the 'and' op up.
1865     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
1866         match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
1867       APInt NotAndMask(~(*C));
1868       BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
1869       if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
1870         // Not masking anything out for the LHS, move mask to RHS.
1871         // and ({x}or X, Y), C --> {x}or X, (and Y, C)
1872         Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
1873         return BinaryOperator::Create(BinOp, X, NewRHS);
1874       }
1875       if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
1876         // Not masking anything out for the RHS, move mask to LHS.
1877         // and ({x}or X, Y), C --> {x}or (and X, C), Y
1878         Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
1879         return BinaryOperator::Create(BinOp, NewLHS, Y);
1880       }
1881     }
1882 
1883     unsigned Width = Ty->getScalarSizeInBits();
1884     const APInt *ShiftC;
1885     if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC)))))) {
1886       if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
1887         // We are clearing high bits that were potentially set by sext+ashr:
1888         // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
1889         Value *Sext = Builder.CreateSExt(X, Ty);
1890         Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
1891         return BinaryOperator::CreateLShr(Sext, ShAmtC);
1892       }
1893     }
1894 
1895     const APInt *AddC;
1896     if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
1897       // If we add zeros to every bit below a mask, the add has no effect:
1898       // (X + AddC) & LowMaskC --> X & LowMaskC
1899       unsigned Ctlz = C->countLeadingZeros();
1900       APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz));
1901       if ((*AddC & LowMask).isZero())
1902         return BinaryOperator::CreateAnd(X, Op1);
1903 
1904       // If we are masking the result of the add down to exactly one bit and
1905       // the constant we are adding has no bits set below that bit, then the
1906       // add is flipping a single bit. Example:
1907       // (X + 4) & 4 --> (X & 4) ^ 4
1908       if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
1909         assert((*C & *AddC) != 0 && "Expected common bit");
1910         Value *NewAnd = Builder.CreateAnd(X, Op1);
1911         return BinaryOperator::CreateXor(NewAnd, Op1);
1912       }
1913     }
1914 
1915     // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
1916     // bitwidth of X and OP behaves well when given trunc(C1) and X.
1917     auto isSuitableBinOpcode = [](BinaryOperator *B) {
1918       switch (B->getOpcode()) {
1919       case Instruction::Xor:
1920       case Instruction::Or:
1921       case Instruction::Mul:
1922       case Instruction::Add:
1923       case Instruction::Sub:
1924         return true;
1925       default:
1926         return false;
1927       }
1928     };
1929     BinaryOperator *BO;
1930     if (match(Op0, m_OneUse(m_BinOp(BO))) && isSuitableBinOpcode(BO)) {
1931       Value *X;
1932       const APInt *C1;
1933       // TODO: The one-use restrictions could be relaxed a little if the AND
1934       // is going to be removed.
1935       if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
1936           C->isIntN(X->getType()->getScalarSizeInBits())) {
1937         unsigned XWidth = X->getType()->getScalarSizeInBits();
1938         Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
1939         Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
1940                            ? Builder.CreateBinOp(BO->getOpcode(), X, TruncC1)
1941                            : Builder.CreateBinOp(BO->getOpcode(), TruncC1, X);
1942         Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
1943         Value *And = Builder.CreateAnd(BinOp, TruncC);
1944         return new ZExtInst(And, Ty);
1945       }
1946     }
1947   }
1948 
1949   if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
1950                       m_SignMask())) &&
1951       match(Y, m_SpecificInt_ICMP(
1952                    ICmpInst::Predicate::ICMP_EQ,
1953                    APInt(Ty->getScalarSizeInBits(),
1954                          Ty->getScalarSizeInBits() -
1955                              X->getType()->getScalarSizeInBits())))) {
1956     auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
1957     auto *SanitizedSignMask = cast<Constant>(Op1);
1958     // We must be careful with the undef elements of the sign bit mask, however:
1959     // the mask elt can be undef iff the shift amount for that lane was undef,
1960     // otherwise we need to sanitize undef masks to zero.
1961     SanitizedSignMask = Constant::replaceUndefsWith(
1962         SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
1963     SanitizedSignMask =
1964         Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
1965     return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
1966   }
1967 
1968   if (Instruction *Z = narrowMaskedBinOp(I))
1969     return Z;
1970 
1971   if (I.getType()->isIntOrIntVectorTy(1)) {
1972     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
1973       if (auto *I =
1974               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
1975         return I;
1976     }
1977     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
1978       if (auto *I =
1979               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
1980         return I;
1981     }
1982   }
1983 
1984   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
1985     return FoldedLogic;
1986 
1987   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1988     return DeMorgan;
1989 
1990   {
1991     Value *A, *B, *C;
1992     // A & (A ^ B) --> A & ~B
1993     if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
1994       return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
1995     // (A ^ B) & A --> A & ~B
1996     if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
1997       return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
1998 
1999     // A & ~(A ^ B) --> A & B
2000     if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2001       return BinaryOperator::CreateAnd(Op0, B);
2002     // ~(A ^ B) & A --> A & B
2003     if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2004       return BinaryOperator::CreateAnd(Op1, B);
2005 
2006     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
2007     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2008       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2009         if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
2010           return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
2011 
2012     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
2013     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2014       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2015         if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
2016           return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
2017 
2018     // (A | B) & ((~A) ^ B) -> (A & B)
2019     // (A | B) & (B ^ (~A)) -> (A & B)
2020     // (B | A) & ((~A) ^ B) -> (A & B)
2021     // (B | A) & (B ^ (~A)) -> (A & B)
2022     if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2023         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2024       return BinaryOperator::CreateAnd(A, B);
2025 
2026     // ((~A) ^ B) & (A | B) -> (A & B)
2027     // ((~A) ^ B) & (B | A) -> (A & B)
2028     // (B ^ (~A)) & (A | B) -> (A & B)
2029     // (B ^ (~A)) & (B | A) -> (A & B)
2030     if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2031         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2032       return BinaryOperator::CreateAnd(A, B);
2033   }
2034 
2035   {
2036     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2037     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2038     if (LHS && RHS)
2039       if (Value *Res = foldAndOfICmps(LHS, RHS, I))
2040         return replaceInstUsesWith(I, Res);
2041 
2042     // TODO: Make this recursive; it's a little tricky because an arbitrary
2043     // number of 'and' instructions might have to be created.
2044     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
2045       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2046         if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
2047           return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
2048       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2049         if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
2050           return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
2051     }
2052     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
2053       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2054         if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
2055           return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y));
2056       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2057         if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
2058           return replaceInstUsesWith(I, Builder.CreateAnd(Res, X));
2059     }
2060   }
2061 
2062   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2063     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2064       if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
2065         return replaceInstUsesWith(I, Res);
2066 
2067   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2068     return FoldedFCmps;
2069 
2070   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
2071     return CastedAnd;
2072 
2073   // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
2074   Value *A;
2075   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2076       A->getType()->isIntOrIntVectorTy(1))
2077     return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
2078   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2079       A->getType()->isIntOrIntVectorTy(1))
2080     return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
2081 
2082   // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0
2083   unsigned FullShift = Ty->getScalarSizeInBits() - 1;
2084   if (match(&I, m_c_And(m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))),
2085                         m_Value(Y)))) {
2086     Constant *Zero = ConstantInt::getNullValue(Ty);
2087     Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg");
2088     return SelectInst::Create(Cmp, Y, Zero);
2089   }
2090 
2091   // (~x) & y  -->  ~(x | (~y))  iff that gets rid of inversions
2092   if (sinkNotIntoOtherHandOfAndOrOr(I))
2093     return &I;
2094 
2095   // An and recurrence w/loop invariant step is equivelent to (and start, step)
2096   PHINode *PN = nullptr;
2097   Value *Start = nullptr, *Step = nullptr;
2098   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2099     return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
2100 
2101   return nullptr;
2102 }
2103 
2104 Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
2105                                                       bool MatchBSwaps,
2106                                                       bool MatchBitReversals) {
2107   SmallVector<Instruction *, 4> Insts;
2108   if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
2109                                        Insts))
2110     return nullptr;
2111   Instruction *LastInst = Insts.pop_back_val();
2112   LastInst->removeFromParent();
2113 
2114   for (auto *Inst : Insts)
2115     Worklist.push(Inst);
2116   return LastInst;
2117 }
2118 
2119 /// Match UB-safe variants of the funnel shift intrinsic.
2120 static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
2121   // TODO: Can we reduce the code duplication between this and the related
2122   // rotate matching code under visitSelect and visitTrunc?
2123   unsigned Width = Or.getType()->getScalarSizeInBits();
2124 
2125   // First, find an or'd pair of opposite shifts:
2126   // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
2127   BinaryOperator *Or0, *Or1;
2128   if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
2129       !match(Or.getOperand(1), m_BinOp(Or1)))
2130     return nullptr;
2131 
2132   Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
2133   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
2134       !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2135       Or0->getOpcode() == Or1->getOpcode())
2136     return nullptr;
2137 
2138   // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2139   if (Or0->getOpcode() == BinaryOperator::LShr) {
2140     std::swap(Or0, Or1);
2141     std::swap(ShVal0, ShVal1);
2142     std::swap(ShAmt0, ShAmt1);
2143   }
2144   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2145          Or1->getOpcode() == BinaryOperator::LShr &&
2146          "Illegal or(shift,shift) pair");
2147 
2148   // Match the shift amount operands for a funnel shift pattern. This always
2149   // matches a subtraction on the R operand.
2150   auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2151     // Check for constant shift amounts that sum to the bitwidth.
2152     const APInt *LI, *RI;
2153     if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
2154       if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2155         return ConstantInt::get(L->getType(), *LI);
2156 
2157     Constant *LC, *RC;
2158     if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
2159         match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2160         match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
2161         match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
2162       return ConstantExpr::mergeUndefsWith(LC, RC);
2163 
2164     // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
2165     // We limit this to X < Width in case the backend re-expands the intrinsic,
2166     // and has to reintroduce a shift modulo operation (InstCombine might remove
2167     // it after this fold). This still doesn't guarantee that the final codegen
2168     // will match this original pattern.
2169     if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
2170       KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or);
2171       return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2172     }
2173 
2174     // For non-constant cases, the following patterns currently only work for
2175     // rotation patterns.
2176     // TODO: Add general funnel-shift compatible patterns.
2177     if (ShVal0 != ShVal1)
2178       return nullptr;
2179 
2180     // For non-constant cases we don't support non-pow2 shift masks.
2181     // TODO: Is it worth matching urem as well?
2182     if (!isPowerOf2_32(Width))
2183       return nullptr;
2184 
2185     // The shift amount may be masked with negation:
2186     // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
2187     Value *X;
2188     unsigned Mask = Width - 1;
2189     if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
2190         match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
2191       return X;
2192 
2193     // Similar to above, but the shift amount may be extended after masking,
2194     // so return the extended value as the parameter for the intrinsic.
2195     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2196         match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
2197                        m_SpecificInt(Mask))))
2198       return L;
2199 
2200     if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2201         match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
2202       return L;
2203 
2204     return nullptr;
2205   };
2206 
2207   Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
2208   bool IsFshl = true; // Sub on LSHR.
2209   if (!ShAmt) {
2210     ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2211     IsFshl = false; // Sub on SHL.
2212   }
2213   if (!ShAmt)
2214     return nullptr;
2215 
2216   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2217   Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
2218   return CallInst::Create(F, {ShVal0, ShVal1, ShAmt});
2219 }
2220 
2221 /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
2222 static Instruction *matchOrConcat(Instruction &Or,
2223                                   InstCombiner::BuilderTy &Builder) {
2224   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
2225   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
2226   Type *Ty = Or.getType();
2227 
2228   unsigned Width = Ty->getScalarSizeInBits();
2229   if ((Width & 1) != 0)
2230     return nullptr;
2231   unsigned HalfWidth = Width / 2;
2232 
2233   // Canonicalize zext (lower half) to LHS.
2234   if (!isa<ZExtInst>(Op0))
2235     std::swap(Op0, Op1);
2236 
2237   // Find lower/upper half.
2238   Value *LowerSrc, *ShlVal, *UpperSrc;
2239   const APInt *C;
2240   if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
2241       !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
2242       !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
2243     return nullptr;
2244   if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
2245       LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
2246     return nullptr;
2247 
2248   auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
2249     Value *NewLower = Builder.CreateZExt(Lo, Ty);
2250     Value *NewUpper = Builder.CreateZExt(Hi, Ty);
2251     NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
2252     Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
2253     Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
2254     return Builder.CreateCall(F, BinOp);
2255   };
2256 
2257   // BSWAP: Push the concat down, swapping the lower/upper sources.
2258   // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
2259   Value *LowerBSwap, *UpperBSwap;
2260   if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
2261       match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
2262     return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
2263 
2264   // BITREVERSE: Push the concat down, swapping the lower/upper sources.
2265   // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
2266   Value *LowerBRev, *UpperBRev;
2267   if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
2268       match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
2269     return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
2270 
2271   return nullptr;
2272 }
2273 
2274 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
2275 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
2276   unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
2277   for (unsigned i = 0; i != NumElts; ++i) {
2278     Constant *EltC1 = C1->getAggregateElement(i);
2279     Constant *EltC2 = C2->getAggregateElement(i);
2280     if (!EltC1 || !EltC2)
2281       return false;
2282 
2283     // One element must be all ones, and the other must be all zeros.
2284     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
2285           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
2286       return false;
2287   }
2288   return true;
2289 }
2290 
2291 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
2292 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
2293 /// B, it can be used as the condition operand of a select instruction.
2294 Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B) {
2295   // Step 1: We may have peeked through bitcasts in the caller.
2296   // Exit immediately if we don't have (vector) integer types.
2297   Type *Ty = A->getType();
2298   if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
2299     return nullptr;
2300 
2301   // Step 2: We need 0 or all-1's bitmasks.
2302   if (ComputeNumSignBits(A) != Ty->getScalarSizeInBits())
2303     return nullptr;
2304 
2305   // Step 3: If B is the 'not' value of A, we have our answer.
2306   if (match(A, m_Not(m_Specific(B)))) {
2307     // If these are scalars or vectors of i1, A can be used directly.
2308     if (Ty->isIntOrIntVectorTy(1))
2309       return A;
2310     return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(Ty));
2311   }
2312 
2313   // If both operands are constants, see if the constants are inverse bitmasks.
2314   Constant *AConst, *BConst;
2315   if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
2316     if (AConst == ConstantExpr::getNot(BConst))
2317       return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
2318 
2319   // Look for more complex patterns. The 'not' op may be hidden behind various
2320   // casts. Look through sexts and bitcasts to find the booleans.
2321   Value *Cond;
2322   Value *NotB;
2323   if (match(A, m_SExt(m_Value(Cond))) &&
2324       Cond->getType()->isIntOrIntVectorTy(1) &&
2325       match(B, m_OneUse(m_Not(m_Value(NotB))))) {
2326     NotB = peekThroughBitcast(NotB, true);
2327     if (match(NotB, m_SExt(m_Specific(Cond))))
2328       return Cond;
2329   }
2330 
2331   // All scalar (and most vector) possibilities should be handled now.
2332   // Try more matches that only apply to non-splat constant vectors.
2333   if (!Ty->isVectorTy())
2334     return nullptr;
2335 
2336   // If both operands are xor'd with constants using the same sexted boolean
2337   // operand, see if the constants are inverse bitmasks.
2338   // TODO: Use ConstantExpr::getNot()?
2339   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
2340       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
2341       Cond->getType()->isIntOrIntVectorTy(1) &&
2342       areInverseVectorBitmasks(AConst, BConst)) {
2343     AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
2344     return Builder.CreateXor(Cond, AConst);
2345   }
2346   return nullptr;
2347 }
2348 
2349 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
2350 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
2351 Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
2352                                               Value *D) {
2353   // The potential condition of the select may be bitcasted. In that case, look
2354   // through its bitcast and the corresponding bitcast of the 'not' condition.
2355   Type *OrigType = A->getType();
2356   A = peekThroughBitcast(A, true);
2357   B = peekThroughBitcast(B, true);
2358   if (Value *Cond = getSelectCondition(A, B)) {
2359     // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
2360     // The bitcasts will either all exist or all not exist. The builder will
2361     // not create unnecessary casts if the types already match.
2362     Value *BitcastC = Builder.CreateBitCast(C, A->getType());
2363     Value *BitcastD = Builder.CreateBitCast(D, A->getType());
2364     Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
2365     return Builder.CreateBitCast(Select, OrigType);
2366   }
2367 
2368   return nullptr;
2369 }
2370 
2371 /// Fold (icmp)|(icmp) if possible.
2372 Value *InstCombinerImpl::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
2373                                        BinaryOperator &Or) {
2374   const SimplifyQuery Q = SQ.getWithInstruction(&Or);
2375 
2376   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
2377   // if K1 and K2 are a one-bit mask.
2378   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &Or,
2379                                                /* IsAnd */ false))
2380     return V;
2381 
2382   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
2383   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
2384   Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
2385   auto *LHSC = dyn_cast<ConstantInt>(LHS1);
2386   auto *RHSC = dyn_cast<ConstantInt>(RHS1);
2387 
2388   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
2389   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
2390   // The original condition actually refers to the following two ranges:
2391   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
2392   // We can fold these two ranges if:
2393   // 1) C1 and C2 is unsigned greater than C3.
2394   // 2) The two ranges are separated.
2395   // 3) C1 ^ C2 is one-bit mask.
2396   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
2397   // This implies all values in the two ranges differ by exactly one bit.
2398   if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
2399       PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
2400       LHSC->getType() == RHSC->getType() &&
2401       LHSC->getValue() == (RHSC->getValue())) {
2402 
2403     Value *AddOpnd;
2404     ConstantInt *LAddC, *RAddC;
2405     if (match(LHS0, m_Add(m_Value(AddOpnd), m_ConstantInt(LAddC))) &&
2406         match(RHS0, m_Add(m_Specific(AddOpnd), m_ConstantInt(RAddC))) &&
2407         LAddC->getValue().ugt(LHSC->getValue()) &&
2408         RAddC->getValue().ugt(LHSC->getValue())) {
2409 
2410       APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
2411       if (DiffC.isPowerOf2()) {
2412         ConstantInt *MaxAddC = nullptr;
2413         if (LAddC->getValue().ult(RAddC->getValue()))
2414           MaxAddC = RAddC;
2415         else
2416           MaxAddC = LAddC;
2417 
2418         APInt RRangeLow = -RAddC->getValue();
2419         APInt RRangeHigh = RRangeLow + LHSC->getValue();
2420         APInt LRangeLow = -LAddC->getValue();
2421         APInt LRangeHigh = LRangeLow + LHSC->getValue();
2422         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
2423         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
2424         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
2425                                                    : RRangeLow - LRangeLow;
2426 
2427         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
2428             RangeDiff.ugt(LHSC->getValue())) {
2429           Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
2430 
2431           Value *NewAnd = Builder.CreateAnd(AddOpnd, MaskC);
2432           Value *NewAdd = Builder.CreateAdd(NewAnd, MaxAddC);
2433           return Builder.CreateICmp(LHS->getPredicate(), NewAdd, LHSC);
2434         }
2435       }
2436     }
2437   }
2438 
2439   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
2440   if (predicatesFoldable(PredL, PredR)) {
2441     if (LHS0 == RHS1 && LHS1 == RHS0)
2442       LHS->swapOperands();
2443     if (LHS0 == RHS0 && LHS1 == RHS1) {
2444       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
2445       bool IsSigned = LHS->isSigned() || RHS->isSigned();
2446       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
2447     }
2448   }
2449 
2450   // handle (roughly):
2451   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
2452   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
2453     return V;
2454 
2455   if (LHS->hasOneUse() || RHS->hasOneUse()) {
2456     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
2457     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
2458     Value *A = nullptr, *B = nullptr;
2459     if (PredL == ICmpInst::ICMP_EQ && match(LHS1, m_Zero())) {
2460       B = LHS0;
2461       if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS1)
2462         A = RHS0;
2463       else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
2464         A = RHS1;
2465     }
2466     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
2467     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
2468     else if (PredR == ICmpInst::ICMP_EQ && match(RHS1, m_Zero())) {
2469       B = RHS0;
2470       if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS1)
2471         A = LHS0;
2472       else if (PredL == ICmpInst::ICMP_UGT && RHS0 == LHS0)
2473         A = LHS1;
2474     }
2475     if (A && B && B->getType()->isIntOrIntVectorTy())
2476       return Builder.CreateICmp(
2477           ICmpInst::ICMP_UGE,
2478           Builder.CreateAdd(B, Constant::getAllOnesValue(B->getType())), A);
2479   }
2480 
2481   if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, Or, Builder, Q))
2482     return V;
2483   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, Or, Builder, Q))
2484     return V;
2485 
2486   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
2487   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
2488     return V;
2489 
2490   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
2491   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
2492     return V;
2493 
2494   if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
2495     return V;
2496 
2497   if (Value *V = foldIsPowerOf2(LHS, RHS, false /* JoinedByAnd */, Builder))
2498     return V;
2499 
2500   if (Value *X =
2501           foldUnsignedUnderflowCheck(LHS, RHS, /*IsAnd=*/false, Q, Builder))
2502     return X;
2503   if (Value *X =
2504           foldUnsignedUnderflowCheck(RHS, LHS, /*IsAnd=*/false, Q, Builder))
2505     return X;
2506 
2507   if (Value *X = foldEqOfParts(LHS, RHS, /*IsAnd=*/false))
2508     return X;
2509 
2510   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
2511   // TODO: Remove this when foldLogOpOfMaskedICmps can handle vectors.
2512   if (PredL == ICmpInst::ICMP_NE && match(LHS1, m_Zero()) &&
2513       PredR == ICmpInst::ICMP_NE && match(RHS1, m_Zero()) &&
2514       LHS0->getType()->isIntOrIntVectorTy() &&
2515       LHS0->getType() == RHS0->getType()) {
2516     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
2517     return Builder.CreateICmp(PredL, NewOr,
2518                               Constant::getNullValue(NewOr->getType()));
2519   }
2520 
2521   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
2522   if (!LHSC || !RHSC)
2523     return nullptr;
2524 
2525   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
2526   //   iff C2 + CA == C1.
2527   if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
2528     ConstantInt *AddC;
2529     if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
2530       if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
2531         return Builder.CreateICmpULE(LHS0, LHSC);
2532   }
2533 
2534   // From here on, we only handle:
2535   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
2536   if (LHS0 != RHS0)
2537     return nullptr;
2538 
2539   // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
2540   if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
2541       PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
2542       PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
2543       PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
2544     return nullptr;
2545 
2546   // We can't fold (ugt x, C) | (sgt x, C2).
2547   if (!predicatesFoldable(PredL, PredR))
2548     return nullptr;
2549 
2550   // Ensure that the larger constant is on the RHS.
2551   bool ShouldSwap;
2552   if (CmpInst::isSigned(PredL) ||
2553       (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
2554     ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
2555   else
2556     ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
2557 
2558   if (ShouldSwap) {
2559     std::swap(LHS, RHS);
2560     std::swap(LHSC, RHSC);
2561     std::swap(PredL, PredR);
2562   }
2563 
2564   // At this point, we know we have two icmp instructions
2565   // comparing a value against two constants and or'ing the result
2566   // together.  Because of the above check, we know that we only have
2567   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
2568   // icmp folding check above), that the two constants are not
2569   // equal.
2570   assert(LHSC != RHSC && "Compares not folded above?");
2571 
2572   switch (PredL) {
2573   default:
2574     llvm_unreachable("Unknown integer condition code!");
2575   case ICmpInst::ICMP_EQ:
2576     switch (PredR) {
2577     default:
2578       llvm_unreachable("Unknown integer condition code!");
2579     case ICmpInst::ICMP_EQ:
2580       // Potential folds for this case should already be handled.
2581       break;
2582     case ICmpInst::ICMP_UGT:
2583       // (X == 0 || X u> C) -> (X-1) u>= C
2584       if (LHSC->isMinValue(false))
2585         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue() + 1,
2586                                false, false);
2587       // (X == 13 | X u> 14) -> no change
2588       break;
2589     case ICmpInst::ICMP_SGT:
2590       // (X == INT_MIN || X s> C) -> (X-(INT_MIN+1)) u>= C-INT_MIN
2591       if (LHSC->isMinValue(true))
2592         return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue() + 1,
2593                                true, false);
2594       // (X == 13 | X s> 14) -> no change
2595       break;
2596     }
2597     break;
2598   case ICmpInst::ICMP_ULT:
2599     switch (PredR) {
2600     default:
2601       llvm_unreachable("Unknown integer condition code!");
2602     case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
2603       // (X u< C || X == UINT_MAX) => (X-C) u>= UINT_MAX-C
2604       if (RHSC->isMaxValue(false))
2605         return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue(),
2606                                false, false);
2607       break;
2608     case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
2609       assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
2610       return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
2611                              false, false);
2612     }
2613     break;
2614   case ICmpInst::ICMP_SLT:
2615     switch (PredR) {
2616     default:
2617       llvm_unreachable("Unknown integer condition code!");
2618     case ICmpInst::ICMP_EQ:
2619       // (X s< C || X == INT_MAX) => (X-C) u>= INT_MAX-C
2620       if (RHSC->isMaxValue(true))
2621         return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue(),
2622                                true, false);
2623       // (X s< 13 | X == 14) -> no change
2624       break;
2625     case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) u> 2
2626       assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
2627       return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
2628                              false);
2629     }
2630     break;
2631   }
2632   return nullptr;
2633 }
2634 
2635 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2636 // here. We should standardize that construct where it is needed or choose some
2637 // other way to ensure that commutated variants of patterns are not missed.
2638 Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
2639   if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1),
2640                                 SQ.getWithInstruction(&I)))
2641     return replaceInstUsesWith(I, V);
2642 
2643   if (SimplifyAssociativeOrCommutative(I))
2644     return &I;
2645 
2646   if (Instruction *X = foldVectorBinop(I))
2647     return X;
2648 
2649   // See if we can simplify any instructions used by the instruction whose sole
2650   // purpose is to compute bits we don't care about.
2651   if (SimplifyDemandedInstructionBits(I))
2652     return &I;
2653 
2654   // Do this before using distributive laws to catch simple and/or/not patterns.
2655   if (Instruction *Xor = foldOrToXor(I, Builder))
2656     return Xor;
2657 
2658   // (A&B)|(A&C) -> A&(B|C) etc
2659   if (Value *V = SimplifyUsingDistributiveLaws(I))
2660     return replaceInstUsesWith(I, V);
2661 
2662   if (Value *V = SimplifyBSwap(I, Builder))
2663     return replaceInstUsesWith(I, V);
2664 
2665   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2666   if (I.getType()->isIntOrIntVectorTy(1)) {
2667     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
2668       if (auto *I =
2669               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
2670         return I;
2671     }
2672     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
2673       if (auto *I =
2674               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
2675         return I;
2676     }
2677   }
2678 
2679   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
2680     return FoldedLogic;
2681 
2682   if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
2683                                                   /*MatchBitReversals*/ true))
2684     return BitOp;
2685 
2686   if (Instruction *Funnel = matchFunnelShift(I, *this))
2687     return Funnel;
2688 
2689   if (Instruction *Concat = matchOrConcat(I, Builder))
2690     return replaceInstUsesWith(I, Concat);
2691 
2692   Value *X, *Y;
2693   const APInt *CV;
2694   if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
2695       !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
2696     // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
2697     // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
2698     Value *Or = Builder.CreateOr(X, Y);
2699     return BinaryOperator::CreateXor(Or, ConstantInt::get(I.getType(), *CV));
2700   }
2701 
2702   // (A & C)|(B & D)
2703   Value *A, *B, *C, *D;
2704   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2705       match(Op1, m_And(m_Value(B), m_Value(D)))) {
2706     // (A & C1)|(B & C2)
2707     ConstantInt *C1, *C2;
2708     if (match(C, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2))) {
2709       Value *V1 = nullptr, *V2 = nullptr;
2710       if ((C1->getValue() & C2->getValue()).isZero()) {
2711         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2712         // iff (C1&C2) == 0 and (N&~C1) == 0
2713         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2714             ((V1 == B &&
2715               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2716              (V2 == B &&
2717               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
2718           return BinaryOperator::CreateAnd(A,
2719                                 Builder.getInt(C1->getValue()|C2->getValue()));
2720         // Or commutes, try both ways.
2721         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2722             ((V1 == A &&
2723               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2724              (V2 == A &&
2725               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
2726           return BinaryOperator::CreateAnd(B,
2727                                  Builder.getInt(C1->getValue()|C2->getValue()));
2728 
2729         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2730         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2731         ConstantInt *C3 = nullptr, *C4 = nullptr;
2732         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2733             (C3->getValue() & ~C1->getValue()).isZero() &&
2734             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2735             (C4->getValue() & ~C2->getValue()).isZero()) {
2736           V2 = Builder.CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2737           return BinaryOperator::CreateAnd(V2,
2738                                  Builder.getInt(C1->getValue()|C2->getValue()));
2739         }
2740       }
2741 
2742       if (C1->getValue() == ~C2->getValue()) {
2743         Value *X;
2744 
2745         // ((X|B)&C1)|(B&C2) -> (X&C1) | B iff C1 == ~C2
2746         if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
2747           return BinaryOperator::CreateOr(Builder.CreateAnd(X, C1), B);
2748         // (A&C2)|((X|A)&C1) -> (X&C2) | A iff C1 == ~C2
2749         if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
2750           return BinaryOperator::CreateOr(Builder.CreateAnd(X, C2), A);
2751 
2752         // ((X^B)&C1)|(B&C2) -> (X&C1) ^ B iff C1 == ~C2
2753         if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
2754           return BinaryOperator::CreateXor(Builder.CreateAnd(X, C1), B);
2755         // (A&C2)|((X^A)&C1) -> (X&C2) ^ A iff C1 == ~C2
2756         if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
2757           return BinaryOperator::CreateXor(Builder.CreateAnd(X, C2), A);
2758       }
2759     }
2760 
2761     // Don't try to form a select if it's unlikely that we'll get rid of at
2762     // least one of the operands. A select is generally more expensive than the
2763     // 'or' that it is replacing.
2764     if (Op0->hasOneUse() || Op1->hasOneUse()) {
2765       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2766       if (Value *V = matchSelectFromAndOr(A, C, B, D))
2767         return replaceInstUsesWith(I, V);
2768       if (Value *V = matchSelectFromAndOr(A, C, D, B))
2769         return replaceInstUsesWith(I, V);
2770       if (Value *V = matchSelectFromAndOr(C, A, B, D))
2771         return replaceInstUsesWith(I, V);
2772       if (Value *V = matchSelectFromAndOr(C, A, D, B))
2773         return replaceInstUsesWith(I, V);
2774       if (Value *V = matchSelectFromAndOr(B, D, A, C))
2775         return replaceInstUsesWith(I, V);
2776       if (Value *V = matchSelectFromAndOr(B, D, C, A))
2777         return replaceInstUsesWith(I, V);
2778       if (Value *V = matchSelectFromAndOr(D, B, A, C))
2779         return replaceInstUsesWith(I, V);
2780       if (Value *V = matchSelectFromAndOr(D, B, C, A))
2781         return replaceInstUsesWith(I, V);
2782     }
2783   }
2784 
2785   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2786   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2787     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2788       return BinaryOperator::CreateOr(Op0, C);
2789 
2790   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2791   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2792     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2793       return BinaryOperator::CreateOr(Op1, C);
2794 
2795   // ((B | C) & A) | B -> B | (A & C)
2796   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2797     return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
2798 
2799   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2800     return DeMorgan;
2801 
2802   // Canonicalize xor to the RHS.
2803   bool SwappedForXor = false;
2804   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2805     std::swap(Op0, Op1);
2806     SwappedForXor = true;
2807   }
2808 
2809   // A | ( A ^ B) -> A |  B
2810   // A | (~A ^ B) -> A | ~B
2811   // (A & B) | (A ^ B)
2812   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2813     if (Op0 == A || Op0 == B)
2814       return BinaryOperator::CreateOr(A, B);
2815 
2816     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2817         match(Op0, m_And(m_Specific(B), m_Specific(A))))
2818       return BinaryOperator::CreateOr(A, B);
2819 
2820     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2821       Value *Not = Builder.CreateNot(B, B->getName() + ".not");
2822       return BinaryOperator::CreateOr(Not, Op0);
2823     }
2824     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2825       Value *Not = Builder.CreateNot(A, A->getName() + ".not");
2826       return BinaryOperator::CreateOr(Not, Op0);
2827     }
2828   }
2829 
2830   // A | ~(A | B) -> A | ~B
2831   // A | ~(A ^ B) -> A | ~B
2832   if (match(Op1, m_Not(m_Value(A))))
2833     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2834       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2835           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2836                                B->getOpcode() == Instruction::Xor)) {
2837         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2838                                                  B->getOperand(0);
2839         Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
2840         return BinaryOperator::CreateOr(Not, Op0);
2841       }
2842 
2843   if (SwappedForXor)
2844     std::swap(Op0, Op1);
2845 
2846   {
2847     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2848     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2849     if (LHS && RHS)
2850       if (Value *Res = foldOrOfICmps(LHS, RHS, I))
2851         return replaceInstUsesWith(I, Res);
2852 
2853     // TODO: Make this recursive; it's a little tricky because an arbitrary
2854     // number of 'or' instructions might have to be created.
2855     Value *X, *Y;
2856     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2857       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2858         if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2859           return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2860       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2861         if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2862           return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2863     }
2864     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2865       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2866         if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2867           return replaceInstUsesWith(I, Builder.CreateOr(Res, Y));
2868       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2869         if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2870           return replaceInstUsesWith(I, Builder.CreateOr(Res, X));
2871     }
2872   }
2873 
2874   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2875     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2876       if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
2877         return replaceInstUsesWith(I, Res);
2878 
2879   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
2880     return FoldedFCmps;
2881 
2882   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2883     return CastedOr;
2884 
2885   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2886   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2887       A->getType()->isIntOrIntVectorTy(1))
2888     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2889   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2890       A->getType()->isIntOrIntVectorTy(1))
2891     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2892 
2893   // Note: If we've gotten to the point of visiting the outer OR, then the
2894   // inner one couldn't be simplified.  If it was a constant, then it won't
2895   // be simplified by a later pass either, so we try swapping the inner/outer
2896   // ORs in the hopes that we'll be able to simplify it this way.
2897   // (X|C) | V --> (X|V) | C
2898   ConstantInt *CI;
2899   if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
2900       match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
2901     Value *Inner = Builder.CreateOr(A, Op1);
2902     Inner->takeName(Op0);
2903     return BinaryOperator::CreateOr(Inner, CI);
2904   }
2905 
2906   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2907   // Since this OR statement hasn't been optimized further yet, we hope
2908   // that this transformation will allow the new ORs to be optimized.
2909   {
2910     Value *X = nullptr, *Y = nullptr;
2911     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2912         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2913         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2914       Value *orTrue = Builder.CreateOr(A, C);
2915       Value *orFalse = Builder.CreateOr(B, D);
2916       return SelectInst::Create(X, orTrue, orFalse);
2917     }
2918   }
2919 
2920   // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X)  --> X s> Y ? -1 : X.
2921   {
2922     Value *X, *Y;
2923     Type *Ty = I.getType();
2924     if (match(&I, m_c_Or(m_OneUse(m_AShr(
2925                              m_NSWSub(m_Value(Y), m_Value(X)),
2926                              m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
2927                          m_Deferred(X)))) {
2928       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
2929       Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
2930       return SelectInst::Create(NewICmpInst, AllOnes, X);
2931     }
2932   }
2933 
2934   if (Instruction *V =
2935           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
2936     return V;
2937 
2938   CmpInst::Predicate Pred;
2939   Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
2940   // Check if the OR weakens the overflow condition for umul.with.overflow by
2941   // treating any non-zero result as overflow. In that case, we overflow if both
2942   // umul.with.overflow operands are != 0, as in that case the result can only
2943   // be 0, iff the multiplication overflows.
2944   if (match(&I,
2945             m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
2946                                 m_Value(Ov)),
2947                    m_CombineAnd(m_ICmp(Pred,
2948                                        m_CombineAnd(m_ExtractValue<0>(
2949                                                         m_Deferred(UMulWithOv)),
2950                                                     m_Value(Mul)),
2951                                        m_ZeroInt()),
2952                                 m_Value(MulIsNotZero)))) &&
2953       (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
2954       Pred == CmpInst::ICMP_NE) {
2955     Value *A, *B;
2956     if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
2957                               m_Value(A), m_Value(B)))) {
2958       Value *NotNullA = Builder.CreateIsNotNull(A);
2959       Value *NotNullB = Builder.CreateIsNotNull(B);
2960       return BinaryOperator::CreateAnd(NotNullA, NotNullB);
2961     }
2962   }
2963 
2964   // (~x) | y  -->  ~(x & (~y))  iff that gets rid of inversions
2965   if (sinkNotIntoOtherHandOfAndOrOr(I))
2966     return &I;
2967 
2968   // Improve "get low bit mask up to and including bit X" pattern:
2969   //   (1 << X) | ((1 << X) + -1)  -->  -1 l>> (bitwidth(x) - 1 - X)
2970   if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
2971                        m_Shl(m_One(), m_Deferred(X)))) &&
2972       match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
2973     Type *Ty = X->getType();
2974     Value *Sub = Builder.CreateSub(
2975         ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
2976     return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
2977   }
2978 
2979   // An or recurrence w/loop invariant step is equivelent to (or start, step)
2980   PHINode *PN = nullptr;
2981   Value *Start = nullptr, *Step = nullptr;
2982   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2983     return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
2984 
2985   return nullptr;
2986 }
2987 
2988 /// A ^ B can be specified using other logic ops in a variety of patterns. We
2989 /// can fold these early and efficiently by morphing an existing instruction.
2990 static Instruction *foldXorToXor(BinaryOperator &I,
2991                                  InstCombiner::BuilderTy &Builder) {
2992   assert(I.getOpcode() == Instruction::Xor);
2993   Value *Op0 = I.getOperand(0);
2994   Value *Op1 = I.getOperand(1);
2995   Value *A, *B;
2996 
2997   // There are 4 commuted variants for each of the basic patterns.
2998 
2999   // (A & B) ^ (A | B) -> A ^ B
3000   // (A & B) ^ (B | A) -> A ^ B
3001   // (A | B) ^ (A & B) -> A ^ B
3002   // (A | B) ^ (B & A) -> A ^ B
3003   if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
3004                         m_c_Or(m_Deferred(A), m_Deferred(B)))))
3005     return BinaryOperator::CreateXor(A, B);
3006 
3007   // (A | ~B) ^ (~A | B) -> A ^ B
3008   // (~B | A) ^ (~A | B) -> A ^ B
3009   // (~A | B) ^ (A | ~B) -> A ^ B
3010   // (B | ~A) ^ (A | ~B) -> A ^ B
3011   if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
3012                       m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
3013     return BinaryOperator::CreateXor(A, B);
3014 
3015   // (A & ~B) ^ (~A & B) -> A ^ B
3016   // (~B & A) ^ (~A & B) -> A ^ B
3017   // (~A & B) ^ (A & ~B) -> A ^ B
3018   // (B & ~A) ^ (A & ~B) -> A ^ B
3019   if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
3020                       m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
3021     return BinaryOperator::CreateXor(A, B);
3022 
3023   // For the remaining cases we need to get rid of one of the operands.
3024   if (!Op0->hasOneUse() && !Op1->hasOneUse())
3025     return nullptr;
3026 
3027   // (A | B) ^ ~(A & B) -> ~(A ^ B)
3028   // (A | B) ^ ~(B & A) -> ~(A ^ B)
3029   // (A & B) ^ ~(A | B) -> ~(A ^ B)
3030   // (A & B) ^ ~(B | A) -> ~(A ^ B)
3031   // Complexity sorting ensures the not will be on the right side.
3032   if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
3033        match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
3034       (match(Op0, m_And(m_Value(A), m_Value(B))) &&
3035        match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
3036     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
3037 
3038   return nullptr;
3039 }
3040 
3041 Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
3042                                         BinaryOperator &I) {
3043   assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
3044          I.getOperand(1) == RHS && "Should be 'xor' with these operands");
3045 
3046   if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
3047     if (LHS->getOperand(0) == RHS->getOperand(1) &&
3048         LHS->getOperand(1) == RHS->getOperand(0))
3049       LHS->swapOperands();
3050     if (LHS->getOperand(0) == RHS->getOperand(0) &&
3051         LHS->getOperand(1) == RHS->getOperand(1)) {
3052       // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3053       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
3054       unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
3055       bool IsSigned = LHS->isSigned() || RHS->isSigned();
3056       return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder);
3057     }
3058   }
3059 
3060   // TODO: This can be generalized to compares of non-signbits using
3061   // decomposeBitTestICmp(). It could be enhanced more by using (something like)
3062   // foldLogOpOfMaskedICmps().
3063   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3064   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
3065   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
3066   if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
3067       LHS0->getType() == RHS0->getType() &&
3068       LHS0->getType()->isIntOrIntVectorTy()) {
3069     // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
3070     // (X <  0) ^ (Y <  0) --> (X ^ Y) < 0
3071     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
3072          PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) ||
3073         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
3074          PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) {
3075       Value *Zero = ConstantInt::getNullValue(LHS0->getType());
3076       return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero);
3077     }
3078     // (X > -1) ^ (Y <  0) --> (X ^ Y) > -1
3079     // (X <  0) ^ (Y > -1) --> (X ^ Y) > -1
3080     if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) &&
3081          PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) ||
3082         (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) &&
3083          PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) {
3084       Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType());
3085       return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne);
3086     }
3087   }
3088 
3089   // Instead of trying to imitate the folds for and/or, decompose this 'xor'
3090   // into those logic ops. That is, try to turn this into an and-of-icmps
3091   // because we have many folds for that pattern.
3092   //
3093   // This is based on a truth table definition of xor:
3094   // X ^ Y --> (X | Y) & !(X & Y)
3095   if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
3096     // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
3097     // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
3098     if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
3099       // TODO: Independently handle cases where the 'and' side is a constant.
3100       ICmpInst *X = nullptr, *Y = nullptr;
3101       if (OrICmp == LHS && AndICmp == RHS) {
3102         // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS  --> X & !Y
3103         X = LHS;
3104         Y = RHS;
3105       }
3106       if (OrICmp == RHS && AndICmp == LHS) {
3107         // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS  --> !Y & X
3108         X = RHS;
3109         Y = LHS;
3110       }
3111       if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
3112         // Invert the predicate of 'Y', thus inverting its output.
3113         Y->setPredicate(Y->getInversePredicate());
3114         // So, are there other uses of Y?
3115         if (!Y->hasOneUse()) {
3116           // We need to adapt other uses of Y though. Get a value that matches
3117           // the original value of Y before inversion. While this increases
3118           // immediate instruction count, we have just ensured that all the
3119           // users are freely-invertible, so that 'not' *will* get folded away.
3120           BuilderTy::InsertPointGuard Guard(Builder);
3121           // Set insertion point to right after the Y.
3122           Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
3123           Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3124           // Replace all uses of Y (excluding the one in NotY!) with NotY.
3125           Worklist.pushUsersToWorkList(*Y);
3126           Y->replaceUsesWithIf(NotY,
3127                                [NotY](Use &U) { return U.getUser() != NotY; });
3128         }
3129         // All done.
3130         return Builder.CreateAnd(LHS, RHS);
3131       }
3132     }
3133   }
3134 
3135   return nullptr;
3136 }
3137 
3138 /// If we have a masked merge, in the canonical form of:
3139 /// (assuming that A only has one use.)
3140 ///   |        A  |  |B|
3141 ///   ((x ^ y) & M) ^ y
3142 ///    |  D  |
3143 /// * If M is inverted:
3144 ///      |  D  |
3145 ///     ((x ^ y) & ~M) ^ y
3146 ///   We can canonicalize by swapping the final xor operand
3147 ///   to eliminate the 'not' of the mask.
3148 ///     ((x ^ y) & M) ^ x
3149 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
3150 ///   because that shortens the dependency chain and improves analysis:
3151 ///     (x & M) | (y & ~M)
3152 static Instruction *visitMaskedMerge(BinaryOperator &I,
3153                                      InstCombiner::BuilderTy &Builder) {
3154   Value *B, *X, *D;
3155   Value *M;
3156   if (!match(&I, m_c_Xor(m_Value(B),
3157                          m_OneUse(m_c_And(
3158                              m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
3159                                           m_Value(D)),
3160                              m_Value(M))))))
3161     return nullptr;
3162 
3163   Value *NotM;
3164   if (match(M, m_Not(m_Value(NotM)))) {
3165     // De-invert the mask and swap the value in B part.
3166     Value *NewA = Builder.CreateAnd(D, NotM);
3167     return BinaryOperator::CreateXor(NewA, X);
3168   }
3169 
3170   Constant *C;
3171   if (D->hasOneUse() && match(M, m_Constant(C))) {
3172     // Propagating undef is unsafe. Clamp undef elements to -1.
3173     Type *EltTy = C->getType()->getScalarType();
3174     C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3175     // Unfold.
3176     Value *LHS = Builder.CreateAnd(X, C);
3177     Value *NotC = Builder.CreateNot(C);
3178     Value *RHS = Builder.CreateAnd(B, NotC);
3179     return BinaryOperator::CreateOr(LHS, RHS);
3180   }
3181 
3182   return nullptr;
3183 }
3184 
3185 // Transform
3186 //   ~(x ^ y)
3187 // into:
3188 //   (~x) ^ y
3189 // or into
3190 //   x ^ (~y)
3191 static Instruction *sinkNotIntoXor(BinaryOperator &I,
3192                                    InstCombiner::BuilderTy &Builder) {
3193   Value *X, *Y;
3194   // FIXME: one-use check is not needed in general, but currently we are unable
3195   // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
3196   if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
3197     return nullptr;
3198 
3199   // We only want to do the transform if it is free to do.
3200   if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
3201     // Ok, good.
3202   } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
3203     std::swap(X, Y);
3204   } else
3205     return nullptr;
3206 
3207   Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
3208   return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
3209 }
3210 
3211 /// Canonicalize a shifty way to code absolute value to the more common pattern
3212 /// that uses negation and select.
3213 static Instruction *canonicalizeAbs(BinaryOperator &Xor,
3214                                     InstCombiner::BuilderTy &Builder) {
3215   assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
3216 
3217   // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
3218   // We're relying on the fact that we only do this transform when the shift has
3219   // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
3220   // instructions).
3221   Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
3222   if (Op0->hasNUses(2))
3223     std::swap(Op0, Op1);
3224 
3225   Type *Ty = Xor.getType();
3226   Value *A;
3227   const APInt *ShAmt;
3228   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
3229       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
3230       match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
3231     // Op1 = ashr i32 A, 31   ; smear the sign bit
3232     // xor (add A, Op1), Op1  ; add -1 and flip bits if negative
3233     // --> (A < 0) ? -A : A
3234     Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
3235     // Copy the nuw/nsw flags from the add to the negate.
3236     auto *Add = cast<BinaryOperator>(Op0);
3237     Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
3238                                    Add->hasNoSignedWrap());
3239     return SelectInst::Create(Cmp, Neg, A);
3240   }
3241   return nullptr;
3242 }
3243 
3244 // Transform
3245 //   z = (~x) &/| y
3246 // into:
3247 //   z = ~(x |/& (~y))
3248 // iff y is free to invert and all uses of z can be freely updated.
3249 bool InstCombinerImpl::sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I) {
3250   Instruction::BinaryOps NewOpc;
3251   switch (I.getOpcode()) {
3252   case Instruction::And:
3253     NewOpc = Instruction::Or;
3254     break;
3255   case Instruction::Or:
3256     NewOpc = Instruction::And;
3257     break;
3258   default:
3259     return false;
3260   };
3261 
3262   Value *X, *Y;
3263   if (!match(&I, m_c_BinOp(m_Not(m_Value(X)), m_Value(Y))))
3264     return false;
3265 
3266   // Will we be able to fold the `not` into Y eventually?
3267   if (!InstCombiner::isFreeToInvert(Y, Y->hasOneUse()))
3268     return false;
3269 
3270   // And can our users be adapted?
3271   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
3272     return false;
3273 
3274   Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3275   Value *NewBinOp =
3276       BinaryOperator::Create(NewOpc, X, NotY, I.getName() + ".not");
3277   Builder.Insert(NewBinOp);
3278   replaceInstUsesWith(I, NewBinOp);
3279   // We can not just create an outer `not`, it will most likely be immediately
3280   // folded back, reconstructing our initial pattern, and causing an
3281   // infinite combine loop, so immediately manually fold it away.
3282   freelyInvertAllUsersOf(NewBinOp);
3283   return true;
3284 }
3285 
3286 Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
3287   Value *NotOp;
3288   if (!match(&I, m_Not(m_Value(NotOp))))
3289     return nullptr;
3290 
3291   // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
3292   // We must eliminate the and/or (one-use) for these transforms to not increase
3293   // the instruction count.
3294   //
3295   // ~(~X & Y) --> (X | ~Y)
3296   // ~(Y & ~X) --> (X | ~Y)
3297   //
3298   // Note: The logical matches do not check for the commuted patterns because
3299   //       those are handled via SimplifySelectsFeedingBinaryOp().
3300   Type *Ty = I.getType();
3301   Value *X, *Y;
3302   if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
3303     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3304     return BinaryOperator::CreateOr(X, NotY);
3305   }
3306   if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
3307     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3308     return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
3309   }
3310 
3311   // ~(~X | Y) --> (X & ~Y)
3312   // ~(Y | ~X) --> (X & ~Y)
3313   if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
3314     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3315     return BinaryOperator::CreateAnd(X, NotY);
3316   }
3317   if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
3318     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
3319     return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
3320   }
3321 
3322   // Is this a 'not' (~) fed by a binary operator?
3323   BinaryOperator *NotVal;
3324   if (match(NotOp, m_BinOp(NotVal))) {
3325     if (NotVal->getOpcode() == Instruction::And ||
3326         NotVal->getOpcode() == Instruction::Or) {
3327       // Apply DeMorgan's Law when inverts are free:
3328       // ~(X & Y) --> (~X | ~Y)
3329       // ~(X | Y) --> (~X & ~Y)
3330       if (isFreeToInvert(NotVal->getOperand(0),
3331                          NotVal->getOperand(0)->hasOneUse()) &&
3332           isFreeToInvert(NotVal->getOperand(1),
3333                          NotVal->getOperand(1)->hasOneUse())) {
3334         Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
3335         Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
3336         if (NotVal->getOpcode() == Instruction::And)
3337           return BinaryOperator::CreateOr(NotX, NotY);
3338         return BinaryOperator::CreateAnd(NotX, NotY);
3339       }
3340     }
3341 
3342     // ~((-X) | Y) --> (X - 1) & (~Y)
3343     if (match(NotVal,
3344               m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
3345       Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
3346       Value *NotY = Builder.CreateNot(Y);
3347       return BinaryOperator::CreateAnd(DecX, NotY);
3348     }
3349 
3350     // ~(~X >>s Y) --> (X >>s Y)
3351     if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
3352       return BinaryOperator::CreateAShr(X, Y);
3353 
3354     // If we are inverting a right-shifted constant, we may be able to eliminate
3355     // the 'not' by inverting the constant and using the opposite shift type.
3356     // Canonicalization rules ensure that only a negative constant uses 'ashr',
3357     // but we must check that in case that transform has not fired yet.
3358 
3359     // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
3360     Constant *C;
3361     if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
3362         match(C, m_Negative())) {
3363       // We matched a negative constant, so propagating undef is unsafe.
3364       // Clamp undef elements to -1.
3365       Type *EltTy = Ty->getScalarType();
3366       C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
3367       return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
3368     }
3369 
3370     // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
3371     if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
3372         match(C, m_NonNegative())) {
3373       // We matched a non-negative constant, so propagating undef is unsafe.
3374       // Clamp undef elements to 0.
3375       Type *EltTy = Ty->getScalarType();
3376       C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
3377       return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
3378     }
3379 
3380     // ~(X + C) --> ~C - X
3381     if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
3382       return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
3383 
3384     // ~(X - Y) --> ~X + Y
3385     // FIXME: is it really beneficial to sink the `not` here?
3386     if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
3387       if (isa<Constant>(X) || NotVal->hasOneUse())
3388         return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
3389 
3390     // ~(~X + Y) --> X - Y
3391     if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
3392       return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
3393                                                    NotVal);
3394   }
3395 
3396   // not (cmp A, B) = !cmp A, B
3397   CmpInst::Predicate Pred;
3398   if (match(NotOp, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
3399     cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
3400     return replaceInstUsesWith(I, NotOp);
3401   }
3402 
3403   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
3404   // ~min(~X, ~Y) --> max(X, Y)
3405   // ~max(~X, Y) --> min(X, ~Y)
3406   auto *II = dyn_cast<IntrinsicInst>(NotOp);
3407   if (II && II->hasOneUse()) {
3408     if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) &&
3409         isFreeToInvert(X, X->hasOneUse()) &&
3410         isFreeToInvert(Y, Y->hasOneUse())) {
3411       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
3412       Value *NotX = Builder.CreateNot(X);
3413       Value *NotY = Builder.CreateNot(Y);
3414       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY);
3415       return replaceInstUsesWith(I, InvMaxMin);
3416     }
3417     if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
3418       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
3419       Value *NotY = Builder.CreateNot(Y);
3420       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
3421       return replaceInstUsesWith(I, InvMaxMin);
3422     }
3423   }
3424 
3425   // TODO: Remove folds if we canonicalize to intrinsics (see above).
3426   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
3427   //
3428   //   %notx = xor i32 %x, -1
3429   //   %cmp1 = icmp sgt i32 %notx, %y
3430   //   %smax = select i1 %cmp1, i32 %notx, i32 %y
3431   //   %res = xor i32 %smax, -1
3432   // =>
3433   //   %noty = xor i32 %y, -1
3434   //   %cmp2 = icmp slt %x, %noty
3435   //   %res = select i1 %cmp2, i32 %x, i32 %noty
3436   //
3437   // Same is applicable for smin/umax/umin.
3438   if (NotOp->hasOneUse()) {
3439     Value *LHS, *RHS;
3440     SelectPatternFlavor SPF = matchSelectPattern(NotOp, LHS, RHS).Flavor;
3441     if (SelectPatternResult::isMinOrMax(SPF)) {
3442       // It's possible we get here before the not has been simplified, so make
3443       // sure the input to the not isn't freely invertible.
3444       if (match(LHS, m_Not(m_Value(X))) && !isFreeToInvert(X, X->hasOneUse())) {
3445         Value *NotY = Builder.CreateNot(RHS);
3446         return SelectInst::Create(
3447             Builder.CreateICmp(getInverseMinMaxPred(SPF), X, NotY), X, NotY);
3448       }
3449 
3450       // It's possible we get here before the not has been simplified, so make
3451       // sure the input to the not isn't freely invertible.
3452       if (match(RHS, m_Not(m_Value(Y))) && !isFreeToInvert(Y, Y->hasOneUse())) {
3453         Value *NotX = Builder.CreateNot(LHS);
3454         return SelectInst::Create(
3455             Builder.CreateICmp(getInverseMinMaxPred(SPF), NotX, Y), NotX, Y);
3456       }
3457 
3458       // If both sides are freely invertible, then we can get rid of the xor
3459       // completely.
3460       if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
3461           isFreeToInvert(RHS, !RHS->hasNUsesOrMore(3))) {
3462         Value *NotLHS = Builder.CreateNot(LHS);
3463         Value *NotRHS = Builder.CreateNot(RHS);
3464         return SelectInst::Create(
3465             Builder.CreateICmp(getInverseMinMaxPred(SPF), NotLHS, NotRHS),
3466             NotLHS, NotRHS);
3467       }
3468     }
3469 
3470     // Pull 'not' into operands of select if both operands are one-use compares
3471     // or one is one-use compare and the other one is a constant.
3472     // Inverting the predicates eliminates the 'not' operation.
3473     // Example:
3474     //   not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
3475     //     select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
3476     //   not (select ?, (cmp TPred, ?, ?), true -->
3477     //     select ?, (cmp InvTPred, ?, ?), false
3478     if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
3479       Value *TV = Sel->getTrueValue();
3480       Value *FV = Sel->getFalseValue();
3481       auto *CmpT = dyn_cast<CmpInst>(TV);
3482       auto *CmpF = dyn_cast<CmpInst>(FV);
3483       bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
3484       bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
3485       if (InvertibleT && InvertibleF) {
3486         if (CmpT)
3487           CmpT->setPredicate(CmpT->getInversePredicate());
3488         else
3489           Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
3490         if (CmpF)
3491           CmpF->setPredicate(CmpF->getInversePredicate());
3492         else
3493           Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
3494         return replaceInstUsesWith(I, Sel);
3495       }
3496     }
3497   }
3498 
3499   if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
3500     return NewXor;
3501 
3502   return nullptr;
3503 }
3504 
3505 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
3506 // here. We should standardize that construct where it is needed or choose some
3507 // other way to ensure that commutated variants of patterns are not missed.
3508 Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
3509   if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1),
3510                                  SQ.getWithInstruction(&I)))
3511     return replaceInstUsesWith(I, V);
3512 
3513   if (SimplifyAssociativeOrCommutative(I))
3514     return &I;
3515 
3516   if (Instruction *X = foldVectorBinop(I))
3517     return X;
3518 
3519   if (Instruction *NewXor = foldXorToXor(I, Builder))
3520     return NewXor;
3521 
3522   // (A&B)^(A&C) -> A&(B^C) etc
3523   if (Value *V = SimplifyUsingDistributiveLaws(I))
3524     return replaceInstUsesWith(I, V);
3525 
3526   // See if we can simplify any instructions used by the instruction whose sole
3527   // purpose is to compute bits we don't care about.
3528   if (SimplifyDemandedInstructionBits(I))
3529     return &I;
3530 
3531   if (Value *V = SimplifyBSwap(I, Builder))
3532     return replaceInstUsesWith(I, V);
3533 
3534   if (Instruction *R = foldNot(I))
3535     return R;
3536 
3537   // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
3538   // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
3539   // calls in there are unnecessary as SimplifyDemandedInstructionBits should
3540   // have already taken care of those cases.
3541   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3542   Value *M;
3543   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
3544                         m_c_And(m_Deferred(M), m_Value()))))
3545     return BinaryOperator::CreateOr(Op0, Op1);
3546 
3547   if (Instruction *Xor = visitMaskedMerge(I, Builder))
3548     return Xor;
3549 
3550   // Use DeMorgan and reassociation to eliminate a 'not' op.
3551   Value *X, *Y;
3552   Constant *C1;
3553   if (match(Op1, m_Constant(C1))) {
3554     Constant *C2;
3555     if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
3556       // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
3557       Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
3558       return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
3559     }
3560     if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
3561       // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
3562       Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
3563       return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
3564     }
3565   }
3566 
3567   Type *Ty = I.getType();
3568   {
3569     const APInt *RHSC;
3570     if (match(Op1, m_APInt(RHSC))) {
3571       Value *X;
3572       const APInt *C;
3573       // (C - X) ^ signmaskC --> (C + signmaskC) - X
3574       if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
3575         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
3576 
3577       // (X + C) ^ signmaskC --> X + (C + signmaskC)
3578       if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
3579         return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
3580 
3581       // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
3582       if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
3583           MaskedValueIsZero(X, *C, 0, &I))
3584         return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
3585 
3586       // If RHSC is inverting the remaining bits of shifted X,
3587       // canonicalize to a 'not' before the shift to help SCEV and codegen:
3588       // (X << C) ^ RHSC --> ~X << C
3589       if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
3590           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
3591         Value *NotX = Builder.CreateNot(X);
3592         return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
3593       }
3594       // (X >>u C) ^ RHSC --> ~X >>u C
3595       if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
3596           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
3597         Value *NotX = Builder.CreateNot(X);
3598         return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
3599       }
3600       // TODO: We could handle 'ashr' here as well. That would be matching
3601       //       a 'not' op and moving it before the shift. Doing that requires
3602       //       preventing the inverse fold in canShiftBinOpWithConstantRHS().
3603     }
3604   }
3605 
3606   // FIXME: This should not be limited to scalar (pull into APInt match above).
3607   {
3608     Value *X;
3609     ConstantInt *C1, *C2, *C3;
3610     // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
3611     if (match(Op1, m_ConstantInt(C3)) &&
3612         match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
3613                           m_ConstantInt(C2))) &&
3614         Op0->hasOneUse()) {
3615       // fold (C1 >> C2) ^ C3
3616       APInt FoldConst = C1->getValue().lshr(C2->getValue());
3617       FoldConst ^= C3->getValue();
3618       // Prepare the two operands.
3619       auto *Opnd0 = cast<Instruction>(Builder.CreateLShr(X, C2));
3620       Opnd0->takeName(cast<Instruction>(Op0));
3621       Opnd0->setDebugLoc(I.getDebugLoc());
3622       return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
3623     }
3624   }
3625 
3626   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
3627     return FoldedLogic;
3628 
3629   // Y ^ (X | Y) --> X & ~Y
3630   // Y ^ (Y | X) --> X & ~Y
3631   if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
3632     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
3633   // (X | Y) ^ Y --> X & ~Y
3634   // (Y | X) ^ Y --> X & ~Y
3635   if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
3636     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
3637 
3638   // Y ^ (X & Y) --> ~X & Y
3639   // Y ^ (Y & X) --> ~X & Y
3640   if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
3641     return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
3642   // (X & Y) ^ Y --> ~X & Y
3643   // (Y & X) ^ Y --> ~X & Y
3644   // Canonical form is (X & C) ^ C; don't touch that.
3645   // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
3646   //       be fixed to prefer that (otherwise we get infinite looping).
3647   if (!match(Op1, m_Constant()) &&
3648       match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
3649     return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
3650 
3651   Value *A, *B, *C;
3652   // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
3653   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
3654                         m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
3655       return BinaryOperator::CreateXor(
3656           Builder.CreateAnd(Builder.CreateNot(A), C), B);
3657 
3658   // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
3659   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
3660                         m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
3661       return BinaryOperator::CreateXor(
3662           Builder.CreateAnd(Builder.CreateNot(B), C), A);
3663 
3664   // (A & B) ^ (A ^ B) -> (A | B)
3665   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
3666       match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
3667     return BinaryOperator::CreateOr(A, B);
3668   // (A ^ B) ^ (A & B) -> (A | B)
3669   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3670       match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
3671     return BinaryOperator::CreateOr(A, B);
3672 
3673   // (A & ~B) ^ ~A -> ~(A & B)
3674   // (~B & A) ^ ~A -> ~(A & B)
3675   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
3676       match(Op1, m_Not(m_Specific(A))))
3677     return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
3678 
3679   // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
3680   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
3681     return BinaryOperator::CreateOr(A, B);
3682 
3683   // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
3684   // TODO: Loosen one-use restriction if common operand is a constant.
3685   Value *D;
3686   if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
3687       match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
3688     if (B == C || B == D)
3689       std::swap(A, B);
3690     if (A == C)
3691       std::swap(C, D);
3692     if (A == D) {
3693       Value *NotA = Builder.CreateNot(A);
3694       return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
3695     }
3696   }
3697 
3698   if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
3699     if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
3700       if (Value *V = foldXorOfICmps(LHS, RHS, I))
3701         return replaceInstUsesWith(I, V);
3702 
3703   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
3704     return CastedXor;
3705 
3706   if (Instruction *Abs = canonicalizeAbs(I, Builder))
3707     return Abs;
3708 
3709   // Otherwise, if all else failed, try to hoist the xor-by-constant:
3710   //   (X ^ C) ^ Y --> (X ^ Y) ^ C
3711   // Just like we do in other places, we completely avoid the fold
3712   // for constantexprs, at least to avoid endless combine loop.
3713   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
3714                                                     m_Unless(m_ConstantExpr())),
3715                                        m_ImmConstant(C1))),
3716                         m_Value(Y))))
3717     return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
3718 
3719   return nullptr;
3720 }
3721