xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp (revision 5deeebd8c6ca991269e72902a7a62cada57947f6)
10b57cec5SDimitry Andric //===- InstCombineAndOrXor.cpp --------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the visitAnd, visitOr, and visitXor functions.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "InstCombineInternal.h"
140b57cec5SDimitry Andric #include "llvm/Analysis/CmpInstAnalysis.h"
150b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
160b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
170b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
180b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
19e8d8bef9SDimitry Andric #include "llvm/Transforms/InstCombine/InstCombiner.h"
20e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
21e8d8bef9SDimitry Andric 
220b57cec5SDimitry Andric using namespace llvm;
230b57cec5SDimitry Andric using namespace PatternMatch;
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric #define DEBUG_TYPE "instcombine"
260b57cec5SDimitry Andric 
270b57cec5SDimitry Andric /// This is the complement of getICmpCode, which turns an opcode and two
280b57cec5SDimitry Andric /// operands into either a constant true or false, or a brand new ICmp
290b57cec5SDimitry Andric /// instruction. The sign is passed in to determine which kind of predicate to
300b57cec5SDimitry Andric /// use in the new icmp instruction.
310b57cec5SDimitry Andric static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
320b57cec5SDimitry Andric                               InstCombiner::BuilderTy &Builder) {
330b57cec5SDimitry Andric   ICmpInst::Predicate NewPred;
340b57cec5SDimitry Andric   if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
350b57cec5SDimitry Andric     return TorF;
360b57cec5SDimitry Andric   return Builder.CreateICmp(NewPred, LHS, RHS);
370b57cec5SDimitry Andric }
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric /// This is the complement of getFCmpCode, which turns an opcode and two
400b57cec5SDimitry Andric /// operands into either a FCmp instruction, or a true/false constant.
410b57cec5SDimitry Andric static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
420b57cec5SDimitry Andric                            InstCombiner::BuilderTy &Builder) {
4381ad6265SDimitry Andric   FCmpInst::Predicate NewPred;
4481ad6265SDimitry Andric   if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
4581ad6265SDimitry Andric     return TorF;
4681ad6265SDimitry Andric   return Builder.CreateFCmp(NewPred, LHS, RHS);
470b57cec5SDimitry Andric }
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
508bcb0991SDimitry Andric /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates
510b57cec5SDimitry Andric /// whether to treat V, Lo, and Hi as signed or not.
52e8d8bef9SDimitry Andric Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
53e8d8bef9SDimitry Andric                                          const APInt &Hi, bool isSigned,
54e8d8bef9SDimitry Andric                                          bool Inside) {
558bcb0991SDimitry Andric   assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
568bcb0991SDimitry Andric          "Lo is not < Hi in range emission code!");
570b57cec5SDimitry Andric 
580b57cec5SDimitry Andric   Type *Ty = V->getType();
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric   // V >= Min && V <  Hi --> V <  Hi
610b57cec5SDimitry Andric   // V <  Min || V >= Hi --> V >= Hi
620b57cec5SDimitry Andric   ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
630b57cec5SDimitry Andric   if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
640b57cec5SDimitry Andric     Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
650b57cec5SDimitry Andric     return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
660b57cec5SDimitry Andric   }
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   // V >= Lo && V <  Hi --> V - Lo u<  Hi - Lo
690b57cec5SDimitry Andric   // V <  Lo || V >= Hi --> V - Lo u>= Hi - Lo
700b57cec5SDimitry Andric   Value *VMinusLo =
710b57cec5SDimitry Andric       Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
720b57cec5SDimitry Andric   Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
730b57cec5SDimitry Andric   return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
740b57cec5SDimitry Andric }
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
770b57cec5SDimitry Andric /// that can be simplified.
780b57cec5SDimitry Andric /// One of A and B is considered the mask. The other is the value. This is
790b57cec5SDimitry Andric /// described as the "AMask" or "BMask" part of the enum. If the enum contains
800b57cec5SDimitry Andric /// only "Mask", then both A and B can be considered masks. If A is the mask,
810b57cec5SDimitry Andric /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
820b57cec5SDimitry Andric /// If both A and C are constants, this proof is also easy.
830b57cec5SDimitry Andric /// For the following explanations, we assume that A is the mask.
840b57cec5SDimitry Andric ///
850b57cec5SDimitry Andric /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
860b57cec5SDimitry Andric /// bits of A are set in B.
870b57cec5SDimitry Andric ///   Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
880b57cec5SDimitry Andric ///
890b57cec5SDimitry Andric /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
900b57cec5SDimitry Andric /// bits of A are cleared in B.
910b57cec5SDimitry Andric ///   Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
920b57cec5SDimitry Andric ///
930b57cec5SDimitry Andric /// "Mixed" declares that (A & B) == C and C might or might not contain any
940b57cec5SDimitry Andric /// number of one bits and zero bits.
950b57cec5SDimitry Andric ///   Example: (icmp eq (A & 3), 1) -> AMask_Mixed
960b57cec5SDimitry Andric ///
970b57cec5SDimitry Andric /// "Not" means that in above descriptions "==" should be replaced by "!=".
980b57cec5SDimitry Andric ///   Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
990b57cec5SDimitry Andric ///
1000b57cec5SDimitry Andric /// If the mask A contains a single bit, then the following is equivalent:
1010b57cec5SDimitry Andric ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
1020b57cec5SDimitry Andric ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
1030b57cec5SDimitry Andric enum MaskedICmpType {
1040b57cec5SDimitry Andric   AMask_AllOnes           =     1,
1050b57cec5SDimitry Andric   AMask_NotAllOnes        =     2,
1060b57cec5SDimitry Andric   BMask_AllOnes           =     4,
1070b57cec5SDimitry Andric   BMask_NotAllOnes        =     8,
1080b57cec5SDimitry Andric   Mask_AllZeros           =    16,
1090b57cec5SDimitry Andric   Mask_NotAllZeros        =    32,
1100b57cec5SDimitry Andric   AMask_Mixed             =    64,
1110b57cec5SDimitry Andric   AMask_NotMixed          =   128,
1120b57cec5SDimitry Andric   BMask_Mixed             =   256,
1130b57cec5SDimitry Andric   BMask_NotMixed          =   512
1140b57cec5SDimitry Andric };
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
1170b57cec5SDimitry Andric /// satisfies.
1180b57cec5SDimitry Andric static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
1190b57cec5SDimitry Andric                                   ICmpInst::Predicate Pred) {
120349cc55cSDimitry Andric   const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
121349cc55cSDimitry Andric   match(A, m_APInt(ConstA));
122349cc55cSDimitry Andric   match(B, m_APInt(ConstB));
123349cc55cSDimitry Andric   match(C, m_APInt(ConstC));
1240b57cec5SDimitry Andric   bool IsEq = (Pred == ICmpInst::ICMP_EQ);
125349cc55cSDimitry Andric   bool IsAPow2 = ConstA && ConstA->isPowerOf2();
126349cc55cSDimitry Andric   bool IsBPow2 = ConstB && ConstB->isPowerOf2();
1270b57cec5SDimitry Andric   unsigned MaskVal = 0;
128349cc55cSDimitry Andric   if (ConstC && ConstC->isZero()) {
1290b57cec5SDimitry Andric     // if C is zero, then both A and B qualify as mask
1300b57cec5SDimitry Andric     MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
1310b57cec5SDimitry Andric                      : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
1320b57cec5SDimitry Andric     if (IsAPow2)
1330b57cec5SDimitry Andric       MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
1340b57cec5SDimitry Andric                        : (AMask_AllOnes | AMask_Mixed));
1350b57cec5SDimitry Andric     if (IsBPow2)
1360b57cec5SDimitry Andric       MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
1370b57cec5SDimitry Andric                        : (BMask_AllOnes | BMask_Mixed));
1380b57cec5SDimitry Andric     return MaskVal;
1390b57cec5SDimitry Andric   }
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   if (A == C) {
1420b57cec5SDimitry Andric     MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
1430b57cec5SDimitry Andric                      : (AMask_NotAllOnes | AMask_NotMixed));
1440b57cec5SDimitry Andric     if (IsAPow2)
1450b57cec5SDimitry Andric       MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
1460b57cec5SDimitry Andric                        : (Mask_AllZeros | AMask_Mixed));
147349cc55cSDimitry Andric   } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
1480b57cec5SDimitry Andric     MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
1490b57cec5SDimitry Andric   }
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric   if (B == C) {
1520b57cec5SDimitry Andric     MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
1530b57cec5SDimitry Andric                      : (BMask_NotAllOnes | BMask_NotMixed));
1540b57cec5SDimitry Andric     if (IsBPow2)
1550b57cec5SDimitry Andric       MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
1560b57cec5SDimitry Andric                        : (Mask_AllZeros | BMask_Mixed));
157349cc55cSDimitry Andric   } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
1580b57cec5SDimitry Andric     MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   return MaskVal;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric /// Convert an analysis of a masked ICmp into its equivalent if all boolean
1650b57cec5SDimitry Andric /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
1660b57cec5SDimitry Andric /// is adjacent to the corresponding normal flag (recording ==), this just
1670b57cec5SDimitry Andric /// involves swapping those bits over.
1680b57cec5SDimitry Andric static unsigned conjugateICmpMask(unsigned Mask) {
1690b57cec5SDimitry Andric   unsigned NewMask;
1700b57cec5SDimitry Andric   NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
1710b57cec5SDimitry Andric                      AMask_Mixed | BMask_Mixed))
1720b57cec5SDimitry Andric             << 1;
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
1750b57cec5SDimitry Andric                       AMask_NotMixed | BMask_NotMixed))
1760b57cec5SDimitry Andric              >> 1;
1770b57cec5SDimitry Andric 
1780b57cec5SDimitry Andric   return NewMask;
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric // Adapts the external decomposeBitTestICmp for local use.
1820b57cec5SDimitry Andric static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
1830b57cec5SDimitry Andric                                  Value *&X, Value *&Y, Value *&Z) {
1840b57cec5SDimitry Andric   APInt Mask;
1850b57cec5SDimitry Andric   if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
1860b57cec5SDimitry Andric     return false;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   Y = ConstantInt::get(X->getType(), Mask);
1890b57cec5SDimitry Andric   Z = ConstantInt::get(X->getType(), 0);
1900b57cec5SDimitry Andric   return true;
1910b57cec5SDimitry Andric }
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
1940b57cec5SDimitry Andric /// Return the pattern classes (from MaskedICmpType) for the left hand side and
1950b57cec5SDimitry Andric /// the right hand side as a pair.
1960b57cec5SDimitry Andric /// LHS and RHS are the left hand side and the right hand side ICmps and PredL
1970b57cec5SDimitry Andric /// and PredR are their predicates, respectively.
198bdd1243dSDimitry Andric static std::optional<std::pair<unsigned, unsigned>> getMaskedTypeForICmpPair(
199bdd1243dSDimitry Andric     Value *&A, Value *&B, Value *&C, Value *&D, Value *&E, ICmpInst *LHS,
200bdd1243dSDimitry Andric     ICmpInst *RHS, ICmpInst::Predicate &PredL, ICmpInst::Predicate &PredR) {
201349cc55cSDimitry Andric   // Don't allow pointers. Splat vectors are fine.
202349cc55cSDimitry Andric   if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
203349cc55cSDimitry Andric       !RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
204bdd1243dSDimitry Andric     return std::nullopt;
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   // Here comes the tricky part:
2070b57cec5SDimitry Andric   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
2080b57cec5SDimitry Andric   // and L11 & L12 == L21 & L22. The same goes for RHS.
2090b57cec5SDimitry Andric   // Now we must find those components L** and R**, that are equal, so
2100b57cec5SDimitry Andric   // that we can extract the parameters A, B, C, D, and E for the canonical
2110b57cec5SDimitry Andric   // above.
2120b57cec5SDimitry Andric   Value *L1 = LHS->getOperand(0);
2130b57cec5SDimitry Andric   Value *L2 = LHS->getOperand(1);
2140b57cec5SDimitry Andric   Value *L11, *L12, *L21, *L22;
2150b57cec5SDimitry Andric   // Check whether the icmp can be decomposed into a bit test.
2160b57cec5SDimitry Andric   if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
2170b57cec5SDimitry Andric     L21 = L22 = L1 = nullptr;
2180b57cec5SDimitry Andric   } else {
2190b57cec5SDimitry Andric     // Look for ANDs in the LHS icmp.
2200b57cec5SDimitry Andric     if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
2210b57cec5SDimitry Andric       // Any icmp can be viewed as being trivially masked; if it allows us to
2220b57cec5SDimitry Andric       // remove one, it's worth it.
2230b57cec5SDimitry Andric       L11 = L1;
2240b57cec5SDimitry Andric       L12 = Constant::getAllOnesValue(L1->getType());
2250b57cec5SDimitry Andric     }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
2280b57cec5SDimitry Andric       L21 = L2;
2290b57cec5SDimitry Andric       L22 = Constant::getAllOnesValue(L2->getType());
2300b57cec5SDimitry Andric     }
2310b57cec5SDimitry Andric   }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   // Bail if LHS was a icmp that can't be decomposed into an equality.
2340b57cec5SDimitry Andric   if (!ICmpInst::isEquality(PredL))
235bdd1243dSDimitry Andric     return std::nullopt;
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   Value *R1 = RHS->getOperand(0);
2380b57cec5SDimitry Andric   Value *R2 = RHS->getOperand(1);
2390b57cec5SDimitry Andric   Value *R11, *R12;
2400b57cec5SDimitry Andric   bool Ok = false;
2410b57cec5SDimitry Andric   if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
2420b57cec5SDimitry Andric     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
2430b57cec5SDimitry Andric       A = R11;
2440b57cec5SDimitry Andric       D = R12;
2450b57cec5SDimitry Andric     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
2460b57cec5SDimitry Andric       A = R12;
2470b57cec5SDimitry Andric       D = R11;
2480b57cec5SDimitry Andric     } else {
249bdd1243dSDimitry Andric       return std::nullopt;
2500b57cec5SDimitry Andric     }
2510b57cec5SDimitry Andric     E = R2;
2520b57cec5SDimitry Andric     R1 = nullptr;
2530b57cec5SDimitry Andric     Ok = true;
2540b57cec5SDimitry Andric   } else {
2550b57cec5SDimitry Andric     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
2560b57cec5SDimitry Andric       // As before, model no mask as a trivial mask if it'll let us do an
2570b57cec5SDimitry Andric       // optimization.
2580b57cec5SDimitry Andric       R11 = R1;
2590b57cec5SDimitry Andric       R12 = Constant::getAllOnesValue(R1->getType());
2600b57cec5SDimitry Andric     }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
2630b57cec5SDimitry Andric       A = R11;
2640b57cec5SDimitry Andric       D = R12;
2650b57cec5SDimitry Andric       E = R2;
2660b57cec5SDimitry Andric       Ok = true;
2670b57cec5SDimitry Andric     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
2680b57cec5SDimitry Andric       A = R12;
2690b57cec5SDimitry Andric       D = R11;
2700b57cec5SDimitry Andric       E = R2;
2710b57cec5SDimitry Andric       Ok = true;
2720b57cec5SDimitry Andric     }
2730b57cec5SDimitry Andric   }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric   // Bail if RHS was a icmp that can't be decomposed into an equality.
2760b57cec5SDimitry Andric   if (!ICmpInst::isEquality(PredR))
277bdd1243dSDimitry Andric     return std::nullopt;
2780b57cec5SDimitry Andric 
2790b57cec5SDimitry Andric   // Look for ANDs on the right side of the RHS icmp.
2800b57cec5SDimitry Andric   if (!Ok) {
2810b57cec5SDimitry Andric     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
2820b57cec5SDimitry Andric       R11 = R2;
2830b57cec5SDimitry Andric       R12 = Constant::getAllOnesValue(R2->getType());
2840b57cec5SDimitry Andric     }
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
2870b57cec5SDimitry Andric       A = R11;
2880b57cec5SDimitry Andric       D = R12;
2890b57cec5SDimitry Andric       E = R1;
2900b57cec5SDimitry Andric       Ok = true;
2910b57cec5SDimitry Andric     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
2920b57cec5SDimitry Andric       A = R12;
2930b57cec5SDimitry Andric       D = R11;
2940b57cec5SDimitry Andric       E = R1;
2950b57cec5SDimitry Andric       Ok = true;
2960b57cec5SDimitry Andric     } else {
297bdd1243dSDimitry Andric       return std::nullopt;
2980b57cec5SDimitry Andric     }
299349cc55cSDimitry Andric 
300349cc55cSDimitry Andric     assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
3010b57cec5SDimitry Andric   }
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   if (L11 == A) {
3040b57cec5SDimitry Andric     B = L12;
3050b57cec5SDimitry Andric     C = L2;
3060b57cec5SDimitry Andric   } else if (L12 == A) {
3070b57cec5SDimitry Andric     B = L11;
3080b57cec5SDimitry Andric     C = L2;
3090b57cec5SDimitry Andric   } else if (L21 == A) {
3100b57cec5SDimitry Andric     B = L22;
3110b57cec5SDimitry Andric     C = L1;
3120b57cec5SDimitry Andric   } else if (L22 == A) {
3130b57cec5SDimitry Andric     B = L21;
3140b57cec5SDimitry Andric     C = L1;
3150b57cec5SDimitry Andric   }
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric   unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
3180b57cec5SDimitry Andric   unsigned RightType = getMaskedICmpType(A, D, E, PredR);
319bdd1243dSDimitry Andric   return std::optional<std::pair<unsigned, unsigned>>(
320bdd1243dSDimitry Andric       std::make_pair(LeftType, RightType));
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single
3240b57cec5SDimitry Andric /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros
3250b57cec5SDimitry Andric /// and the right hand side is of type BMask_Mixed. For example,
3260b57cec5SDimitry Andric /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8).
32781ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
3280b57cec5SDimitry Andric static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
329e8d8bef9SDimitry Andric     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
330e8d8bef9SDimitry Andric     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
331e8d8bef9SDimitry Andric     InstCombiner::BuilderTy &Builder) {
3320b57cec5SDimitry Andric   // We are given the canonical form:
3330b57cec5SDimitry Andric   //   (icmp ne (A & B), 0) & (icmp eq (A & D), E).
3340b57cec5SDimitry Andric   // where D & E == E.
3350b57cec5SDimitry Andric   //
3360b57cec5SDimitry Andric   // If IsAnd is false, we get it in negated form:
3370b57cec5SDimitry Andric   //   (icmp eq (A & B), 0) | (icmp ne (A & D), E) ->
3380b57cec5SDimitry Andric   //      !((icmp ne (A & B), 0) & (icmp eq (A & D), E)).
3390b57cec5SDimitry Andric   //
3400b57cec5SDimitry Andric   // We currently handle the case of B, C, D, E are constant.
3410b57cec5SDimitry Andric   //
34281ad6265SDimitry Andric   const APInt *BCst, *CCst, *DCst, *OrigECst;
34381ad6265SDimitry Andric   if (!match(B, m_APInt(BCst)) || !match(C, m_APInt(CCst)) ||
34481ad6265SDimitry Andric       !match(D, m_APInt(DCst)) || !match(E, m_APInt(OrigECst)))
3450b57cec5SDimitry Andric     return nullptr;
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // Update E to the canonical form when D is a power of two and RHS is
3500b57cec5SDimitry Andric   // canonicalized as,
3510b57cec5SDimitry Andric   // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or
3520b57cec5SDimitry Andric   // (icmp ne (A & D), D) -> (icmp eq (A & D), 0).
35381ad6265SDimitry Andric   APInt ECst = *OrigECst;
3540b57cec5SDimitry Andric   if (PredR != NewCC)
35581ad6265SDimitry Andric     ECst ^= *DCst;
3560b57cec5SDimitry Andric 
3570b57cec5SDimitry Andric   // If B or D is zero, skip because if LHS or RHS can be trivially folded by
3580b57cec5SDimitry Andric   // other folding rules and this pattern won't apply any more.
35981ad6265SDimitry Andric   if (*BCst == 0 || *DCst == 0)
3600b57cec5SDimitry Andric     return nullptr;
3610b57cec5SDimitry Andric 
3620b57cec5SDimitry Andric   // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't
3630b57cec5SDimitry Andric   // deduce anything from it.
3640b57cec5SDimitry Andric   // For example,
3650b57cec5SDimitry Andric   // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding.
36681ad6265SDimitry Andric   if ((*BCst & *DCst) == 0)
3670b57cec5SDimitry Andric     return nullptr;
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   // If the following two conditions are met:
3700b57cec5SDimitry Andric   //
3710b57cec5SDimitry Andric   // 1. mask B covers only a single bit that's not covered by mask D, that is,
3720b57cec5SDimitry Andric   // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of
3730b57cec5SDimitry Andric   // B and D has only one bit set) and,
3740b57cec5SDimitry Andric   //
3750b57cec5SDimitry Andric   // 2. RHS (and E) indicates that the rest of B's bits are zero (in other
3760b57cec5SDimitry Andric   // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0
3770b57cec5SDimitry Andric   //
3780b57cec5SDimitry Andric   // then that single bit in B must be one and thus the whole expression can be
3790b57cec5SDimitry Andric   // folded to
3800b57cec5SDimitry Andric   //   (A & (B | D)) == (B & (B ^ D)) | E.
3810b57cec5SDimitry Andric   //
3820b57cec5SDimitry Andric   // For example,
3830b57cec5SDimitry Andric   // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9)
3840b57cec5SDimitry Andric   // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8)
38581ad6265SDimitry Andric   if ((((*BCst & *DCst) & ECst) == 0) &&
38681ad6265SDimitry Andric       (*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
38781ad6265SDimitry Andric     APInt BorD = *BCst | *DCst;
38881ad6265SDimitry Andric     APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
38981ad6265SDimitry Andric     Value *NewMask = ConstantInt::get(A->getType(), BorD);
39081ad6265SDimitry Andric     Value *NewMaskedValue = ConstantInt::get(A->getType(), BandBxorDorE);
3910b57cec5SDimitry Andric     Value *NewAnd = Builder.CreateAnd(A, NewMask);
3920b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
3930b57cec5SDimitry Andric   }
3940b57cec5SDimitry Andric 
39581ad6265SDimitry Andric   auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
39681ad6265SDimitry Andric     return (*C1 & *C2) == *C1;
3970b57cec5SDimitry Andric   };
39881ad6265SDimitry Andric   auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
39981ad6265SDimitry Andric     return (*C1 & *C2) == *C2;
4000b57cec5SDimitry Andric   };
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric   // In the following, we consider only the cases where B is a superset of D, B
4030b57cec5SDimitry Andric   // is a subset of D, or B == D because otherwise there's at least one bit
4040b57cec5SDimitry Andric   // covered by B but not D, in which case we can't deduce much from it, so
4050b57cec5SDimitry Andric   // no folding (aside from the single must-be-one bit case right above.)
4060b57cec5SDimitry Andric   // For example,
4070b57cec5SDimitry Andric   // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding.
4080b57cec5SDimitry Andric   if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
4090b57cec5SDimitry Andric     return nullptr;
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric   // At this point, either B is a superset of D, B is a subset of D or B == D.
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict
4140b57cec5SDimitry Andric   // and the whole expression becomes false (or true if negated), otherwise, no
4150b57cec5SDimitry Andric   // folding.
4160b57cec5SDimitry Andric   // For example,
4170b57cec5SDimitry Andric   // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false.
4180b57cec5SDimitry Andric   // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding.
41981ad6265SDimitry Andric   if (ECst.isZero()) {
4200b57cec5SDimitry Andric     if (IsSubSetOrEqual(BCst, DCst))
4210b57cec5SDimitry Andric       return ConstantInt::get(LHS->getType(), !IsAnd);
4220b57cec5SDimitry Andric     return nullptr;
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B ==
4260b57cec5SDimitry Andric   // D. If B is a superset of (or equal to) D, since E is not zero, LHS is
4270b57cec5SDimitry Andric   // subsumed by RHS (RHS implies LHS.) So the whole expression becomes
4280b57cec5SDimitry Andric   // RHS. For example,
4290b57cec5SDimitry Andric   // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
4300b57cec5SDimitry Andric   // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
4310b57cec5SDimitry Andric   if (IsSuperSetOrEqual(BCst, DCst))
4320b57cec5SDimitry Andric     return RHS;
4330b57cec5SDimitry Andric   // Otherwise, B is a subset of D. If B and E have a common bit set,
4340b57cec5SDimitry Andric   // ie. (B & E) != 0, then LHS is subsumed by RHS. For example.
4350b57cec5SDimitry Andric   // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8).
4360b57cec5SDimitry Andric   assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
43781ad6265SDimitry Andric   if ((*BCst & ECst) != 0)
4380b57cec5SDimitry Andric     return RHS;
4390b57cec5SDimitry Andric   // Otherwise, LHS and RHS contradict and the whole expression becomes false
4400b57cec5SDimitry Andric   // (or true if negated.) For example,
4410b57cec5SDimitry Andric   // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false.
4420b57cec5SDimitry Andric   // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false.
4430b57cec5SDimitry Andric   return ConstantInt::get(LHS->getType(), !IsAnd);
4440b57cec5SDimitry Andric }
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single
4470b57cec5SDimitry Andric /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side
4480b57cec5SDimitry Andric /// aren't of the common mask pattern type.
44981ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
4500b57cec5SDimitry Andric static Value *foldLogOpOfMaskedICmpsAsymmetric(
451e8d8bef9SDimitry Andric     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
452e8d8bef9SDimitry Andric     Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
453e8d8bef9SDimitry Andric     unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
4540b57cec5SDimitry Andric   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
4550b57cec5SDimitry Andric          "Expected equality predicates for masked type of icmps.");
4560b57cec5SDimitry Andric   // Handle Mask_NotAllZeros-BMask_Mixed cases.
4570b57cec5SDimitry Andric   // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or
4580b57cec5SDimitry Andric   // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E)
4590b57cec5SDimitry Andric   //    which gets swapped to
4600b57cec5SDimitry Andric   //    (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C).
4610b57cec5SDimitry Andric   if (!IsAnd) {
4620b57cec5SDimitry Andric     LHSMask = conjugateICmpMask(LHSMask);
4630b57cec5SDimitry Andric     RHSMask = conjugateICmpMask(RHSMask);
4640b57cec5SDimitry Andric   }
4650b57cec5SDimitry Andric   if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
4660b57cec5SDimitry Andric     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
4670b57cec5SDimitry Andric             LHS, RHS, IsAnd, A, B, C, D, E,
4680b57cec5SDimitry Andric             PredL, PredR, Builder)) {
4690b57cec5SDimitry Andric       return V;
4700b57cec5SDimitry Andric     }
4710b57cec5SDimitry Andric   } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
4720b57cec5SDimitry Andric     if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
4730b57cec5SDimitry Andric             RHS, LHS, IsAnd, A, D, E, B, C,
4740b57cec5SDimitry Andric             PredR, PredL, Builder)) {
4750b57cec5SDimitry Andric       return V;
4760b57cec5SDimitry Andric     }
4770b57cec5SDimitry Andric   }
4780b57cec5SDimitry Andric   return nullptr;
4790b57cec5SDimitry Andric }
4800b57cec5SDimitry Andric 
4810b57cec5SDimitry Andric /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
4820b57cec5SDimitry Andric /// into a single (icmp(A & X) ==/!= Y).
4830b57cec5SDimitry Andric static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
48481ad6265SDimitry Andric                                      bool IsLogical,
485e8d8bef9SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
4860b57cec5SDimitry Andric   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
4870b57cec5SDimitry Andric   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
488bdd1243dSDimitry Andric   std::optional<std::pair<unsigned, unsigned>> MaskPair =
4890b57cec5SDimitry Andric       getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
4900b57cec5SDimitry Andric   if (!MaskPair)
4910b57cec5SDimitry Andric     return nullptr;
4920b57cec5SDimitry Andric   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
4930b57cec5SDimitry Andric          "Expected equality predicates for masked type of icmps.");
4940b57cec5SDimitry Andric   unsigned LHSMask = MaskPair->first;
4950b57cec5SDimitry Andric   unsigned RHSMask = MaskPair->second;
4960b57cec5SDimitry Andric   unsigned Mask = LHSMask & RHSMask;
4970b57cec5SDimitry Andric   if (Mask == 0) {
4980b57cec5SDimitry Andric     // Even if the two sides don't share a common pattern, check if folding can
4990b57cec5SDimitry Andric     // still happen.
5000b57cec5SDimitry Andric     if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
5010b57cec5SDimitry Andric             LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
5020b57cec5SDimitry Andric             Builder))
5030b57cec5SDimitry Andric       return V;
5040b57cec5SDimitry Andric     return nullptr;
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   // In full generality:
5080b57cec5SDimitry Andric   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
5090b57cec5SDimitry Andric   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
5100b57cec5SDimitry Andric   //
5110b57cec5SDimitry Andric   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
5120b57cec5SDimitry Andric   // equivalent to (icmp (A & X) !Op Y).
5130b57cec5SDimitry Andric   //
5140b57cec5SDimitry Andric   // Therefore, we can pretend for the rest of this function that we're dealing
5150b57cec5SDimitry Andric   // with the conjunction, provided we flip the sense of any comparisons (both
5160b57cec5SDimitry Andric   // input and output).
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // In most cases we're going to produce an EQ for the "&&" case.
5190b57cec5SDimitry Andric   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
5200b57cec5SDimitry Andric   if (!IsAnd) {
5210b57cec5SDimitry Andric     // Convert the masking analysis into its equivalent with negated
5220b57cec5SDimitry Andric     // comparisons.
5230b57cec5SDimitry Andric     Mask = conjugateICmpMask(Mask);
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   if (Mask & Mask_AllZeros) {
5270b57cec5SDimitry Andric     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
5280b57cec5SDimitry Andric     // -> (icmp eq (A & (B|D)), 0)
52981ad6265SDimitry Andric     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
53081ad6265SDimitry Andric       return nullptr; // TODO: Use freeze?
5310b57cec5SDimitry Andric     Value *NewOr = Builder.CreateOr(B, D);
5320b57cec5SDimitry Andric     Value *NewAnd = Builder.CreateAnd(A, NewOr);
5330b57cec5SDimitry Andric     // We can't use C as zero because we might actually handle
5340b57cec5SDimitry Andric     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
5350b57cec5SDimitry Andric     // with B and D, having a single bit set.
5360b57cec5SDimitry Andric     Value *Zero = Constant::getNullValue(A->getType());
5370b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd, Zero);
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric   if (Mask & BMask_AllOnes) {
5400b57cec5SDimitry Andric     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
5410b57cec5SDimitry Andric     // -> (icmp eq (A & (B|D)), (B|D))
54281ad6265SDimitry Andric     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
54381ad6265SDimitry Andric       return nullptr; // TODO: Use freeze?
5440b57cec5SDimitry Andric     Value *NewOr = Builder.CreateOr(B, D);
5450b57cec5SDimitry Andric     Value *NewAnd = Builder.CreateAnd(A, NewOr);
5460b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd, NewOr);
5470b57cec5SDimitry Andric   }
5480b57cec5SDimitry Andric   if (Mask & AMask_AllOnes) {
5490b57cec5SDimitry Andric     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
5500b57cec5SDimitry Andric     // -> (icmp eq (A & (B&D)), A)
55181ad6265SDimitry Andric     if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
55281ad6265SDimitry Andric       return nullptr; // TODO: Use freeze?
5530b57cec5SDimitry Andric     Value *NewAnd1 = Builder.CreateAnd(B, D);
5540b57cec5SDimitry Andric     Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
5550b57cec5SDimitry Andric     return Builder.CreateICmp(NewCC, NewAnd2, A);
5560b57cec5SDimitry Andric   }
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   // Remaining cases assume at least that B and D are constant, and depend on
5590b57cec5SDimitry Andric   // their actual values. This isn't strictly necessary, just a "handle the
5600b57cec5SDimitry Andric   // easy cases for now" decision.
561349cc55cSDimitry Andric   const APInt *ConstB, *ConstD;
562349cc55cSDimitry Andric   if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
5630b57cec5SDimitry Andric     return nullptr;
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
5660b57cec5SDimitry Andric     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
5670b57cec5SDimitry Andric     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
5680b57cec5SDimitry Andric     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
5690b57cec5SDimitry Andric     // Only valid if one of the masks is a superset of the other (check "B&D" is
5700b57cec5SDimitry Andric     // the same as either B or D).
571349cc55cSDimitry Andric     APInt NewMask = *ConstB & *ConstD;
572349cc55cSDimitry Andric     if (NewMask == *ConstB)
5730b57cec5SDimitry Andric       return LHS;
574349cc55cSDimitry Andric     else if (NewMask == *ConstD)
5750b57cec5SDimitry Andric       return RHS;
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   if (Mask & AMask_NotAllOnes) {
5790b57cec5SDimitry Andric     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
5800b57cec5SDimitry Andric     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
5810b57cec5SDimitry Andric     // Only valid if one of the masks is a superset of the other (check "B|D" is
5820b57cec5SDimitry Andric     // the same as either B or D).
583349cc55cSDimitry Andric     APInt NewMask = *ConstB | *ConstD;
584349cc55cSDimitry Andric     if (NewMask == *ConstB)
5850b57cec5SDimitry Andric       return LHS;
586349cc55cSDimitry Andric     else if (NewMask == *ConstD)
5870b57cec5SDimitry Andric       return RHS;
5880b57cec5SDimitry Andric   }
5890b57cec5SDimitry Andric 
59006c3fb27SDimitry Andric   if (Mask & (BMask_Mixed | BMask_NotMixed)) {
59106c3fb27SDimitry Andric     // Mixed:
5920b57cec5SDimitry Andric     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
5930b57cec5SDimitry Andric     // We already know that B & C == C && D & E == E.
5940b57cec5SDimitry Andric     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
5950b57cec5SDimitry Andric     // C and E, which are shared by both the mask B and the mask D, don't
5960b57cec5SDimitry Andric     // contradict, then we can transform to
5970b57cec5SDimitry Andric     // -> (icmp eq (A & (B|D)), (C|E))
5980b57cec5SDimitry Andric     // Currently, we only handle the case of B, C, D, and E being constant.
5990b57cec5SDimitry Andric     // We can't simply use C and E because we might actually handle
6000b57cec5SDimitry Andric     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
6010b57cec5SDimitry Andric     // with B and D, having a single bit set.
60206c3fb27SDimitry Andric 
60306c3fb27SDimitry Andric     // NotMixed:
60406c3fb27SDimitry Andric     // (icmp ne (A & B), C) & (icmp ne (A & D), E)
60506c3fb27SDimitry Andric     // -> (icmp ne (A & (B & D)), (C & E))
60606c3fb27SDimitry Andric     // Check the intersection (B & D) for inequality.
60706c3fb27SDimitry Andric     // Assume that (B & D) == B || (B & D) == D, i.e B/D is a subset of D/B
60806c3fb27SDimitry Andric     // and (B & D) & (C ^ E) == 0, bits of C and E, which are shared by both the
60906c3fb27SDimitry Andric     // B and the D, don't contradict.
61006c3fb27SDimitry Andric     // Note that we can assume (~B & C) == 0 && (~D & E) == 0, previous
61106c3fb27SDimitry Andric     // operation should delete these icmps if it hadn't been met.
61206c3fb27SDimitry Andric 
613349cc55cSDimitry Andric     const APInt *OldConstC, *OldConstE;
614349cc55cSDimitry Andric     if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
6150b57cec5SDimitry Andric       return nullptr;
616349cc55cSDimitry Andric 
61706c3fb27SDimitry Andric     auto FoldBMixed = [&](ICmpInst::Predicate CC, bool IsNot) -> Value * {
61806c3fb27SDimitry Andric       CC = IsNot ? CmpInst::getInversePredicate(CC) : CC;
61906c3fb27SDimitry Andric       const APInt ConstC = PredL != CC ? *ConstB ^ *OldConstC : *OldConstC;
62006c3fb27SDimitry Andric       const APInt ConstE = PredR != CC ? *ConstD ^ *OldConstE : *OldConstE;
6210b57cec5SDimitry Andric 
622349cc55cSDimitry Andric       if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
62306c3fb27SDimitry Andric         return IsNot ? nullptr : ConstantInt::get(LHS->getType(), !IsAnd);
6240b57cec5SDimitry Andric 
62506c3fb27SDimitry Andric       if (IsNot && !ConstB->isSubsetOf(*ConstD) && !ConstD->isSubsetOf(*ConstB))
62606c3fb27SDimitry Andric         return nullptr;
62706c3fb27SDimitry Andric 
62806c3fb27SDimitry Andric       APInt BD, CE;
62906c3fb27SDimitry Andric       if (IsNot) {
63006c3fb27SDimitry Andric         BD = *ConstB & *ConstD;
63106c3fb27SDimitry Andric         CE = ConstC & ConstE;
63206c3fb27SDimitry Andric       } else {
63306c3fb27SDimitry Andric         BD = *ConstB | *ConstD;
63406c3fb27SDimitry Andric         CE = ConstC | ConstE;
6350b57cec5SDimitry Andric       }
63606c3fb27SDimitry Andric       Value *NewAnd = Builder.CreateAnd(A, BD);
63706c3fb27SDimitry Andric       Value *CEVal = ConstantInt::get(A->getType(), CE);
63806c3fb27SDimitry Andric       return Builder.CreateICmp(CC, CEVal, NewAnd);
63906c3fb27SDimitry Andric     };
6400b57cec5SDimitry Andric 
64106c3fb27SDimitry Andric     if (Mask & BMask_Mixed)
64206c3fb27SDimitry Andric       return FoldBMixed(NewCC, false);
64306c3fb27SDimitry Andric     if (Mask & BMask_NotMixed) // can be else also
64406c3fb27SDimitry Andric       return FoldBMixed(NewCC, true);
64506c3fb27SDimitry Andric   }
6460b57cec5SDimitry Andric   return nullptr;
6470b57cec5SDimitry Andric }
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
6500b57cec5SDimitry Andric /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
6510b57cec5SDimitry Andric /// If \p Inverted is true then the check is for the inverted range, e.g.
6520b57cec5SDimitry Andric /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
653e8d8bef9SDimitry Andric Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
6540b57cec5SDimitry Andric                                             bool Inverted) {
6550b57cec5SDimitry Andric   // Check the lower range comparison, e.g. x >= 0
6560b57cec5SDimitry Andric   // InstCombine already ensured that if there is a constant it's on the RHS.
6570b57cec5SDimitry Andric   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
6580b57cec5SDimitry Andric   if (!RangeStart)
6590b57cec5SDimitry Andric     return nullptr;
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
6620b57cec5SDimitry Andric                                Cmp0->getPredicate());
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
6650b57cec5SDimitry Andric   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
6660b57cec5SDimitry Andric         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
6670b57cec5SDimitry Andric     return nullptr;
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
6700b57cec5SDimitry Andric                                Cmp1->getPredicate());
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   Value *Input = Cmp0->getOperand(0);
6730b57cec5SDimitry Andric   Value *RangeEnd;
6740b57cec5SDimitry Andric   if (Cmp1->getOperand(0) == Input) {
6750b57cec5SDimitry Andric     // For the upper range compare we have: icmp x, n
6760b57cec5SDimitry Andric     RangeEnd = Cmp1->getOperand(1);
6770b57cec5SDimitry Andric   } else if (Cmp1->getOperand(1) == Input) {
6780b57cec5SDimitry Andric     // For the upper range compare we have: icmp n, x
6790b57cec5SDimitry Andric     RangeEnd = Cmp1->getOperand(0);
6800b57cec5SDimitry Andric     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
6810b57cec5SDimitry Andric   } else {
6820b57cec5SDimitry Andric     return nullptr;
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric 
6850b57cec5SDimitry Andric   // Check the upper range comparison, e.g. x < n
6860b57cec5SDimitry Andric   ICmpInst::Predicate NewPred;
6870b57cec5SDimitry Andric   switch (Pred1) {
6880b57cec5SDimitry Andric     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
6890b57cec5SDimitry Andric     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
6900b57cec5SDimitry Andric     default: return nullptr;
6910b57cec5SDimitry Andric   }
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   // This simplification is only valid if the upper range is not negative.
6940b57cec5SDimitry Andric   KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
6950b57cec5SDimitry Andric   if (!Known.isNonNegative())
6960b57cec5SDimitry Andric     return nullptr;
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   if (Inverted)
6990b57cec5SDimitry Andric     NewPred = ICmpInst::getInversePredicate(NewPred);
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric   return Builder.CreateICmp(NewPred, Input, RangeEnd);
7020b57cec5SDimitry Andric }
7030b57cec5SDimitry Andric 
7040fca6ea1SDimitry Andric // (or (icmp eq X, 0), (icmp eq X, Pow2OrZero))
7050fca6ea1SDimitry Andric //      -> (icmp eq (and X, Pow2OrZero), X)
7060fca6ea1SDimitry Andric // (and (icmp ne X, 0), (icmp ne X, Pow2OrZero))
7070fca6ea1SDimitry Andric //      -> (icmp ne (and X, Pow2OrZero), X)
7080fca6ea1SDimitry Andric static Value *
7090fca6ea1SDimitry Andric foldAndOrOfICmpsWithPow2AndWithZero(InstCombiner::BuilderTy &Builder,
7100fca6ea1SDimitry Andric                                     ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
7110fca6ea1SDimitry Andric                                     const SimplifyQuery &Q) {
7120fca6ea1SDimitry Andric   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
7130fca6ea1SDimitry Andric   // Make sure we have right compares for our op.
7140fca6ea1SDimitry Andric   if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
7150fca6ea1SDimitry Andric     return nullptr;
7160fca6ea1SDimitry Andric 
7170fca6ea1SDimitry Andric   // Make it so we can match LHS against the (icmp eq/ne X, 0) just for
7180fca6ea1SDimitry Andric   // simplicity.
7190fca6ea1SDimitry Andric   if (match(RHS->getOperand(1), m_Zero()))
7200fca6ea1SDimitry Andric     std::swap(LHS, RHS);
7210fca6ea1SDimitry Andric 
7220fca6ea1SDimitry Andric   Value *Pow2, *Op;
7230fca6ea1SDimitry Andric   // Match the desired pattern:
7240fca6ea1SDimitry Andric   // LHS: (icmp eq/ne X, 0)
7250fca6ea1SDimitry Andric   // RHS: (icmp eq/ne X, Pow2OrZero)
7260fca6ea1SDimitry Andric   // Skip if Pow2OrZero is 1. Either way it gets folded to (icmp ugt X, 1) but
7270fca6ea1SDimitry Andric   // this form ends up slightly less canonical.
7280fca6ea1SDimitry Andric   // We could potentially be more sophisticated than requiring LHS/RHS
7290fca6ea1SDimitry Andric   // be one-use. We don't create additional instructions if only one
7300fca6ea1SDimitry Andric   // of them is one-use. So cases where one is one-use and the other
7310fca6ea1SDimitry Andric   // is two-use might be profitable.
7320fca6ea1SDimitry Andric   if (!match(LHS, m_OneUse(m_ICmp(Pred, m_Value(Op), m_Zero()))) ||
7330fca6ea1SDimitry Andric       !match(RHS, m_OneUse(m_c_ICmp(Pred, m_Specific(Op), m_Value(Pow2)))) ||
7340fca6ea1SDimitry Andric       match(Pow2, m_One()) ||
7350fca6ea1SDimitry Andric       !isKnownToBeAPowerOfTwo(Pow2, Q.DL, /*OrZero=*/true, /*Depth=*/0, Q.AC,
7360fca6ea1SDimitry Andric                               Q.CxtI, Q.DT))
7370fca6ea1SDimitry Andric     return nullptr;
7380fca6ea1SDimitry Andric 
7390fca6ea1SDimitry Andric   Value *And = Builder.CreateAnd(Op, Pow2);
7400fca6ea1SDimitry Andric   return Builder.CreateICmp(Pred, And, Op);
7410fca6ea1SDimitry Andric }
7420fca6ea1SDimitry Andric 
7430b57cec5SDimitry Andric // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
7440b57cec5SDimitry Andric // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
745e8d8bef9SDimitry Andric Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
746e8d8bef9SDimitry Andric                                                        ICmpInst *RHS,
747fe6060f1SDimitry Andric                                                        Instruction *CxtI,
748fe6060f1SDimitry Andric                                                        bool IsAnd,
749fe6060f1SDimitry Andric                                                        bool IsLogical) {
750fe6060f1SDimitry Andric   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
751fe6060f1SDimitry Andric   if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
7520b57cec5SDimitry Andric     return nullptr;
7530b57cec5SDimitry Andric 
754e8d8bef9SDimitry Andric   if (!match(LHS->getOperand(1), m_Zero()) ||
755e8d8bef9SDimitry Andric       !match(RHS->getOperand(1), m_Zero()))
7560b57cec5SDimitry Andric     return nullptr;
7570b57cec5SDimitry Andric 
758fe6060f1SDimitry Andric   Value *L1, *L2, *R1, *R2;
759fe6060f1SDimitry Andric   if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
760fe6060f1SDimitry Andric       match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
761fe6060f1SDimitry Andric     if (L1 == R2 || L2 == R2)
762fe6060f1SDimitry Andric       std::swap(R1, R2);
763fe6060f1SDimitry Andric     if (L2 == R1)
764fe6060f1SDimitry Andric       std::swap(L1, L2);
7650b57cec5SDimitry Andric 
766fe6060f1SDimitry Andric     if (L1 == R1 &&
767fe6060f1SDimitry Andric         isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
768fe6060f1SDimitry Andric         isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
769fe6060f1SDimitry Andric       // If this is a logical and/or, then we must prevent propagation of a
770fe6060f1SDimitry Andric       // poison value from the RHS by inserting freeze.
771fe6060f1SDimitry Andric       if (IsLogical)
772fe6060f1SDimitry Andric         R2 = Builder.CreateFreeze(R2);
773fe6060f1SDimitry Andric       Value *Mask = Builder.CreateOr(L2, R2);
774fe6060f1SDimitry Andric       Value *Masked = Builder.CreateAnd(L1, Mask);
775fe6060f1SDimitry Andric       auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
7760b57cec5SDimitry Andric       return Builder.CreateICmp(NewPred, Masked, Mask);
7770b57cec5SDimitry Andric     }
7780b57cec5SDimitry Andric   }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   return nullptr;
7810b57cec5SDimitry Andric }
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric /// General pattern:
7840b57cec5SDimitry Andric ///   X & Y
7850b57cec5SDimitry Andric ///
7860b57cec5SDimitry Andric /// Where Y is checking that all the high bits (covered by a mask 4294967168)
7870b57cec5SDimitry Andric /// are uniform, i.e.  %arg & 4294967168  can be either  4294967168  or  0
7880b57cec5SDimitry Andric /// Pattern can be one of:
7890b57cec5SDimitry Andric ///   %t = add        i32 %arg,    128
7900b57cec5SDimitry Andric ///   %r = icmp   ult i32 %t,      256
7910b57cec5SDimitry Andric /// Or
7920b57cec5SDimitry Andric ///   %t0 = shl       i32 %arg,    24
7930b57cec5SDimitry Andric ///   %t1 = ashr      i32 %t0,     24
7940b57cec5SDimitry Andric ///   %r  = icmp  eq  i32 %t1,     %arg
7950b57cec5SDimitry Andric /// Or
7960b57cec5SDimitry Andric ///   %t0 = trunc     i32 %arg  to i8
7970b57cec5SDimitry Andric ///   %t1 = sext      i8  %t0   to i32
7980b57cec5SDimitry Andric ///   %r  = icmp  eq  i32 %t1,     %arg
7990b57cec5SDimitry Andric /// This pattern is a signed truncation check.
8000b57cec5SDimitry Andric ///
8010b57cec5SDimitry Andric /// And X is checking that some bit in that same mask is zero.
8020b57cec5SDimitry Andric /// I.e. can be one of:
8030b57cec5SDimitry Andric ///   %r = icmp sgt i32   %arg,    -1
8040b57cec5SDimitry Andric /// Or
8050b57cec5SDimitry Andric ///   %t = and      i32   %arg,    2147483648
8060b57cec5SDimitry Andric ///   %r = icmp eq  i32   %t,      0
8070b57cec5SDimitry Andric ///
8080b57cec5SDimitry Andric /// Since we are checking that all the bits in that mask are the same,
8090b57cec5SDimitry Andric /// and a particular bit is zero, what we are really checking is that all the
8100b57cec5SDimitry Andric /// masked bits are zero.
8110b57cec5SDimitry Andric /// So this should be transformed to:
8120b57cec5SDimitry Andric ///   %r = icmp ult i32 %arg, 128
8130b57cec5SDimitry Andric static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
8140b57cec5SDimitry Andric                                         Instruction &CxtI,
8150b57cec5SDimitry Andric                                         InstCombiner::BuilderTy &Builder) {
8160b57cec5SDimitry Andric   assert(CxtI.getOpcode() == Instruction::And);
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   // Match  icmp ult (add %arg, C01), C1   (C1 == C01 << 1; powers of two)
8190b57cec5SDimitry Andric   auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
8200b57cec5SDimitry Andric                                             APInt &SignBitMask) -> bool {
8210b57cec5SDimitry Andric     CmpInst::Predicate Pred;
8220b57cec5SDimitry Andric     const APInt *I01, *I1; // powers of two; I1 == I01 << 1
8230b57cec5SDimitry Andric     if (!(match(ICmp,
8240b57cec5SDimitry Andric                 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
8250b57cec5SDimitry Andric           Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
8260b57cec5SDimitry Andric       return false;
8270b57cec5SDimitry Andric     // Which bit is the new sign bit as per the 'signed truncation' pattern?
8280b57cec5SDimitry Andric     SignBitMask = *I01;
8290b57cec5SDimitry Andric     return true;
8300b57cec5SDimitry Andric   };
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   // One icmp needs to be 'signed truncation check'.
8330b57cec5SDimitry Andric   // We need to match this first, else we will mismatch commutative cases.
8340b57cec5SDimitry Andric   Value *X1;
8350b57cec5SDimitry Andric   APInt HighestBit;
8360b57cec5SDimitry Andric   ICmpInst *OtherICmp;
8370b57cec5SDimitry Andric   if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
8380b57cec5SDimitry Andric     OtherICmp = ICmp0;
8390b57cec5SDimitry Andric   else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
8400b57cec5SDimitry Andric     OtherICmp = ICmp1;
8410b57cec5SDimitry Andric   else
8420b57cec5SDimitry Andric     return nullptr;
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   // Try to match/decompose into:  icmp eq (X & Mask), 0
8470b57cec5SDimitry Andric   auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
8480b57cec5SDimitry Andric                            APInt &UnsetBitsMask) -> bool {
8490b57cec5SDimitry Andric     CmpInst::Predicate Pred = ICmp->getPredicate();
8500b57cec5SDimitry Andric     // Can it be decomposed into  icmp eq (X & Mask), 0  ?
8510b57cec5SDimitry Andric     if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
8520b57cec5SDimitry Andric                                    Pred, X, UnsetBitsMask,
8530b57cec5SDimitry Andric                                    /*LookThroughTrunc=*/false) &&
8540b57cec5SDimitry Andric         Pred == ICmpInst::ICMP_EQ)
8550b57cec5SDimitry Andric       return true;
8560b57cec5SDimitry Andric     // Is it  icmp eq (X & Mask), 0  already?
8570b57cec5SDimitry Andric     const APInt *Mask;
8580b57cec5SDimitry Andric     if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
8590b57cec5SDimitry Andric         Pred == ICmpInst::ICMP_EQ) {
8600b57cec5SDimitry Andric       UnsetBitsMask = *Mask;
8610b57cec5SDimitry Andric       return true;
8620b57cec5SDimitry Andric     }
8630b57cec5SDimitry Andric     return false;
8640b57cec5SDimitry Andric   };
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   // And the other icmp needs to be decomposable into a bit test.
8670b57cec5SDimitry Andric   Value *X0;
8680b57cec5SDimitry Andric   APInt UnsetBitsMask;
8690b57cec5SDimitry Andric   if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
8700b57cec5SDimitry Andric     return nullptr;
8710b57cec5SDimitry Andric 
872349cc55cSDimitry Andric   assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   // Are they working on the same value?
8750b57cec5SDimitry Andric   Value *X;
8760b57cec5SDimitry Andric   if (X1 == X0) {
8770b57cec5SDimitry Andric     // Ok as is.
8780b57cec5SDimitry Andric     X = X1;
8790b57cec5SDimitry Andric   } else if (match(X0, m_Trunc(m_Specific(X1)))) {
8800b57cec5SDimitry Andric     UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
8810b57cec5SDimitry Andric     X = X1;
8820b57cec5SDimitry Andric   } else
8830b57cec5SDimitry Andric     return nullptr;
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric   // So which bits should be uniform as per the 'signed truncation check'?
8860b57cec5SDimitry Andric   // (all the bits starting with (i.e. including) HighestBit)
8870b57cec5SDimitry Andric   APInt SignBitsMask = ~(HighestBit - 1U);
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   // UnsetBitsMask must have some common bits with SignBitsMask,
8900b57cec5SDimitry Andric   if (!UnsetBitsMask.intersects(SignBitsMask))
8910b57cec5SDimitry Andric     return nullptr;
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // Does UnsetBitsMask contain any bits outside of SignBitsMask?
8940b57cec5SDimitry Andric   if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
8950b57cec5SDimitry Andric     APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
8960b57cec5SDimitry Andric     if (!OtherHighestBit.isPowerOf2())
8970b57cec5SDimitry Andric       return nullptr;
8980b57cec5SDimitry Andric     HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
8990b57cec5SDimitry Andric   }
9000b57cec5SDimitry Andric   // Else, if it does not, then all is ok as-is.
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric   // %r = icmp ult %X, SignBit
9030b57cec5SDimitry Andric   return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
9040b57cec5SDimitry Andric                                CxtI.getName() + ".simplified");
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
90781ad6265SDimitry Andric /// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and
90881ad6265SDimitry Andric /// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1).
90981ad6265SDimitry Andric /// Also used for logical and/or, must be poison safe.
91081ad6265SDimitry Andric static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
91181ad6265SDimitry Andric                                    InstCombiner::BuilderTy &Builder) {
91281ad6265SDimitry Andric   CmpInst::Predicate Pred0, Pred1;
91381ad6265SDimitry Andric   Value *X;
91481ad6265SDimitry Andric   if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
91581ad6265SDimitry Andric                           m_SpecificInt(1))) ||
91681ad6265SDimitry Andric       !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())))
91781ad6265SDimitry Andric     return nullptr;
91881ad6265SDimitry Andric 
91981ad6265SDimitry Andric   Value *CtPop = Cmp0->getOperand(0);
92081ad6265SDimitry Andric   if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE)
92181ad6265SDimitry Andric     return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1));
92281ad6265SDimitry Andric   if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ)
92381ad6265SDimitry Andric     return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2));
92481ad6265SDimitry Andric 
92581ad6265SDimitry Andric   return nullptr;
92681ad6265SDimitry Andric }
92781ad6265SDimitry Andric 
9280b57cec5SDimitry Andric /// Reduce a pair of compares that check if a value has exactly 1 bit set.
929*5deeebd8SDimitry Andric /// Also used for logical and/or, must be poison safe if range attributes are
930*5deeebd8SDimitry Andric /// dropped.
9310b57cec5SDimitry Andric static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
932*5deeebd8SDimitry Andric                              InstCombiner::BuilderTy &Builder,
933*5deeebd8SDimitry Andric                              InstCombinerImpl &IC) {
9340b57cec5SDimitry Andric   // Handle 'and' / 'or' commutation: make the equality check the first operand.
9350b57cec5SDimitry Andric   if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
9360b57cec5SDimitry Andric     std::swap(Cmp0, Cmp1);
9370b57cec5SDimitry Andric   else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
9380b57cec5SDimitry Andric     std::swap(Cmp0, Cmp1);
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1
9410b57cec5SDimitry Andric   CmpInst::Predicate Pred0, Pred1;
9420b57cec5SDimitry Andric   Value *X;
9430b57cec5SDimitry Andric   if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
9440b57cec5SDimitry Andric       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
9450b57cec5SDimitry Andric                          m_SpecificInt(2))) &&
9460b57cec5SDimitry Andric       Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
947*5deeebd8SDimitry Andric     auto *CtPop = cast<Instruction>(Cmp1->getOperand(0));
948*5deeebd8SDimitry Andric     // Drop range attributes and re-infer them in the next iteration.
949*5deeebd8SDimitry Andric     CtPop->dropPoisonGeneratingAnnotations();
950*5deeebd8SDimitry Andric     IC.addToWorklist(CtPop);
9510b57cec5SDimitry Andric     return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
9520b57cec5SDimitry Andric   }
9530b57cec5SDimitry Andric   // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1
9540b57cec5SDimitry Andric   if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
9550b57cec5SDimitry Andric       match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
9560b57cec5SDimitry Andric                          m_SpecificInt(1))) &&
9570b57cec5SDimitry Andric       Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
958*5deeebd8SDimitry Andric     auto *CtPop = cast<Instruction>(Cmp1->getOperand(0));
959*5deeebd8SDimitry Andric     // Drop range attributes and re-infer them in the next iteration.
960*5deeebd8SDimitry Andric     CtPop->dropPoisonGeneratingAnnotations();
961*5deeebd8SDimitry Andric     IC.addToWorklist(CtPop);
9620b57cec5SDimitry Andric     return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
9630b57cec5SDimitry Andric   }
9640b57cec5SDimitry Andric   return nullptr;
9650b57cec5SDimitry Andric }
9660b57cec5SDimitry Andric 
96706c3fb27SDimitry Andric /// Try to fold (icmp(A & B) == 0) & (icmp(A & D) != E) into (icmp A u< D) iff
96806c3fb27SDimitry Andric /// B is a contiguous set of ones starting from the most significant bit
96906c3fb27SDimitry Andric /// (negative power of 2), D and E are equal, and D is a contiguous set of ones
97006c3fb27SDimitry Andric /// starting at the most significant zero bit in B. Parameter B supports masking
97106c3fb27SDimitry Andric /// using undef/poison in either scalar or vector values.
97206c3fb27SDimitry Andric static Value *foldNegativePower2AndShiftedMask(
97306c3fb27SDimitry Andric     Value *A, Value *B, Value *D, Value *E, ICmpInst::Predicate PredL,
97406c3fb27SDimitry Andric     ICmpInst::Predicate PredR, InstCombiner::BuilderTy &Builder) {
97506c3fb27SDimitry Andric   assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
97606c3fb27SDimitry Andric          "Expected equality predicates for masked type of icmps.");
97706c3fb27SDimitry Andric   if (PredL != ICmpInst::ICMP_EQ || PredR != ICmpInst::ICMP_NE)
97806c3fb27SDimitry Andric     return nullptr;
97906c3fb27SDimitry Andric 
98006c3fb27SDimitry Andric   if (!match(B, m_NegatedPower2()) || !match(D, m_ShiftedMask()) ||
98106c3fb27SDimitry Andric       !match(E, m_ShiftedMask()))
98206c3fb27SDimitry Andric     return nullptr;
98306c3fb27SDimitry Andric 
98406c3fb27SDimitry Andric   // Test scalar arguments for conversion. B has been validated earlier to be a
98506c3fb27SDimitry Andric   // negative power of two and thus is guaranteed to have one or more contiguous
98606c3fb27SDimitry Andric   // ones starting from the MSB followed by zero or more contiguous zeros. D has
98706c3fb27SDimitry Andric   // been validated earlier to be a shifted set of one or more contiguous ones.
98806c3fb27SDimitry Andric   // In order to match, B leading ones and D leading zeros should be equal. The
98906c3fb27SDimitry Andric   // predicate that B be a negative power of 2 prevents the condition of there
99006c3fb27SDimitry Andric   // ever being zero leading ones. Thus 0 == 0 cannot occur. The predicate that
99106c3fb27SDimitry Andric   // D always be a shifted mask prevents the condition of D equaling 0. This
99206c3fb27SDimitry Andric   // prevents matching the condition where B contains the maximum number of
99306c3fb27SDimitry Andric   // leading one bits (-1) and D contains the maximum number of leading zero
99406c3fb27SDimitry Andric   // bits (0).
99506c3fb27SDimitry Andric   auto isReducible = [](const Value *B, const Value *D, const Value *E) {
99606c3fb27SDimitry Andric     const APInt *BCst, *DCst, *ECst;
9970fca6ea1SDimitry Andric     return match(B, m_APIntAllowPoison(BCst)) && match(D, m_APInt(DCst)) &&
99806c3fb27SDimitry Andric            match(E, m_APInt(ECst)) && *DCst == *ECst &&
9990fca6ea1SDimitry Andric            (isa<PoisonValue>(B) ||
100006c3fb27SDimitry Andric             (BCst->countLeadingOnes() == DCst->countLeadingZeros()));
100106c3fb27SDimitry Andric   };
100206c3fb27SDimitry Andric 
100306c3fb27SDimitry Andric   // Test vector type arguments for conversion.
100406c3fb27SDimitry Andric   if (const auto *BVTy = dyn_cast<VectorType>(B->getType())) {
100506c3fb27SDimitry Andric     const auto *BFVTy = dyn_cast<FixedVectorType>(BVTy);
100606c3fb27SDimitry Andric     const auto *BConst = dyn_cast<Constant>(B);
100706c3fb27SDimitry Andric     const auto *DConst = dyn_cast<Constant>(D);
100806c3fb27SDimitry Andric     const auto *EConst = dyn_cast<Constant>(E);
100906c3fb27SDimitry Andric 
101006c3fb27SDimitry Andric     if (!BFVTy || !BConst || !DConst || !EConst)
101106c3fb27SDimitry Andric       return nullptr;
101206c3fb27SDimitry Andric 
101306c3fb27SDimitry Andric     for (unsigned I = 0; I != BFVTy->getNumElements(); ++I) {
101406c3fb27SDimitry Andric       const auto *BElt = BConst->getAggregateElement(I);
101506c3fb27SDimitry Andric       const auto *DElt = DConst->getAggregateElement(I);
101606c3fb27SDimitry Andric       const auto *EElt = EConst->getAggregateElement(I);
101706c3fb27SDimitry Andric 
101806c3fb27SDimitry Andric       if (!BElt || !DElt || !EElt)
101906c3fb27SDimitry Andric         return nullptr;
102006c3fb27SDimitry Andric       if (!isReducible(BElt, DElt, EElt))
102106c3fb27SDimitry Andric         return nullptr;
102206c3fb27SDimitry Andric     }
102306c3fb27SDimitry Andric   } else {
102406c3fb27SDimitry Andric     // Test scalar type arguments for conversion.
102506c3fb27SDimitry Andric     if (!isReducible(B, D, E))
102606c3fb27SDimitry Andric       return nullptr;
102706c3fb27SDimitry Andric   }
102806c3fb27SDimitry Andric   return Builder.CreateICmp(ICmpInst::ICMP_ULT, A, D);
102906c3fb27SDimitry Andric }
103006c3fb27SDimitry Andric 
103106c3fb27SDimitry Andric /// Try to fold ((icmp X u< P) & (icmp(X & M) != M)) or ((icmp X s> -1) &
103206c3fb27SDimitry Andric /// (icmp(X & M) != M)) into (icmp X u< M). Where P is a power of 2, M < P, and
103306c3fb27SDimitry Andric /// M is a contiguous shifted mask starting at the right most significant zero
103406c3fb27SDimitry Andric /// bit in P. SGT is supported as when P is the largest representable power of
103506c3fb27SDimitry Andric /// 2, an earlier optimization converts the expression into (icmp X s> -1).
103606c3fb27SDimitry Andric /// Parameter P supports masking using undef/poison in either scalar or vector
103706c3fb27SDimitry Andric /// values.
103806c3fb27SDimitry Andric static Value *foldPowerOf2AndShiftedMask(ICmpInst *Cmp0, ICmpInst *Cmp1,
103906c3fb27SDimitry Andric                                          bool JoinedByAnd,
104006c3fb27SDimitry Andric                                          InstCombiner::BuilderTy &Builder) {
104106c3fb27SDimitry Andric   if (!JoinedByAnd)
104206c3fb27SDimitry Andric     return nullptr;
104306c3fb27SDimitry Andric   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
104406c3fb27SDimitry Andric   ICmpInst::Predicate CmpPred0 = Cmp0->getPredicate(),
104506c3fb27SDimitry Andric                       CmpPred1 = Cmp1->getPredicate();
104606c3fb27SDimitry Andric   // Assuming P is a 2^n, getMaskedTypeForICmpPair will normalize (icmp X u<
104706c3fb27SDimitry Andric   // 2^n) into (icmp (X & ~(2^n-1)) == 0) and (icmp X s> -1) into (icmp (X &
104806c3fb27SDimitry Andric   // SignMask) == 0).
104906c3fb27SDimitry Andric   std::optional<std::pair<unsigned, unsigned>> MaskPair =
105006c3fb27SDimitry Andric       getMaskedTypeForICmpPair(A, B, C, D, E, Cmp0, Cmp1, CmpPred0, CmpPred1);
105106c3fb27SDimitry Andric   if (!MaskPair)
105206c3fb27SDimitry Andric     return nullptr;
105306c3fb27SDimitry Andric 
105406c3fb27SDimitry Andric   const auto compareBMask = BMask_NotMixed | BMask_NotAllOnes;
105506c3fb27SDimitry Andric   unsigned CmpMask0 = MaskPair->first;
105606c3fb27SDimitry Andric   unsigned CmpMask1 = MaskPair->second;
105706c3fb27SDimitry Andric   if ((CmpMask0 & Mask_AllZeros) && (CmpMask1 == compareBMask)) {
105806c3fb27SDimitry Andric     if (Value *V = foldNegativePower2AndShiftedMask(A, B, D, E, CmpPred0,
105906c3fb27SDimitry Andric                                                     CmpPred1, Builder))
106006c3fb27SDimitry Andric       return V;
106106c3fb27SDimitry Andric   } else if ((CmpMask0 == compareBMask) && (CmpMask1 & Mask_AllZeros)) {
106206c3fb27SDimitry Andric     if (Value *V = foldNegativePower2AndShiftedMask(A, D, B, C, CmpPred1,
106306c3fb27SDimitry Andric                                                     CmpPred0, Builder))
106406c3fb27SDimitry Andric       return V;
106506c3fb27SDimitry Andric   }
106606c3fb27SDimitry Andric   return nullptr;
106706c3fb27SDimitry Andric }
106806c3fb27SDimitry Andric 
10698bcb0991SDimitry Andric /// Commuted variants are assumed to be handled by calling this function again
10708bcb0991SDimitry Andric /// with the parameters swapped.
10718bcb0991SDimitry Andric static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
10728bcb0991SDimitry Andric                                          ICmpInst *UnsignedICmp, bool IsAnd,
10738bcb0991SDimitry Andric                                          const SimplifyQuery &Q,
10748bcb0991SDimitry Andric                                          InstCombiner::BuilderTy &Builder) {
10758bcb0991SDimitry Andric   Value *ZeroCmpOp;
10768bcb0991SDimitry Andric   ICmpInst::Predicate EqPred;
10778bcb0991SDimitry Andric   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
10788bcb0991SDimitry Andric       !ICmpInst::isEquality(EqPred))
10798bcb0991SDimitry Andric     return nullptr;
10808bcb0991SDimitry Andric 
10818bcb0991SDimitry Andric   ICmpInst::Predicate UnsignedPred;
10828bcb0991SDimitry Andric 
10838bcb0991SDimitry Andric   Value *A, *B;
10848bcb0991SDimitry Andric   if (match(UnsignedICmp,
10858bcb0991SDimitry Andric             m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
10868bcb0991SDimitry Andric       match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
10878bcb0991SDimitry Andric       (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
10888bcb0991SDimitry Andric     auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
10890fca6ea1SDimitry Andric       if (!isKnownNonZero(NonZero, Q))
10908bcb0991SDimitry Andric         std::swap(NonZero, Other);
10910fca6ea1SDimitry Andric       return isKnownNonZero(NonZero, Q);
10928bcb0991SDimitry Andric     };
10938bcb0991SDimitry Andric 
10948bcb0991SDimitry Andric     // Given  ZeroCmpOp = (A + B)
10958bcb0991SDimitry Andric     //   ZeroCmpOp <  A && ZeroCmpOp != 0  -->  (0-X) <  Y  iff
10968bcb0991SDimitry Andric     //   ZeroCmpOp >= A || ZeroCmpOp == 0  -->  (0-X) >= Y  iff
10978bcb0991SDimitry Andric     //     with X being the value (A/B) that is known to be non-zero,
10988bcb0991SDimitry Andric     //     and Y being remaining value.
10998bcb0991SDimitry Andric     if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
11008bcb0991SDimitry Andric         IsAnd && GetKnownNonZeroAndOther(B, A))
11018bcb0991SDimitry Andric       return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
11028bcb0991SDimitry Andric     if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
11038bcb0991SDimitry Andric         !IsAnd && GetKnownNonZeroAndOther(B, A))
11048bcb0991SDimitry Andric       return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
11058bcb0991SDimitry Andric   }
11068bcb0991SDimitry Andric 
11078bcb0991SDimitry Andric   return nullptr;
11088bcb0991SDimitry Andric }
11098bcb0991SDimitry Andric 
1110fe6060f1SDimitry Andric struct IntPart {
1111fe6060f1SDimitry Andric   Value *From;
1112fe6060f1SDimitry Andric   unsigned StartBit;
1113fe6060f1SDimitry Andric   unsigned NumBits;
1114fe6060f1SDimitry Andric };
1115fe6060f1SDimitry Andric 
1116fe6060f1SDimitry Andric /// Match an extraction of bits from an integer.
1117bdd1243dSDimitry Andric static std::optional<IntPart> matchIntPart(Value *V) {
1118fe6060f1SDimitry Andric   Value *X;
1119fe6060f1SDimitry Andric   if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
1120bdd1243dSDimitry Andric     return std::nullopt;
1121fe6060f1SDimitry Andric 
1122fe6060f1SDimitry Andric   unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
1123fe6060f1SDimitry Andric   unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
1124fe6060f1SDimitry Andric   Value *Y;
1125fe6060f1SDimitry Andric   const APInt *Shift;
1126fe6060f1SDimitry Andric   // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits
1127fe6060f1SDimitry Andric   // from Y, not any shifted-in zeroes.
1128fe6060f1SDimitry Andric   if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
1129fe6060f1SDimitry Andric       Shift->ule(NumOriginalBits - NumExtractedBits))
1130fe6060f1SDimitry Andric     return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
1131fe6060f1SDimitry Andric   return {{X, 0, NumExtractedBits}};
1132fe6060f1SDimitry Andric }
1133fe6060f1SDimitry Andric 
1134fe6060f1SDimitry Andric /// Materialize an extraction of bits from an integer in IR.
1135fe6060f1SDimitry Andric static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
1136fe6060f1SDimitry Andric   Value *V = P.From;
1137fe6060f1SDimitry Andric   if (P.StartBit)
1138fe6060f1SDimitry Andric     V = Builder.CreateLShr(V, P.StartBit);
1139fe6060f1SDimitry Andric   Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
1140fe6060f1SDimitry Andric   if (TruncTy != V->getType())
1141fe6060f1SDimitry Andric     V = Builder.CreateTrunc(V, TruncTy);
1142fe6060f1SDimitry Andric   return V;
1143fe6060f1SDimitry Andric }
1144fe6060f1SDimitry Andric 
1145fe6060f1SDimitry Andric /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01
1146fe6060f1SDimitry Andric /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01
1147fe6060f1SDimitry Andric /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer.
1148349cc55cSDimitry Andric Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
1149349cc55cSDimitry Andric                                        bool IsAnd) {
1150fe6060f1SDimitry Andric   if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
1151fe6060f1SDimitry Andric     return nullptr;
1152fe6060f1SDimitry Andric 
1153fe6060f1SDimitry Andric   CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
11545f757f3fSDimitry Andric   auto GetMatchPart = [&](ICmpInst *Cmp,
11555f757f3fSDimitry Andric                           unsigned OpNo) -> std::optional<IntPart> {
11565f757f3fSDimitry Andric     if (Pred == Cmp->getPredicate())
11575f757f3fSDimitry Andric       return matchIntPart(Cmp->getOperand(OpNo));
1158fe6060f1SDimitry Andric 
11595f757f3fSDimitry Andric     const APInt *C;
11605f757f3fSDimitry Andric     // (icmp eq (lshr x, C), (lshr y, C)) gets optimized to:
11615f757f3fSDimitry Andric     // (icmp ult (xor x, y), 1 << C) so also look for that.
11625f757f3fSDimitry Andric     if (Pred == CmpInst::ICMP_EQ && Cmp->getPredicate() == CmpInst::ICMP_ULT) {
11635f757f3fSDimitry Andric       if (!match(Cmp->getOperand(1), m_Power2(C)) ||
11645f757f3fSDimitry Andric           !match(Cmp->getOperand(0), m_Xor(m_Value(), m_Value())))
11655f757f3fSDimitry Andric         return std::nullopt;
11665f757f3fSDimitry Andric     }
11675f757f3fSDimitry Andric 
11685f757f3fSDimitry Andric     // (icmp ne (lshr x, C), (lshr y, C)) gets optimized to:
11695f757f3fSDimitry Andric     // (icmp ugt (xor x, y), (1 << C) - 1) so also look for that.
11705f757f3fSDimitry Andric     else if (Pred == CmpInst::ICMP_NE &&
11715f757f3fSDimitry Andric              Cmp->getPredicate() == CmpInst::ICMP_UGT) {
11725f757f3fSDimitry Andric       if (!match(Cmp->getOperand(1), m_LowBitMask(C)) ||
11735f757f3fSDimitry Andric           !match(Cmp->getOperand(0), m_Xor(m_Value(), m_Value())))
11745f757f3fSDimitry Andric         return std::nullopt;
11755f757f3fSDimitry Andric     } else {
11765f757f3fSDimitry Andric       return std::nullopt;
11775f757f3fSDimitry Andric     }
11785f757f3fSDimitry Andric 
11795f757f3fSDimitry Andric     unsigned From = Pred == CmpInst::ICMP_NE ? C->popcount() : C->countr_zero();
11805f757f3fSDimitry Andric     Instruction *I = cast<Instruction>(Cmp->getOperand(0));
11815f757f3fSDimitry Andric     return {{I->getOperand(OpNo), From, C->getBitWidth() - From}};
11825f757f3fSDimitry Andric   };
11835f757f3fSDimitry Andric 
11845f757f3fSDimitry Andric   std::optional<IntPart> L0 = GetMatchPart(Cmp0, 0);
11855f757f3fSDimitry Andric   std::optional<IntPart> R0 = GetMatchPart(Cmp0, 1);
11865f757f3fSDimitry Andric   std::optional<IntPart> L1 = GetMatchPart(Cmp1, 0);
11875f757f3fSDimitry Andric   std::optional<IntPart> R1 = GetMatchPart(Cmp1, 1);
1188fe6060f1SDimitry Andric   if (!L0 || !R0 || !L1 || !R1)
1189fe6060f1SDimitry Andric     return nullptr;
1190fe6060f1SDimitry Andric 
1191fe6060f1SDimitry Andric   // Make sure the LHS/RHS compare a part of the same value, possibly after
1192fe6060f1SDimitry Andric   // an operand swap.
1193fe6060f1SDimitry Andric   if (L0->From != L1->From || R0->From != R1->From) {
1194fe6060f1SDimitry Andric     if (L0->From != R1->From || R0->From != L1->From)
1195fe6060f1SDimitry Andric       return nullptr;
1196fe6060f1SDimitry Andric     std::swap(L1, R1);
1197fe6060f1SDimitry Andric   }
1198fe6060f1SDimitry Andric 
1199fe6060f1SDimitry Andric   // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being
1200fe6060f1SDimitry Andric   // the low part and L1/R1 being the high part.
1201fe6060f1SDimitry Andric   if (L0->StartBit + L0->NumBits != L1->StartBit ||
1202fe6060f1SDimitry Andric       R0->StartBit + R0->NumBits != R1->StartBit) {
1203fe6060f1SDimitry Andric     if (L1->StartBit + L1->NumBits != L0->StartBit ||
1204fe6060f1SDimitry Andric         R1->StartBit + R1->NumBits != R0->StartBit)
1205fe6060f1SDimitry Andric       return nullptr;
1206fe6060f1SDimitry Andric     std::swap(L0, L1);
1207fe6060f1SDimitry Andric     std::swap(R0, R1);
1208fe6060f1SDimitry Andric   }
1209fe6060f1SDimitry Andric 
1210fe6060f1SDimitry Andric   // We can simplify to a comparison of these larger parts of the integers.
1211fe6060f1SDimitry Andric   IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
1212fe6060f1SDimitry Andric   IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
1213fe6060f1SDimitry Andric   Value *LValue = extractIntPart(L, Builder);
1214fe6060f1SDimitry Andric   Value *RValue = extractIntPart(R, Builder);
1215fe6060f1SDimitry Andric   return Builder.CreateICmp(Pred, LValue, RValue);
1216fe6060f1SDimitry Andric }
1217fe6060f1SDimitry Andric 
12185ffd83dbSDimitry Andric /// Reduce logic-of-compares with equality to a constant by substituting a
12195ffd83dbSDimitry Andric /// common operand with the constant. Callers are expected to call this with
12205ffd83dbSDimitry Andric /// Cmp0/Cmp1 switched to handle logic op commutativity.
12215ffd83dbSDimitry Andric static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
1222bdd1243dSDimitry Andric                                           bool IsAnd, bool IsLogical,
12235ffd83dbSDimitry Andric                                           InstCombiner::BuilderTy &Builder,
12245ffd83dbSDimitry Andric                                           const SimplifyQuery &Q) {
12255ffd83dbSDimitry Andric   // Match an equality compare with a non-poison constant as Cmp0.
1226590d96feSDimitry Andric   // Also, give up if the compare can be constant-folded to avoid looping.
12275ffd83dbSDimitry Andric   ICmpInst::Predicate Pred0;
12285ffd83dbSDimitry Andric   Value *X;
12295ffd83dbSDimitry Andric   Constant *C;
12305ffd83dbSDimitry Andric   if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
1231590d96feSDimitry Andric       !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
12325ffd83dbSDimitry Andric     return nullptr;
12335ffd83dbSDimitry Andric   if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
12345ffd83dbSDimitry Andric       (!IsAnd && Pred0 != ICmpInst::ICMP_NE))
12355ffd83dbSDimitry Andric     return nullptr;
12365ffd83dbSDimitry Andric 
12375ffd83dbSDimitry Andric   // The other compare must include a common operand (X). Canonicalize the
12385ffd83dbSDimitry Andric   // common operand as operand 1 (Pred1 is swapped if the common operand was
12395ffd83dbSDimitry Andric   // operand 0).
12405ffd83dbSDimitry Andric   Value *Y;
12415ffd83dbSDimitry Andric   ICmpInst::Predicate Pred1;
12420fca6ea1SDimitry Andric   if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Specific(X))))
12435ffd83dbSDimitry Andric     return nullptr;
12445ffd83dbSDimitry Andric 
12455ffd83dbSDimitry Andric   // Replace variable with constant value equivalence to remove a variable use:
12465ffd83dbSDimitry Andric   // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C)
12475ffd83dbSDimitry Andric   // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C)
12485ffd83dbSDimitry Andric   // Can think of the 'or' substitution with the 'and' bool equivalent:
12495ffd83dbSDimitry Andric   // A || B --> A || (!A && B)
125081ad6265SDimitry Andric   Value *SubstituteCmp = simplifyICmpInst(Pred1, Y, C, Q);
12515ffd83dbSDimitry Andric   if (!SubstituteCmp) {
12525ffd83dbSDimitry Andric     // If we need to create a new instruction, require that the old compare can
12535ffd83dbSDimitry Andric     // be removed.
12545ffd83dbSDimitry Andric     if (!Cmp1->hasOneUse())
12555ffd83dbSDimitry Andric       return nullptr;
12565ffd83dbSDimitry Andric     SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
12575ffd83dbSDimitry Andric   }
1258bdd1243dSDimitry Andric   if (IsLogical)
1259bdd1243dSDimitry Andric     return IsAnd ? Builder.CreateLogicalAnd(Cmp0, SubstituteCmp)
1260bdd1243dSDimitry Andric                  : Builder.CreateLogicalOr(Cmp0, SubstituteCmp);
126181ad6265SDimitry Andric   return Builder.CreateBinOp(IsAnd ? Instruction::And : Instruction::Or, Cmp0,
126281ad6265SDimitry Andric                              SubstituteCmp);
12635ffd83dbSDimitry Andric }
12645ffd83dbSDimitry Andric 
1265349cc55cSDimitry Andric /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2)
1266349cc55cSDimitry Andric /// or   (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2)
1267349cc55cSDimitry Andric /// into a single comparison using range-based reasoning.
126881ad6265SDimitry Andric /// NOTE: This is also used for logical and/or, must be poison-safe!
126981ad6265SDimitry Andric Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
127081ad6265SDimitry Andric                                                      ICmpInst *ICmp2,
127181ad6265SDimitry Andric                                                      bool IsAnd) {
127281ad6265SDimitry Andric   ICmpInst::Predicate Pred1, Pred2;
127381ad6265SDimitry Andric   Value *V1, *V2;
127481ad6265SDimitry Andric   const APInt *C1, *C2;
127581ad6265SDimitry Andric   if (!match(ICmp1, m_ICmp(Pred1, m_Value(V1), m_APInt(C1))) ||
127681ad6265SDimitry Andric       !match(ICmp2, m_ICmp(Pred2, m_Value(V2), m_APInt(C2))))
127781ad6265SDimitry Andric     return nullptr;
127881ad6265SDimitry Andric 
1279349cc55cSDimitry Andric   // Look through add of a constant offset on V1, V2, or both operands. This
1280349cc55cSDimitry Andric   // allows us to interpret the V + C' < C'' range idiom into a proper range.
1281349cc55cSDimitry Andric   const APInt *Offset1 = nullptr, *Offset2 = nullptr;
1282349cc55cSDimitry Andric   if (V1 != V2) {
1283349cc55cSDimitry Andric     Value *X;
1284349cc55cSDimitry Andric     if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
1285349cc55cSDimitry Andric       V1 = X;
1286349cc55cSDimitry Andric     if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
1287349cc55cSDimitry Andric       V2 = X;
1288349cc55cSDimitry Andric   }
1289349cc55cSDimitry Andric 
1290349cc55cSDimitry Andric   if (V1 != V2)
1291349cc55cSDimitry Andric     return nullptr;
1292349cc55cSDimitry Andric 
129381ad6265SDimitry Andric   ConstantRange CR1 = ConstantRange::makeExactICmpRegion(
129481ad6265SDimitry Andric       IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, *C1);
1295349cc55cSDimitry Andric   if (Offset1)
1296349cc55cSDimitry Andric     CR1 = CR1.subtract(*Offset1);
1297349cc55cSDimitry Andric 
129881ad6265SDimitry Andric   ConstantRange CR2 = ConstantRange::makeExactICmpRegion(
129981ad6265SDimitry Andric       IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, *C2);
1300349cc55cSDimitry Andric   if (Offset2)
1301349cc55cSDimitry Andric     CR2 = CR2.subtract(*Offset2);
1302349cc55cSDimitry Andric 
130381ad6265SDimitry Andric   Type *Ty = V1->getType();
130481ad6265SDimitry Andric   Value *NewV = V1;
1305bdd1243dSDimitry Andric   std::optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
130681ad6265SDimitry Andric   if (!CR) {
130781ad6265SDimitry Andric     if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
130881ad6265SDimitry Andric         CR2.isWrappedSet())
1309349cc55cSDimitry Andric       return nullptr;
1310349cc55cSDimitry Andric 
131181ad6265SDimitry Andric     // Check whether we have equal-size ranges that only differ by one bit.
131281ad6265SDimitry Andric     // In that case we can apply a mask to map one range onto the other.
131381ad6265SDimitry Andric     APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
131481ad6265SDimitry Andric     APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
131581ad6265SDimitry Andric     APInt CR1Size = CR1.getUpper() - CR1.getLower();
131681ad6265SDimitry Andric     if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
131781ad6265SDimitry Andric         CR1Size != CR2.getUpper() - CR2.getLower())
131881ad6265SDimitry Andric       return nullptr;
131981ad6265SDimitry Andric 
132081ad6265SDimitry Andric     CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
132181ad6265SDimitry Andric     NewV = Builder.CreateAnd(NewV, ConstantInt::get(Ty, ~LowerDiff));
132281ad6265SDimitry Andric   }
132381ad6265SDimitry Andric 
132481ad6265SDimitry Andric   if (IsAnd)
132581ad6265SDimitry Andric     CR = CR->inverse();
132681ad6265SDimitry Andric 
1327349cc55cSDimitry Andric   CmpInst::Predicate NewPred;
1328349cc55cSDimitry Andric   APInt NewC, Offset;
1329349cc55cSDimitry Andric   CR->getEquivalentICmp(NewPred, NewC, Offset);
1330349cc55cSDimitry Andric 
1331349cc55cSDimitry Andric   if (Offset != 0)
1332349cc55cSDimitry Andric     NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
1333349cc55cSDimitry Andric   return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
1334349cc55cSDimitry Andric }
1335349cc55cSDimitry Andric 
1336bdd1243dSDimitry Andric /// Ignore all operations which only change the sign of a value, returning the
1337bdd1243dSDimitry Andric /// underlying magnitude value.
1338bdd1243dSDimitry Andric static Value *stripSignOnlyFPOps(Value *Val) {
1339bdd1243dSDimitry Andric   match(Val, m_FNeg(m_Value(Val)));
1340bdd1243dSDimitry Andric   match(Val, m_FAbs(m_Value(Val)));
1341bdd1243dSDimitry Andric   match(Val, m_CopySign(m_Value(Val), m_Value()));
1342bdd1243dSDimitry Andric   return Val;
1343bdd1243dSDimitry Andric }
1344bdd1243dSDimitry Andric 
1345bdd1243dSDimitry Andric /// Matches canonical form of isnan, fcmp ord x, 0
1346bdd1243dSDimitry Andric static bool matchIsNotNaN(FCmpInst::Predicate P, Value *LHS, Value *RHS) {
1347bdd1243dSDimitry Andric   return P == FCmpInst::FCMP_ORD && match(RHS, m_AnyZeroFP());
1348bdd1243dSDimitry Andric }
1349bdd1243dSDimitry Andric 
1350bdd1243dSDimitry Andric /// Matches fcmp u__ x, +/-inf
1351bdd1243dSDimitry Andric static bool matchUnorderedInfCompare(FCmpInst::Predicate P, Value *LHS,
1352bdd1243dSDimitry Andric                                      Value *RHS) {
1353bdd1243dSDimitry Andric   return FCmpInst::isUnordered(P) && match(RHS, m_Inf());
1354bdd1243dSDimitry Andric }
1355bdd1243dSDimitry Andric 
1356bdd1243dSDimitry Andric /// and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1357bdd1243dSDimitry Andric ///
1358bdd1243dSDimitry Andric /// Clang emits this pattern for doing an isfinite check in __builtin_isnormal.
1359bdd1243dSDimitry Andric static Value *matchIsFiniteTest(InstCombiner::BuilderTy &Builder, FCmpInst *LHS,
1360bdd1243dSDimitry Andric                                 FCmpInst *RHS) {
1361bdd1243dSDimitry Andric   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1362bdd1243dSDimitry Andric   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1363bdd1243dSDimitry Andric   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1364bdd1243dSDimitry Andric 
1365bdd1243dSDimitry Andric   if (!matchIsNotNaN(PredL, LHS0, LHS1) ||
1366bdd1243dSDimitry Andric       !matchUnorderedInfCompare(PredR, RHS0, RHS1))
1367bdd1243dSDimitry Andric     return nullptr;
1368bdd1243dSDimitry Andric 
1369bdd1243dSDimitry Andric   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1370bdd1243dSDimitry Andric   FastMathFlags FMF = LHS->getFastMathFlags();
1371bdd1243dSDimitry Andric   FMF &= RHS->getFastMathFlags();
1372bdd1243dSDimitry Andric   Builder.setFastMathFlags(FMF);
1373bdd1243dSDimitry Andric 
1374bdd1243dSDimitry Andric   return Builder.CreateFCmp(FCmpInst::getOrderedPredicate(PredR), RHS0, RHS1);
1375bdd1243dSDimitry Andric }
1376bdd1243dSDimitry Andric 
1377e8d8bef9SDimitry Andric Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
137881ad6265SDimitry Andric                                           bool IsAnd, bool IsLogicalSelect) {
13790b57cec5SDimitry Andric   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
13800b57cec5SDimitry Andric   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
13810b57cec5SDimitry Andric   FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric   if (LHS0 == RHS1 && RHS0 == LHS1) {
13840b57cec5SDimitry Andric     // Swap RHS operands to match LHS.
13850b57cec5SDimitry Andric     PredR = FCmpInst::getSwappedPredicate(PredR);
13860b57cec5SDimitry Andric     std::swap(RHS0, RHS1);
13870b57cec5SDimitry Andric   }
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
13900b57cec5SDimitry Andric   // Suppose the relation between x and y is R, where R is one of
13910b57cec5SDimitry Andric   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
13920b57cec5SDimitry Andric   // testing the desired relations.
13930b57cec5SDimitry Andric   //
13940b57cec5SDimitry Andric   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
13950b57cec5SDimitry Andric   //    bool(R & CC0) && bool(R & CC1)
13960b57cec5SDimitry Andric   //  = bool((R & CC0) & (R & CC1))
13970b57cec5SDimitry Andric   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
13980b57cec5SDimitry Andric   //
13990b57cec5SDimitry Andric   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
14000b57cec5SDimitry Andric   //    bool(R & CC0) || bool(R & CC1)
14010b57cec5SDimitry Andric   //  = bool((R & CC0) | (R & CC1))
14020b57cec5SDimitry Andric   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
14030b57cec5SDimitry Andric   if (LHS0 == RHS0 && LHS1 == RHS1) {
14040b57cec5SDimitry Andric     unsigned FCmpCodeL = getFCmpCode(PredL);
14050b57cec5SDimitry Andric     unsigned FCmpCodeR = getFCmpCode(PredR);
14060b57cec5SDimitry Andric     unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
140781ad6265SDimitry Andric 
140881ad6265SDimitry Andric     // Intersect the fast math flags.
140981ad6265SDimitry Andric     // TODO: We can union the fast math flags unless this is a logical select.
141081ad6265SDimitry Andric     IRBuilder<>::FastMathFlagGuard FMFG(Builder);
141181ad6265SDimitry Andric     FastMathFlags FMF = LHS->getFastMathFlags();
141281ad6265SDimitry Andric     FMF &= RHS->getFastMathFlags();
141381ad6265SDimitry Andric     Builder.setFastMathFlags(FMF);
141481ad6265SDimitry Andric 
14150b57cec5SDimitry Andric     return getFCmpValue(NewPred, LHS0, LHS1, Builder);
14160b57cec5SDimitry Andric   }
14170b57cec5SDimitry Andric 
141881ad6265SDimitry Andric   // This transform is not valid for a logical select.
141981ad6265SDimitry Andric   if (!IsLogicalSelect &&
142081ad6265SDimitry Andric       ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
142181ad6265SDimitry Andric        (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
142281ad6265SDimitry Andric         !IsAnd))) {
14230b57cec5SDimitry Andric     if (LHS0->getType() != RHS0->getType())
14240b57cec5SDimitry Andric       return nullptr;
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric     // FCmp canonicalization ensures that (fcmp ord/uno X, X) and
14270b57cec5SDimitry Andric     // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0).
14280b57cec5SDimitry Andric     if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
14290b57cec5SDimitry Andric       // Ignore the constants because they are obviously not NANs:
14300b57cec5SDimitry Andric       // (fcmp ord x, 0.0) & (fcmp ord y, 0.0)  -> (fcmp ord x, y)
14310b57cec5SDimitry Andric       // (fcmp uno x, 0.0) | (fcmp uno y, 0.0)  -> (fcmp uno x, y)
14320b57cec5SDimitry Andric       return Builder.CreateFCmp(PredL, LHS0, RHS0);
14330b57cec5SDimitry Andric   }
14340b57cec5SDimitry Andric 
1435bdd1243dSDimitry Andric   if (IsAnd && stripSignOnlyFPOps(LHS0) == stripSignOnlyFPOps(RHS0)) {
1436bdd1243dSDimitry Andric     // and (fcmp ord x, 0), (fcmp u* x, inf) -> fcmp o* x, inf
1437bdd1243dSDimitry Andric     // and (fcmp ord x, 0), (fcmp u* fabs(x), inf) -> fcmp o* x, inf
1438bdd1243dSDimitry Andric     if (Value *Left = matchIsFiniteTest(Builder, LHS, RHS))
1439bdd1243dSDimitry Andric       return Left;
1440bdd1243dSDimitry Andric     if (Value *Right = matchIsFiniteTest(Builder, RHS, LHS))
1441bdd1243dSDimitry Andric       return Right;
1442bdd1243dSDimitry Andric   }
1443bdd1243dSDimitry Andric 
144406c3fb27SDimitry Andric   // Turn at least two fcmps with constants into llvm.is.fpclass.
144506c3fb27SDimitry Andric   //
144606c3fb27SDimitry Andric   // If we can represent a combined value test with one class call, we can
144706c3fb27SDimitry Andric   // potentially eliminate 4-6 instructions. If we can represent a test with a
144806c3fb27SDimitry Andric   // single fcmp with fneg and fabs, that's likely a better canonical form.
144906c3fb27SDimitry Andric   if (LHS->hasOneUse() && RHS->hasOneUse()) {
145006c3fb27SDimitry Andric     auto [ClassValRHS, ClassMaskRHS] =
145106c3fb27SDimitry Andric         fcmpToClassTest(PredR, *RHS->getFunction(), RHS0, RHS1);
145206c3fb27SDimitry Andric     if (ClassValRHS) {
145306c3fb27SDimitry Andric       auto [ClassValLHS, ClassMaskLHS] =
145406c3fb27SDimitry Andric           fcmpToClassTest(PredL, *LHS->getFunction(), LHS0, LHS1);
145506c3fb27SDimitry Andric       if (ClassValLHS == ClassValRHS) {
145606c3fb27SDimitry Andric         unsigned CombinedMask = IsAnd ? (ClassMaskLHS & ClassMaskRHS)
145706c3fb27SDimitry Andric                                       : (ClassMaskLHS | ClassMaskRHS);
145806c3fb27SDimitry Andric         return Builder.CreateIntrinsic(
145906c3fb27SDimitry Andric             Intrinsic::is_fpclass, {ClassValLHS->getType()},
146006c3fb27SDimitry Andric             {ClassValLHS, Builder.getInt32(CombinedMask)});
146106c3fb27SDimitry Andric       }
146206c3fb27SDimitry Andric     }
146306c3fb27SDimitry Andric   }
146406c3fb27SDimitry Andric 
14650fca6ea1SDimitry Andric   // Canonicalize the range check idiom:
14660fca6ea1SDimitry Andric   // and (fcmp olt/ole/ult/ule x, C), (fcmp ogt/oge/ugt/uge x, -C)
14670fca6ea1SDimitry Andric   // --> fabs(x) olt/ole/ult/ule C
14680fca6ea1SDimitry Andric   // or  (fcmp ogt/oge/ugt/uge x, C), (fcmp olt/ole/ult/ule x, -C)
14690fca6ea1SDimitry Andric   // --> fabs(x) ogt/oge/ugt/uge C
14700fca6ea1SDimitry Andric   // TODO: Generalize to handle a negated variable operand?
14710fca6ea1SDimitry Andric   const APFloat *LHSC, *RHSC;
14720fca6ea1SDimitry Andric   if (LHS0 == RHS0 && LHS->hasOneUse() && RHS->hasOneUse() &&
14730fca6ea1SDimitry Andric       FCmpInst::getSwappedPredicate(PredL) == PredR &&
14740fca6ea1SDimitry Andric       match(LHS1, m_APFloatAllowPoison(LHSC)) &&
14750fca6ea1SDimitry Andric       match(RHS1, m_APFloatAllowPoison(RHSC)) &&
14760fca6ea1SDimitry Andric       LHSC->bitwiseIsEqual(neg(*RHSC))) {
14770fca6ea1SDimitry Andric     auto IsLessThanOrLessEqual = [](FCmpInst::Predicate Pred) {
14780fca6ea1SDimitry Andric       switch (Pred) {
14790fca6ea1SDimitry Andric       case FCmpInst::FCMP_OLT:
14800fca6ea1SDimitry Andric       case FCmpInst::FCMP_OLE:
14810fca6ea1SDimitry Andric       case FCmpInst::FCMP_ULT:
14820fca6ea1SDimitry Andric       case FCmpInst::FCMP_ULE:
14830fca6ea1SDimitry Andric         return true;
14840fca6ea1SDimitry Andric       default:
14850fca6ea1SDimitry Andric         return false;
14860fca6ea1SDimitry Andric       }
14870fca6ea1SDimitry Andric     };
14880fca6ea1SDimitry Andric     if (IsLessThanOrLessEqual(IsAnd ? PredR : PredL)) {
14890fca6ea1SDimitry Andric       std::swap(LHSC, RHSC);
14900fca6ea1SDimitry Andric       std::swap(PredL, PredR);
14910fca6ea1SDimitry Andric     }
14920fca6ea1SDimitry Andric     if (IsLessThanOrLessEqual(IsAnd ? PredL : PredR)) {
14930fca6ea1SDimitry Andric       BuilderTy::FastMathFlagGuard Guard(Builder);
14940fca6ea1SDimitry Andric       Builder.setFastMathFlags(LHS->getFastMathFlags() |
14950fca6ea1SDimitry Andric                                RHS->getFastMathFlags());
14960fca6ea1SDimitry Andric 
14970fca6ea1SDimitry Andric       Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, LHS0);
14980fca6ea1SDimitry Andric       return Builder.CreateFCmp(PredL, FAbs,
14990fca6ea1SDimitry Andric                                 ConstantFP::get(LHS0->getType(), *LHSC));
15000fca6ea1SDimitry Andric     }
15010fca6ea1SDimitry Andric   }
15020fca6ea1SDimitry Andric 
15030b57cec5SDimitry Andric   return nullptr;
15040b57cec5SDimitry Andric }
15050b57cec5SDimitry Andric 
150606c3fb27SDimitry Andric /// Match an fcmp against a special value that performs a test possible by
150706c3fb27SDimitry Andric /// llvm.is.fpclass.
150806c3fb27SDimitry Andric static bool matchIsFPClassLikeFCmp(Value *Op, Value *&ClassVal,
150906c3fb27SDimitry Andric                                    uint64_t &ClassMask) {
151006c3fb27SDimitry Andric   auto *FCmp = dyn_cast<FCmpInst>(Op);
151106c3fb27SDimitry Andric   if (!FCmp || !FCmp->hasOneUse())
151206c3fb27SDimitry Andric     return false;
151306c3fb27SDimitry Andric 
151406c3fb27SDimitry Andric   std::tie(ClassVal, ClassMask) =
151506c3fb27SDimitry Andric       fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
151606c3fb27SDimitry Andric                       FCmp->getOperand(0), FCmp->getOperand(1));
151706c3fb27SDimitry Andric   return ClassVal != nullptr;
151806c3fb27SDimitry Andric }
151906c3fb27SDimitry Andric 
1520bdd1243dSDimitry Andric /// or (is_fpclass x, mask0), (is_fpclass x, mask1)
1521bdd1243dSDimitry Andric ///     -> is_fpclass x, (mask0 | mask1)
1522bdd1243dSDimitry Andric /// and (is_fpclass x, mask0), (is_fpclass x, mask1)
1523bdd1243dSDimitry Andric ///     -> is_fpclass x, (mask0 & mask1)
1524bdd1243dSDimitry Andric /// xor (is_fpclass x, mask0), (is_fpclass x, mask1)
1525bdd1243dSDimitry Andric ///     -> is_fpclass x, (mask0 ^ mask1)
1526bdd1243dSDimitry Andric Instruction *InstCombinerImpl::foldLogicOfIsFPClass(BinaryOperator &BO,
1527bdd1243dSDimitry Andric                                                     Value *Op0, Value *Op1) {
152806c3fb27SDimitry Andric   Value *ClassVal0 = nullptr;
152906c3fb27SDimitry Andric   Value *ClassVal1 = nullptr;
1530bdd1243dSDimitry Andric   uint64_t ClassMask0, ClassMask1;
1531bdd1243dSDimitry Andric 
153206c3fb27SDimitry Andric   // Restrict to folding one fcmp into one is.fpclass for now, don't introduce a
153306c3fb27SDimitry Andric   // new class.
153406c3fb27SDimitry Andric   //
153506c3fb27SDimitry Andric   // TODO: Support forming is.fpclass out of 2 separate fcmps when codegen is
153606c3fb27SDimitry Andric   // better.
153706c3fb27SDimitry Andric 
153806c3fb27SDimitry Andric   bool IsLHSClass =
153906c3fb27SDimitry Andric       match(Op0, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
154006c3fb27SDimitry Andric                      m_Value(ClassVal0), m_ConstantInt(ClassMask0))));
154106c3fb27SDimitry Andric   bool IsRHSClass =
1542bdd1243dSDimitry Andric       match(Op1, m_OneUse(m_Intrinsic<Intrinsic::is_fpclass>(
154306c3fb27SDimitry Andric                      m_Value(ClassVal1), m_ConstantInt(ClassMask1))));
154406c3fb27SDimitry Andric   if ((((IsLHSClass || matchIsFPClassLikeFCmp(Op0, ClassVal0, ClassMask0)) &&
154506c3fb27SDimitry Andric         (IsRHSClass || matchIsFPClassLikeFCmp(Op1, ClassVal1, ClassMask1)))) &&
154606c3fb27SDimitry Andric       ClassVal0 == ClassVal1) {
1547bdd1243dSDimitry Andric     unsigned NewClassMask;
1548bdd1243dSDimitry Andric     switch (BO.getOpcode()) {
1549bdd1243dSDimitry Andric     case Instruction::And:
1550bdd1243dSDimitry Andric       NewClassMask = ClassMask0 & ClassMask1;
1551bdd1243dSDimitry Andric       break;
1552bdd1243dSDimitry Andric     case Instruction::Or:
1553bdd1243dSDimitry Andric       NewClassMask = ClassMask0 | ClassMask1;
1554bdd1243dSDimitry Andric       break;
1555bdd1243dSDimitry Andric     case Instruction::Xor:
1556bdd1243dSDimitry Andric       NewClassMask = ClassMask0 ^ ClassMask1;
1557bdd1243dSDimitry Andric       break;
1558bdd1243dSDimitry Andric     default:
1559bdd1243dSDimitry Andric       llvm_unreachable("not a binary logic operator");
1560bdd1243dSDimitry Andric     }
1561bdd1243dSDimitry Andric 
156206c3fb27SDimitry Andric     if (IsLHSClass) {
1563bdd1243dSDimitry Andric       auto *II = cast<IntrinsicInst>(Op0);
1564bdd1243dSDimitry Andric       II->setArgOperand(
1565bdd1243dSDimitry Andric           1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
1566bdd1243dSDimitry Andric       return replaceInstUsesWith(BO, II);
1567bdd1243dSDimitry Andric     }
1568bdd1243dSDimitry Andric 
156906c3fb27SDimitry Andric     if (IsRHSClass) {
157006c3fb27SDimitry Andric       auto *II = cast<IntrinsicInst>(Op1);
157106c3fb27SDimitry Andric       II->setArgOperand(
157206c3fb27SDimitry Andric           1, ConstantInt::get(II->getArgOperand(1)->getType(), NewClassMask));
157306c3fb27SDimitry Andric       return replaceInstUsesWith(BO, II);
157406c3fb27SDimitry Andric     }
157506c3fb27SDimitry Andric 
157606c3fb27SDimitry Andric     CallInst *NewClass =
157706c3fb27SDimitry Andric         Builder.CreateIntrinsic(Intrinsic::is_fpclass, {ClassVal0->getType()},
157806c3fb27SDimitry Andric                                 {ClassVal0, Builder.getInt32(NewClassMask)});
157906c3fb27SDimitry Andric     return replaceInstUsesWith(BO, NewClass);
158006c3fb27SDimitry Andric   }
158106c3fb27SDimitry Andric 
1582bdd1243dSDimitry Andric   return nullptr;
1583bdd1243dSDimitry Andric }
1584bdd1243dSDimitry Andric 
1585bdd1243dSDimitry Andric /// Look for the pattern that conditionally negates a value via math operations:
1586bdd1243dSDimitry Andric ///   cond.splat = sext i1 cond
1587bdd1243dSDimitry Andric ///   sub = add cond.splat, x
1588bdd1243dSDimitry Andric ///   xor = xor sub, cond.splat
1589bdd1243dSDimitry Andric /// and rewrite it to do the same, but via logical operations:
1590bdd1243dSDimitry Andric ///   value.neg = sub 0, value
1591bdd1243dSDimitry Andric ///   cond = select i1 neg, value.neg, value
1592bdd1243dSDimitry Andric Instruction *InstCombinerImpl::canonicalizeConditionalNegationViaMathToSelect(
1593bdd1243dSDimitry Andric     BinaryOperator &I) {
1594bdd1243dSDimitry Andric   assert(I.getOpcode() == BinaryOperator::Xor && "Only for xor!");
1595bdd1243dSDimitry Andric   Value *Cond, *X;
1596bdd1243dSDimitry Andric   // As per complexity ordering, `xor` is not commutative here.
1597bdd1243dSDimitry Andric   if (!match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())) ||
1598bdd1243dSDimitry Andric       !match(I.getOperand(1), m_SExt(m_Value(Cond))) ||
1599bdd1243dSDimitry Andric       !Cond->getType()->isIntOrIntVectorTy(1) ||
16000fca6ea1SDimitry Andric       !match(I.getOperand(0), m_c_Add(m_SExt(m_Specific(Cond)), m_Value(X))))
1601bdd1243dSDimitry Andric     return nullptr;
1602bdd1243dSDimitry Andric   return SelectInst::Create(Cond, Builder.CreateNeg(X, X->getName() + ".neg"),
1603bdd1243dSDimitry Andric                             X);
1604bdd1243dSDimitry Andric }
1605bdd1243dSDimitry Andric 
16060b57cec5SDimitry Andric /// This a limited reassociation for a special case (see above) where we are
16070b57cec5SDimitry Andric /// checking if two values are either both NAN (unordered) or not-NAN (ordered).
16080b57cec5SDimitry Andric /// This could be handled more generally in '-reassociation', but it seems like
16090b57cec5SDimitry Andric /// an unlikely pattern for a large number of logic ops and fcmps.
16100b57cec5SDimitry Andric static Instruction *reassociateFCmps(BinaryOperator &BO,
16110b57cec5SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
16120b57cec5SDimitry Andric   Instruction::BinaryOps Opcode = BO.getOpcode();
16130b57cec5SDimitry Andric   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
16140b57cec5SDimitry Andric          "Expecting and/or op for fcmp transform");
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   // There are 4 commuted variants of the pattern. Canonicalize operands of this
16170b57cec5SDimitry Andric   // logic op so an fcmp is operand 0 and a matching logic op is operand 1.
16180b57cec5SDimitry Andric   Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
16190b57cec5SDimitry Andric   FCmpInst::Predicate Pred;
16200b57cec5SDimitry Andric   if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
16210b57cec5SDimitry Andric     std::swap(Op0, Op1);
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   // Match inner binop and the predicate for combining 2 NAN checks into 1.
1624349cc55cSDimitry Andric   Value *BO10, *BO11;
16250b57cec5SDimitry Andric   FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
16260b57cec5SDimitry Andric                                                            : FCmpInst::FCMP_UNO;
16270b57cec5SDimitry Andric   if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
1628349cc55cSDimitry Andric       !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
16290b57cec5SDimitry Andric     return nullptr;
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric   // The inner logic op must have a matching fcmp operand.
1632349cc55cSDimitry Andric   Value *Y;
16330b57cec5SDimitry Andric   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
16340b57cec5SDimitry Andric       Pred != NanPred || X->getType() != Y->getType())
16350b57cec5SDimitry Andric     std::swap(BO10, BO11);
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
16380b57cec5SDimitry Andric       Pred != NanPred || X->getType() != Y->getType())
16390b57cec5SDimitry Andric     return nullptr;
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z
16420b57cec5SDimitry Andric   // or  (fcmp uno X, 0), (or  (fcmp uno Y, 0), Z) --> or  (fcmp uno X, Y), Z
16430b57cec5SDimitry Andric   Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
16440b57cec5SDimitry Andric   if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
16450b57cec5SDimitry Andric     // Intersect FMF from the 2 source fcmps.
16460b57cec5SDimitry Andric     NewFCmpInst->copyIRFlags(Op0);
16470b57cec5SDimitry Andric     NewFCmpInst->andIRFlags(BO10);
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric   return BinaryOperator::Create(Opcode, NewFCmp, BO11);
16500b57cec5SDimitry Andric }
16510b57cec5SDimitry Andric 
1652349cc55cSDimitry Andric /// Match variations of De Morgan's Laws:
16530b57cec5SDimitry Andric /// (~A & ~B) == (~(A | B))
16540b57cec5SDimitry Andric /// (~A | ~B) == (~(A & B))
16550b57cec5SDimitry Andric static Instruction *matchDeMorgansLaws(BinaryOperator &I,
16565f757f3fSDimitry Andric                                        InstCombiner &IC) {
1657349cc55cSDimitry Andric   const Instruction::BinaryOps Opcode = I.getOpcode();
16580b57cec5SDimitry Andric   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
16590b57cec5SDimitry Andric          "Trying to match De Morgan's Laws with something other than and/or");
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   // Flip the logic operation.
1662349cc55cSDimitry Andric   const Instruction::BinaryOps FlippedOpcode =
1663349cc55cSDimitry Andric       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
16640b57cec5SDimitry Andric 
1665349cc55cSDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
16660b57cec5SDimitry Andric   Value *A, *B;
1667349cc55cSDimitry Andric   if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
1668349cc55cSDimitry Andric       match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
16695f757f3fSDimitry Andric       !IC.isFreeToInvert(A, A->hasOneUse()) &&
16705f757f3fSDimitry Andric       !IC.isFreeToInvert(B, B->hasOneUse())) {
1671349cc55cSDimitry Andric     Value *AndOr =
16725f757f3fSDimitry Andric         IC.Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
16730b57cec5SDimitry Andric     return BinaryOperator::CreateNot(AndOr);
16740b57cec5SDimitry Andric   }
16750b57cec5SDimitry Andric 
1676349cc55cSDimitry Andric   // The 'not' ops may require reassociation.
1677349cc55cSDimitry Andric   // (A & ~B) & ~C --> A & ~(B | C)
1678349cc55cSDimitry Andric   // (~B & A) & ~C --> A & ~(B | C)
1679349cc55cSDimitry Andric   // (A | ~B) | ~C --> A | ~(B & C)
1680349cc55cSDimitry Andric   // (~B | A) | ~C --> A | ~(B & C)
1681349cc55cSDimitry Andric   Value *C;
1682349cc55cSDimitry Andric   if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
1683349cc55cSDimitry Andric       match(Op1, m_Not(m_Value(C)))) {
16845f757f3fSDimitry Andric     Value *FlippedBO = IC.Builder.CreateBinOp(FlippedOpcode, B, C);
16855f757f3fSDimitry Andric     return BinaryOperator::Create(Opcode, A, IC.Builder.CreateNot(FlippedBO));
1686349cc55cSDimitry Andric   }
1687349cc55cSDimitry Andric 
16880b57cec5SDimitry Andric   return nullptr;
16890b57cec5SDimitry Andric }
16900b57cec5SDimitry Andric 
1691e8d8bef9SDimitry Andric bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
16920b57cec5SDimitry Andric   Value *CastSrc = CI->getOperand(0);
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   // Noop casts and casts of constants should be eliminated trivially.
16950b57cec5SDimitry Andric   if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
16960b57cec5SDimitry Andric     return false;
16970b57cec5SDimitry Andric 
16980b57cec5SDimitry Andric   // If this cast is paired with another cast that can be eliminated, we prefer
16990b57cec5SDimitry Andric   // to have it eliminated.
17000b57cec5SDimitry Andric   if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
17010b57cec5SDimitry Andric     if (isEliminableCastPair(PrecedingCI, CI))
17020b57cec5SDimitry Andric       return false;
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric   return true;
17050b57cec5SDimitry Andric }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric /// Fold {and,or,xor} (cast X), C.
17080b57cec5SDimitry Andric static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
17095f757f3fSDimitry Andric                                           InstCombinerImpl &IC) {
17100b57cec5SDimitry Andric   Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
17110b57cec5SDimitry Andric   if (!C)
17120b57cec5SDimitry Andric     return nullptr;
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric   auto LogicOpc = Logic.getOpcode();
17150b57cec5SDimitry Andric   Type *DestTy = Logic.getType();
17160b57cec5SDimitry Andric   Type *SrcTy = Cast->getSrcTy();
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   // Move the logic operation ahead of a zext or sext if the constant is
17190b57cec5SDimitry Andric   // unchanged in the smaller source type. Performing the logic in a smaller
17200b57cec5SDimitry Andric   // type may provide more information to later folds, and the smaller logic
17210b57cec5SDimitry Andric   // instruction may be cheaper (particularly in the case of vectors).
17220b57cec5SDimitry Andric   Value *X;
17230b57cec5SDimitry Andric   if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
17245f757f3fSDimitry Andric     if (Constant *TruncC = IC.getLosslessUnsignedTrunc(C, SrcTy)) {
17250b57cec5SDimitry Andric       // LogicOpc (zext X), C --> zext (LogicOpc X, C)
17265f757f3fSDimitry Andric       Value *NewOp = IC.Builder.CreateBinOp(LogicOpc, X, TruncC);
17270b57cec5SDimitry Andric       return new ZExtInst(NewOp, DestTy);
17280b57cec5SDimitry Andric     }
17290b57cec5SDimitry Andric   }
17300b57cec5SDimitry Andric 
17310fca6ea1SDimitry Andric   if (match(Cast, m_OneUse(m_SExtLike(m_Value(X))))) {
17325f757f3fSDimitry Andric     if (Constant *TruncC = IC.getLosslessSignedTrunc(C, SrcTy)) {
17330b57cec5SDimitry Andric       // LogicOpc (sext X), C --> sext (LogicOpc X, C)
17345f757f3fSDimitry Andric       Value *NewOp = IC.Builder.CreateBinOp(LogicOpc, X, TruncC);
17350b57cec5SDimitry Andric       return new SExtInst(NewOp, DestTy);
17360b57cec5SDimitry Andric     }
17370b57cec5SDimitry Andric   }
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric   return nullptr;
17400b57cec5SDimitry Andric }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric /// Fold {and,or,xor} (cast X), Y.
1743e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
17440b57cec5SDimitry Andric   auto LogicOpc = I.getOpcode();
17450b57cec5SDimitry Andric   assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
174806c3fb27SDimitry Andric 
174906c3fb27SDimitry Andric   // fold bitwise(A >> BW - 1, zext(icmp))     (BW is the scalar bits of the
175006c3fb27SDimitry Andric   // type of A)
175106c3fb27SDimitry Andric   //   -> bitwise(zext(A < 0), zext(icmp))
175206c3fb27SDimitry Andric   //   -> zext(bitwise(A < 0, icmp))
175306c3fb27SDimitry Andric   auto FoldBitwiseICmpZeroWithICmp = [&](Value *Op0,
175406c3fb27SDimitry Andric                                          Value *Op1) -> Instruction * {
175506c3fb27SDimitry Andric     ICmpInst::Predicate Pred;
175606c3fb27SDimitry Andric     Value *A;
175706c3fb27SDimitry Andric     bool IsMatched =
175806c3fb27SDimitry Andric         match(Op0,
175906c3fb27SDimitry Andric               m_OneUse(m_LShr(
176006c3fb27SDimitry Andric                   m_Value(A),
176106c3fb27SDimitry Andric                   m_SpecificInt(Op0->getType()->getScalarSizeInBits() - 1)))) &&
176206c3fb27SDimitry Andric         match(Op1, m_OneUse(m_ZExt(m_ICmp(Pred, m_Value(), m_Value()))));
176306c3fb27SDimitry Andric 
176406c3fb27SDimitry Andric     if (!IsMatched)
176506c3fb27SDimitry Andric       return nullptr;
176606c3fb27SDimitry Andric 
176706c3fb27SDimitry Andric     auto *ICmpL =
176806c3fb27SDimitry Andric         Builder.CreateICmpSLT(A, Constant::getNullValue(A->getType()));
176906c3fb27SDimitry Andric     auto *ICmpR = cast<ZExtInst>(Op1)->getOperand(0);
177006c3fb27SDimitry Andric     auto *BitwiseOp = Builder.CreateBinOp(LogicOpc, ICmpL, ICmpR);
177106c3fb27SDimitry Andric 
177206c3fb27SDimitry Andric     return new ZExtInst(BitwiseOp, Op0->getType());
177306c3fb27SDimitry Andric   };
177406c3fb27SDimitry Andric 
177506c3fb27SDimitry Andric   if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op0, Op1))
177606c3fb27SDimitry Andric     return Ret;
177706c3fb27SDimitry Andric 
177806c3fb27SDimitry Andric   if (auto *Ret = FoldBitwiseICmpZeroWithICmp(Op1, Op0))
177906c3fb27SDimitry Andric     return Ret;
178006c3fb27SDimitry Andric 
17810b57cec5SDimitry Andric   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
17820b57cec5SDimitry Andric   if (!Cast0)
17830b57cec5SDimitry Andric     return nullptr;
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   // This must be a cast from an integer or integer vector source type to allow
17860b57cec5SDimitry Andric   // transformation of the logic operation to the source type.
17870b57cec5SDimitry Andric   Type *DestTy = I.getType();
17880b57cec5SDimitry Andric   Type *SrcTy = Cast0->getSrcTy();
17890b57cec5SDimitry Andric   if (!SrcTy->isIntOrIntVectorTy())
17900b57cec5SDimitry Andric     return nullptr;
17910b57cec5SDimitry Andric 
17925f757f3fSDimitry Andric   if (Instruction *Ret = foldLogicCastConstant(I, Cast0, *this))
17930b57cec5SDimitry Andric     return Ret;
17940b57cec5SDimitry Andric 
17950b57cec5SDimitry Andric   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
17960b57cec5SDimitry Andric   if (!Cast1)
17970b57cec5SDimitry Andric     return nullptr;
17980b57cec5SDimitry Andric 
1799bdd1243dSDimitry Andric   // Both operands of the logic operation are casts. The casts must be the
1800bdd1243dSDimitry Andric   // same kind for reduction.
1801bdd1243dSDimitry Andric   Instruction::CastOps CastOpcode = Cast0->getOpcode();
1802bdd1243dSDimitry Andric   if (CastOpcode != Cast1->getOpcode())
18030b57cec5SDimitry Andric     return nullptr;
18040b57cec5SDimitry Andric 
1805bdd1243dSDimitry Andric   // If the source types do not match, but the casts are matching extends, we
1806bdd1243dSDimitry Andric   // can still narrow the logic op.
1807bdd1243dSDimitry Andric   if (SrcTy != Cast1->getSrcTy()) {
1808bdd1243dSDimitry Andric     Value *X, *Y;
1809bdd1243dSDimitry Andric     if (match(Cast0, m_OneUse(m_ZExtOrSExt(m_Value(X)))) &&
1810bdd1243dSDimitry Andric         match(Cast1, m_OneUse(m_ZExtOrSExt(m_Value(Y))))) {
1811bdd1243dSDimitry Andric       // Cast the narrower source to the wider source type.
1812bdd1243dSDimitry Andric       unsigned XNumBits = X->getType()->getScalarSizeInBits();
1813bdd1243dSDimitry Andric       unsigned YNumBits = Y->getType()->getScalarSizeInBits();
1814bdd1243dSDimitry Andric       if (XNumBits < YNumBits)
1815bdd1243dSDimitry Andric         X = Builder.CreateCast(CastOpcode, X, Y->getType());
1816bdd1243dSDimitry Andric       else
1817bdd1243dSDimitry Andric         Y = Builder.CreateCast(CastOpcode, Y, X->getType());
1818bdd1243dSDimitry Andric       // Do the logic op in the intermediate width, then widen more.
1819bdd1243dSDimitry Andric       Value *NarrowLogic = Builder.CreateBinOp(LogicOpc, X, Y);
1820bdd1243dSDimitry Andric       return CastInst::Create(CastOpcode, NarrowLogic, DestTy);
1821bdd1243dSDimitry Andric     }
1822bdd1243dSDimitry Andric 
1823bdd1243dSDimitry Andric     // Give up for other cast opcodes.
1824bdd1243dSDimitry Andric     return nullptr;
1825bdd1243dSDimitry Andric   }
1826bdd1243dSDimitry Andric 
18270b57cec5SDimitry Andric   Value *Cast0Src = Cast0->getOperand(0);
18280b57cec5SDimitry Andric   Value *Cast1Src = Cast1->getOperand(0);
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric   // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
183181ad6265SDimitry Andric   if ((Cast0->hasOneUse() || Cast1->hasOneUse()) &&
183281ad6265SDimitry Andric       shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
18330b57cec5SDimitry Andric     Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
18340b57cec5SDimitry Andric                                        I.getName());
18350b57cec5SDimitry Andric     return CastInst::Create(CastOpcode, NewOp, DestTy);
18360b57cec5SDimitry Andric   }
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   return nullptr;
18390b57cec5SDimitry Andric }
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric static Instruction *foldAndToXor(BinaryOperator &I,
18420b57cec5SDimitry Andric                                  InstCombiner::BuilderTy &Builder) {
18430b57cec5SDimitry Andric   assert(I.getOpcode() == Instruction::And);
18440b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0);
18450b57cec5SDimitry Andric   Value *Op1 = I.getOperand(1);
18460b57cec5SDimitry Andric   Value *A, *B;
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric   // Operand complexity canonicalization guarantees that the 'or' is Op0.
18490b57cec5SDimitry Andric   // (A | B) & ~(A & B) --> A ^ B
18500b57cec5SDimitry Andric   // (A | B) & ~(B & A) --> A ^ B
18510b57cec5SDimitry Andric   if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
18520b57cec5SDimitry Andric                         m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
18530b57cec5SDimitry Andric     return BinaryOperator::CreateXor(A, B);
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric   // (A | ~B) & (~A | B) --> ~(A ^ B)
18560b57cec5SDimitry Andric   // (A | ~B) & (B | ~A) --> ~(A ^ B)
18570b57cec5SDimitry Andric   // (~B | A) & (~A | B) --> ~(A ^ B)
18580b57cec5SDimitry Andric   // (~B | A) & (B | ~A) --> ~(A ^ B)
18590b57cec5SDimitry Andric   if (Op0->hasOneUse() || Op1->hasOneUse())
18600b57cec5SDimitry Andric     if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
18610b57cec5SDimitry Andric                           m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
18620b57cec5SDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   return nullptr;
18650b57cec5SDimitry Andric }
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric static Instruction *foldOrToXor(BinaryOperator &I,
18680b57cec5SDimitry Andric                                 InstCombiner::BuilderTy &Builder) {
18690b57cec5SDimitry Andric   assert(I.getOpcode() == Instruction::Or);
18700b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0);
18710b57cec5SDimitry Andric   Value *Op1 = I.getOperand(1);
18720b57cec5SDimitry Andric   Value *A, *B;
18730b57cec5SDimitry Andric 
18740b57cec5SDimitry Andric   // Operand complexity canonicalization guarantees that the 'and' is Op0.
18750b57cec5SDimitry Andric   // (A & B) | ~(A | B) --> ~(A ^ B)
18760b57cec5SDimitry Andric   // (A & B) | ~(B | A) --> ~(A ^ B)
18770b57cec5SDimitry Andric   if (Op0->hasOneUse() || Op1->hasOneUse())
18780b57cec5SDimitry Andric     if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
18790b57cec5SDimitry Andric         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
18800b57cec5SDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
18810b57cec5SDimitry Andric 
1882e8d8bef9SDimitry Andric   // Operand complexity canonicalization guarantees that the 'xor' is Op0.
1883e8d8bef9SDimitry Andric   // (A ^ B) | ~(A | B) --> ~(A & B)
1884e8d8bef9SDimitry Andric   // (A ^ B) | ~(B | A) --> ~(A & B)
1885e8d8bef9SDimitry Andric   if (Op0->hasOneUse() || Op1->hasOneUse())
1886e8d8bef9SDimitry Andric     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1887e8d8bef9SDimitry Andric         match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1888e8d8bef9SDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
1889e8d8bef9SDimitry Andric 
18900b57cec5SDimitry Andric   // (A & ~B) | (~A & B) --> A ^ B
18910b57cec5SDimitry Andric   // (A & ~B) | (B & ~A) --> A ^ B
18920b57cec5SDimitry Andric   // (~B & A) | (~A & B) --> A ^ B
18930b57cec5SDimitry Andric   // (~B & A) | (B & ~A) --> A ^ B
18940b57cec5SDimitry Andric   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
18950b57cec5SDimitry Andric       match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
18960b57cec5SDimitry Andric     return BinaryOperator::CreateXor(A, B);
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric   return nullptr;
18990b57cec5SDimitry Andric }
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric /// Return true if a constant shift amount is always less than the specified
19020b57cec5SDimitry Andric /// bit-width. If not, the shift could create poison in the narrower type.
19030b57cec5SDimitry Andric static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
1904e8d8bef9SDimitry Andric   APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
1905e8d8bef9SDimitry Andric   return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
19060b57cec5SDimitry Andric }
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and
19090b57cec5SDimitry Andric /// a common zext operand: and (binop (zext X), C), (zext X).
1910e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
19110b57cec5SDimitry Andric   // This transform could also apply to {or, and, xor}, but there are better
19120b57cec5SDimitry Andric   // folds for those cases, so we don't expect those patterns here. AShr is not
19130b57cec5SDimitry Andric   // handled because it should always be transformed to LShr in this sequence.
19140b57cec5SDimitry Andric   // The subtract transform is different because it has a constant on the left.
19150b57cec5SDimitry Andric   // Add/mul commute the constant to RHS; sub with constant RHS becomes add.
19160b57cec5SDimitry Andric   Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
19170b57cec5SDimitry Andric   Constant *C;
19180b57cec5SDimitry Andric   if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
19190b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
19200b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
19210b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
19220b57cec5SDimitry Andric       !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
19230b57cec5SDimitry Andric     return nullptr;
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric   Value *X;
19260b57cec5SDimitry Andric   if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
19270b57cec5SDimitry Andric     return nullptr;
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   Type *Ty = And.getType();
19300b57cec5SDimitry Andric   if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
19310b57cec5SDimitry Andric     return nullptr;
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric   // If we're narrowing a shift, the shift amount must be safe (less than the
19340b57cec5SDimitry Andric   // width) in the narrower type. If the shift amount is greater, instsimplify
19350b57cec5SDimitry Andric   // usually handles that case, but we can't guarantee/assert it.
19360b57cec5SDimitry Andric   Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
19370b57cec5SDimitry Andric   if (Opc == Instruction::LShr || Opc == Instruction::Shl)
19380b57cec5SDimitry Andric     if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
19390b57cec5SDimitry Andric       return nullptr;
19400b57cec5SDimitry Andric 
19410b57cec5SDimitry Andric   // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X)
19420b57cec5SDimitry Andric   // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X)
19430b57cec5SDimitry Andric   Value *NewC = ConstantExpr::getTrunc(C, X->getType());
19440b57cec5SDimitry Andric   Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
19450b57cec5SDimitry Andric                                          : Builder.CreateBinOp(Opc, X, NewC);
19460b57cec5SDimitry Andric   return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
19470b57cec5SDimitry Andric }
19480b57cec5SDimitry Andric 
1949349cc55cSDimitry Andric /// Try folding relatively complex patterns for both And and Or operations
1950349cc55cSDimitry Andric /// with all And and Or swapped.
1951349cc55cSDimitry Andric static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
1952349cc55cSDimitry Andric                                              InstCombiner::BuilderTy &Builder) {
1953349cc55cSDimitry Andric   const Instruction::BinaryOps Opcode = I.getOpcode();
1954349cc55cSDimitry Andric   assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1955349cc55cSDimitry Andric 
1956349cc55cSDimitry Andric   // Flip the logic operation.
1957349cc55cSDimitry Andric   const Instruction::BinaryOps FlippedOpcode =
1958349cc55cSDimitry Andric       (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1959349cc55cSDimitry Andric 
1960349cc55cSDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
196104eeddc0SDimitry Andric   Value *A, *B, *C, *X, *Y, *Dummy;
196204eeddc0SDimitry Andric 
196304eeddc0SDimitry Andric   // Match following expressions:
196404eeddc0SDimitry Andric   // (~(A | B) & C)
196504eeddc0SDimitry Andric   // (~(A & B) | C)
196604eeddc0SDimitry Andric   // Captures X = ~(A | B) or ~(A & B)
196704eeddc0SDimitry Andric   const auto matchNotOrAnd =
196804eeddc0SDimitry Andric       [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
196904eeddc0SDimitry Andric                               Value *&X, bool CountUses = false) -> bool {
197004eeddc0SDimitry Andric     if (CountUses && !Op->hasOneUse())
197104eeddc0SDimitry Andric       return false;
197204eeddc0SDimitry Andric 
197304eeddc0SDimitry Andric     if (match(Op, m_c_BinOp(FlippedOpcode,
197404eeddc0SDimitry Andric                             m_CombineAnd(m_Value(X),
197504eeddc0SDimitry Andric                                          m_Not(m_c_BinOp(Opcode, m_A, m_B))),
197604eeddc0SDimitry Andric                             m_C)))
197704eeddc0SDimitry Andric       return !CountUses || X->hasOneUse();
197804eeddc0SDimitry Andric 
197904eeddc0SDimitry Andric     return false;
198004eeddc0SDimitry Andric   };
1981349cc55cSDimitry Andric 
1982349cc55cSDimitry Andric   // (~(A | B) & C) | ... --> ...
1983349cc55cSDimitry Andric   // (~(A & B) | C) & ... --> ...
1984349cc55cSDimitry Andric   // TODO: One use checks are conservative. We just need to check that a total
1985349cc55cSDimitry Andric   //       number of multiple used values does not exceed reduction
1986349cc55cSDimitry Andric   //       in operations.
198704eeddc0SDimitry Andric   if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
1988349cc55cSDimitry Andric     // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A
1989349cc55cSDimitry Andric     // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A)
199004eeddc0SDimitry Andric     if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
199104eeddc0SDimitry Andric                       true)) {
1992349cc55cSDimitry Andric       Value *Xor = Builder.CreateXor(B, C);
1993349cc55cSDimitry Andric       return (Opcode == Instruction::Or)
1994349cc55cSDimitry Andric                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
1995349cc55cSDimitry Andric                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
1996349cc55cSDimitry Andric     }
1997349cc55cSDimitry Andric 
1998349cc55cSDimitry Andric     // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B
1999349cc55cSDimitry Andric     // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B)
200004eeddc0SDimitry Andric     if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
200104eeddc0SDimitry Andric                       true)) {
2002349cc55cSDimitry Andric       Value *Xor = Builder.CreateXor(A, C);
2003349cc55cSDimitry Andric       return (Opcode == Instruction::Or)
2004349cc55cSDimitry Andric                  ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
2005349cc55cSDimitry Andric                  : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
2006349cc55cSDimitry Andric     }
2007349cc55cSDimitry Andric 
2008349cc55cSDimitry Andric     // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A)
2009349cc55cSDimitry Andric     // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A)
2010349cc55cSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
2011349cc55cSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
2012349cc55cSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateBinOp(
2013349cc55cSDimitry Andric           Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
2014349cc55cSDimitry Andric 
2015349cc55cSDimitry Andric     // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B)
2016349cc55cSDimitry Andric     // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B)
2017349cc55cSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
2018349cc55cSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
2019349cc55cSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateBinOp(
2020349cc55cSDimitry Andric           Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
20214824e7fdSDimitry Andric 
20224824e7fdSDimitry Andric     // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B)))
20234824e7fdSDimitry Andric     // Note, the pattern with swapped and/or is not handled because the
20244824e7fdSDimitry Andric     // result is more undefined than a source:
20254824e7fdSDimitry Andric     // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid.
20264824e7fdSDimitry Andric     if (Opcode == Instruction::Or && Op0->hasOneUse() &&
20274824e7fdSDimitry Andric         match(Op1, m_OneUse(m_Not(m_CombineAnd(
20284824e7fdSDimitry Andric                        m_Value(Y),
20294824e7fdSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(C),
20304824e7fdSDimitry Andric                                  m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
20314824e7fdSDimitry Andric       // X = ~(A | B)
20324824e7fdSDimitry Andric       // Y = (C | (A ^ B)
20334824e7fdSDimitry Andric       Value *Or = cast<BinaryOperator>(X)->getOperand(0);
20344824e7fdSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
20354824e7fdSDimitry Andric     }
2036349cc55cSDimitry Andric   }
2037349cc55cSDimitry Andric 
20380eae32dcSDimitry Andric   // (~A & B & C) | ... --> ...
20390eae32dcSDimitry Andric   // (~A | B | C) | ... --> ...
20400eae32dcSDimitry Andric   // TODO: One use checks are conservative. We just need to check that a total
20410eae32dcSDimitry Andric   //       number of multiple used values does not exceed reduction
20420eae32dcSDimitry Andric   //       in operations.
20430eae32dcSDimitry Andric   if (match(Op0,
20440eae32dcSDimitry Andric             m_OneUse(m_c_BinOp(FlippedOpcode,
20450eae32dcSDimitry Andric                                m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
20460eae32dcSDimitry Andric                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
20470eae32dcSDimitry Andric       match(Op0, m_OneUse(m_c_BinOp(
20480eae32dcSDimitry Andric                      FlippedOpcode,
20490eae32dcSDimitry Andric                      m_c_BinOp(FlippedOpcode, m_Value(C),
20500eae32dcSDimitry Andric                                m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
20510eae32dcSDimitry Andric                      m_Value(B))))) {
20520eae32dcSDimitry Andric     // X = ~A
20530eae32dcSDimitry Andric     // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C))
20540eae32dcSDimitry Andric     // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C))
20550eae32dcSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
20560eae32dcSDimitry Andric                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
20570eae32dcSDimitry Andric                        m_Specific(C))))) ||
20580eae32dcSDimitry Andric         match(Op1, m_OneUse(m_Not(m_c_BinOp(
20590eae32dcSDimitry Andric                        Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
20600eae32dcSDimitry Andric                        m_Specific(A))))) ||
20610eae32dcSDimitry Andric         match(Op1, m_OneUse(m_Not(m_c_BinOp(
20620eae32dcSDimitry Andric                        Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
20630eae32dcSDimitry Andric                        m_Specific(B)))))) {
20640eae32dcSDimitry Andric       Value *Xor = Builder.CreateXor(B, C);
20650eae32dcSDimitry Andric       return (Opcode == Instruction::Or)
20660eae32dcSDimitry Andric                  ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
20670eae32dcSDimitry Andric                  : BinaryOperator::CreateOr(Xor, X);
20680eae32dcSDimitry Andric     }
20690eae32dcSDimitry Andric 
20700eae32dcSDimitry Andric     // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A
20710eae32dcSDimitry Andric     // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A
20720eae32dcSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
20730eae32dcSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
20740eae32dcSDimitry Andric       return BinaryOperator::Create(
20750eae32dcSDimitry Andric           FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
20760eae32dcSDimitry Andric           X);
20770eae32dcSDimitry Andric 
20780eae32dcSDimitry Andric     // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A
20790eae32dcSDimitry Andric     // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A
20800eae32dcSDimitry Andric     if (match(Op1, m_OneUse(m_Not(m_OneUse(
20810eae32dcSDimitry Andric                        m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
20820eae32dcSDimitry Andric       return BinaryOperator::Create(
20830eae32dcSDimitry Andric           FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
20840eae32dcSDimitry Andric           X);
20850eae32dcSDimitry Andric   }
20860eae32dcSDimitry Andric 
2087349cc55cSDimitry Andric   return nullptr;
2088349cc55cSDimitry Andric }
2089349cc55cSDimitry Andric 
2090bdd1243dSDimitry Andric /// Try to reassociate a pair of binops so that values with one use only are
2091bdd1243dSDimitry Andric /// part of the same instruction. This may enable folds that are limited with
2092bdd1243dSDimitry Andric /// multi-use restrictions and makes it more likely to match other patterns that
2093bdd1243dSDimitry Andric /// are looking for a common operand.
2094bdd1243dSDimitry Andric static Instruction *reassociateForUses(BinaryOperator &BO,
2095bdd1243dSDimitry Andric                                        InstCombinerImpl::BuilderTy &Builder) {
2096bdd1243dSDimitry Andric   Instruction::BinaryOps Opcode = BO.getOpcode();
2097bdd1243dSDimitry Andric   Value *X, *Y, *Z;
2098bdd1243dSDimitry Andric   if (match(&BO,
2099bdd1243dSDimitry Andric             m_c_BinOp(Opcode, m_OneUse(m_BinOp(Opcode, m_Value(X), m_Value(Y))),
2100bdd1243dSDimitry Andric                       m_OneUse(m_Value(Z))))) {
2101bdd1243dSDimitry Andric     if (!isa<Constant>(X) && !isa<Constant>(Y) && !isa<Constant>(Z)) {
2102bdd1243dSDimitry Andric       // (X op Y) op Z --> (Y op Z) op X
2103bdd1243dSDimitry Andric       if (!X->hasOneUse()) {
2104bdd1243dSDimitry Andric         Value *YZ = Builder.CreateBinOp(Opcode, Y, Z);
2105bdd1243dSDimitry Andric         return BinaryOperator::Create(Opcode, YZ, X);
2106bdd1243dSDimitry Andric       }
2107bdd1243dSDimitry Andric       // (X op Y) op Z --> (X op Z) op Y
2108bdd1243dSDimitry Andric       if (!Y->hasOneUse()) {
2109bdd1243dSDimitry Andric         Value *XZ = Builder.CreateBinOp(Opcode, X, Z);
2110bdd1243dSDimitry Andric         return BinaryOperator::Create(Opcode, XZ, Y);
2111bdd1243dSDimitry Andric       }
2112bdd1243dSDimitry Andric     }
2113bdd1243dSDimitry Andric   }
2114bdd1243dSDimitry Andric 
2115bdd1243dSDimitry Andric   return nullptr;
2116bdd1243dSDimitry Andric }
2117bdd1243dSDimitry Andric 
2118bdd1243dSDimitry Andric // Match
2119bdd1243dSDimitry Andric // (X + C2) | C
2120bdd1243dSDimitry Andric // (X + C2) ^ C
2121bdd1243dSDimitry Andric // (X + C2) & C
2122bdd1243dSDimitry Andric // and convert to do the bitwise logic first:
2123bdd1243dSDimitry Andric // (X | C) + C2
2124bdd1243dSDimitry Andric // (X ^ C) + C2
2125bdd1243dSDimitry Andric // (X & C) + C2
2126bdd1243dSDimitry Andric // iff bits affected by logic op are lower than last bit affected by math op
2127bdd1243dSDimitry Andric static Instruction *canonicalizeLogicFirst(BinaryOperator &I,
2128bdd1243dSDimitry Andric                                            InstCombiner::BuilderTy &Builder) {
2129bdd1243dSDimitry Andric   Type *Ty = I.getType();
2130bdd1243dSDimitry Andric   Instruction::BinaryOps OpC = I.getOpcode();
2131bdd1243dSDimitry Andric   Value *Op0 = I.getOperand(0);
2132bdd1243dSDimitry Andric   Value *Op1 = I.getOperand(1);
2133bdd1243dSDimitry Andric   Value *X;
2134bdd1243dSDimitry Andric   const APInt *C, *C2;
2135bdd1243dSDimitry Andric 
2136bdd1243dSDimitry Andric   if (!(match(Op0, m_OneUse(m_Add(m_Value(X), m_APInt(C2)))) &&
2137bdd1243dSDimitry Andric         match(Op1, m_APInt(C))))
2138bdd1243dSDimitry Andric     return nullptr;
2139bdd1243dSDimitry Andric 
2140bdd1243dSDimitry Andric   unsigned Width = Ty->getScalarSizeInBits();
214106c3fb27SDimitry Andric   unsigned LastOneMath = Width - C2->countr_zero();
2142bdd1243dSDimitry Andric 
2143bdd1243dSDimitry Andric   switch (OpC) {
2144bdd1243dSDimitry Andric   case Instruction::And:
214506c3fb27SDimitry Andric     if (C->countl_one() < LastOneMath)
2146bdd1243dSDimitry Andric       return nullptr;
2147bdd1243dSDimitry Andric     break;
2148bdd1243dSDimitry Andric   case Instruction::Xor:
2149bdd1243dSDimitry Andric   case Instruction::Or:
215006c3fb27SDimitry Andric     if (C->countl_zero() < LastOneMath)
2151bdd1243dSDimitry Andric       return nullptr;
2152bdd1243dSDimitry Andric     break;
2153bdd1243dSDimitry Andric   default:
2154bdd1243dSDimitry Andric     llvm_unreachable("Unexpected BinaryOp!");
2155bdd1243dSDimitry Andric   }
2156bdd1243dSDimitry Andric 
2157bdd1243dSDimitry Andric   Value *NewBinOp = Builder.CreateBinOp(OpC, X, ConstantInt::get(Ty, *C));
215806c3fb27SDimitry Andric   return BinaryOperator::CreateWithCopiedFlags(Instruction::Add, NewBinOp,
215906c3fb27SDimitry Andric                                                ConstantInt::get(Ty, *C2), Op0);
216006c3fb27SDimitry Andric }
216106c3fb27SDimitry Andric 
216206c3fb27SDimitry Andric // binop(shift(ShiftedC1, ShAmt), shift(ShiftedC2, add(ShAmt, AddC))) ->
216306c3fb27SDimitry Andric // shift(binop(ShiftedC1, shift(ShiftedC2, AddC)), ShAmt)
216406c3fb27SDimitry Andric // where both shifts are the same and AddC is a valid shift amount.
216506c3fb27SDimitry Andric Instruction *InstCombinerImpl::foldBinOpOfDisplacedShifts(BinaryOperator &I) {
216606c3fb27SDimitry Andric   assert((I.isBitwiseLogicOp() || I.getOpcode() == Instruction::Add) &&
216706c3fb27SDimitry Andric          "Unexpected opcode");
216806c3fb27SDimitry Andric 
216906c3fb27SDimitry Andric   Value *ShAmt;
217006c3fb27SDimitry Andric   Constant *ShiftedC1, *ShiftedC2, *AddC;
217106c3fb27SDimitry Andric   Type *Ty = I.getType();
217206c3fb27SDimitry Andric   unsigned BitWidth = Ty->getScalarSizeInBits();
21735f757f3fSDimitry Andric   if (!match(&I, m_c_BinOp(m_Shift(m_ImmConstant(ShiftedC1), m_Value(ShAmt)),
217406c3fb27SDimitry Andric                            m_Shift(m_ImmConstant(ShiftedC2),
21755f757f3fSDimitry Andric                                    m_AddLike(m_Deferred(ShAmt),
21765f757f3fSDimitry Andric                                              m_ImmConstant(AddC))))))
217706c3fb27SDimitry Andric     return nullptr;
217806c3fb27SDimitry Andric 
217906c3fb27SDimitry Andric   // Make sure the add constant is a valid shift amount.
218006c3fb27SDimitry Andric   if (!match(AddC,
218106c3fb27SDimitry Andric              m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(BitWidth, BitWidth))))
218206c3fb27SDimitry Andric     return nullptr;
218306c3fb27SDimitry Andric 
218406c3fb27SDimitry Andric   // Avoid constant expressions.
218506c3fb27SDimitry Andric   auto *Op0Inst = dyn_cast<Instruction>(I.getOperand(0));
218606c3fb27SDimitry Andric   auto *Op1Inst = dyn_cast<Instruction>(I.getOperand(1));
218706c3fb27SDimitry Andric   if (!Op0Inst || !Op1Inst)
218806c3fb27SDimitry Andric     return nullptr;
218906c3fb27SDimitry Andric 
219006c3fb27SDimitry Andric   // Both shifts must be the same.
219106c3fb27SDimitry Andric   Instruction::BinaryOps ShiftOp =
219206c3fb27SDimitry Andric       static_cast<Instruction::BinaryOps>(Op0Inst->getOpcode());
219306c3fb27SDimitry Andric   if (ShiftOp != Op1Inst->getOpcode())
219406c3fb27SDimitry Andric     return nullptr;
219506c3fb27SDimitry Andric 
219606c3fb27SDimitry Andric   // For adds, only left shifts are supported.
219706c3fb27SDimitry Andric   if (I.getOpcode() == Instruction::Add && ShiftOp != Instruction::Shl)
219806c3fb27SDimitry Andric     return nullptr;
219906c3fb27SDimitry Andric 
220006c3fb27SDimitry Andric   Value *NewC = Builder.CreateBinOp(
220106c3fb27SDimitry Andric       I.getOpcode(), ShiftedC1, Builder.CreateBinOp(ShiftOp, ShiftedC2, AddC));
220206c3fb27SDimitry Andric   return BinaryOperator::Create(ShiftOp, NewC, ShAmt);
2203bdd1243dSDimitry Andric }
2204bdd1243dSDimitry Andric 
2205297eecfbSDimitry Andric // Fold and/or/xor with two equal intrinsic IDs:
2206297eecfbSDimitry Andric // bitwise(fshl (A, B, ShAmt), fshl(C, D, ShAmt))
2207297eecfbSDimitry Andric // -> fshl(bitwise(A, C), bitwise(B, D), ShAmt)
2208297eecfbSDimitry Andric // bitwise(fshr (A, B, ShAmt), fshr(C, D, ShAmt))
2209297eecfbSDimitry Andric // -> fshr(bitwise(A, C), bitwise(B, D), ShAmt)
2210297eecfbSDimitry Andric // bitwise(bswap(A), bswap(B)) -> bswap(bitwise(A, B))
2211297eecfbSDimitry Andric // bitwise(bswap(A), C) -> bswap(bitwise(A, bswap(C)))
2212297eecfbSDimitry Andric // bitwise(bitreverse(A), bitreverse(B)) -> bitreverse(bitwise(A, B))
2213297eecfbSDimitry Andric // bitwise(bitreverse(A), C) -> bitreverse(bitwise(A, bitreverse(C)))
2214297eecfbSDimitry Andric static Instruction *
2215297eecfbSDimitry Andric foldBitwiseLogicWithIntrinsics(BinaryOperator &I,
2216297eecfbSDimitry Andric                                InstCombiner::BuilderTy &Builder) {
2217297eecfbSDimitry Andric   assert(I.isBitwiseLogicOp() && "Should and/or/xor");
2218297eecfbSDimitry Andric   if (!I.getOperand(0)->hasOneUse())
2219297eecfbSDimitry Andric     return nullptr;
2220297eecfbSDimitry Andric   IntrinsicInst *X = dyn_cast<IntrinsicInst>(I.getOperand(0));
2221297eecfbSDimitry Andric   if (!X)
2222297eecfbSDimitry Andric     return nullptr;
2223297eecfbSDimitry Andric 
2224297eecfbSDimitry Andric   IntrinsicInst *Y = dyn_cast<IntrinsicInst>(I.getOperand(1));
2225297eecfbSDimitry Andric   if (Y && (!Y->hasOneUse() || X->getIntrinsicID() != Y->getIntrinsicID()))
2226297eecfbSDimitry Andric     return nullptr;
2227297eecfbSDimitry Andric 
2228297eecfbSDimitry Andric   Intrinsic::ID IID = X->getIntrinsicID();
2229297eecfbSDimitry Andric   const APInt *RHSC;
2230297eecfbSDimitry Andric   // Try to match constant RHS.
2231297eecfbSDimitry Andric   if (!Y && (!(IID == Intrinsic::bswap || IID == Intrinsic::bitreverse) ||
2232297eecfbSDimitry Andric              !match(I.getOperand(1), m_APInt(RHSC))))
2233297eecfbSDimitry Andric     return nullptr;
2234297eecfbSDimitry Andric 
2235297eecfbSDimitry Andric   switch (IID) {
2236297eecfbSDimitry Andric   case Intrinsic::fshl:
2237297eecfbSDimitry Andric   case Intrinsic::fshr: {
2238297eecfbSDimitry Andric     if (X->getOperand(2) != Y->getOperand(2))
2239297eecfbSDimitry Andric       return nullptr;
2240297eecfbSDimitry Andric     Value *NewOp0 =
2241297eecfbSDimitry Andric         Builder.CreateBinOp(I.getOpcode(), X->getOperand(0), Y->getOperand(0));
2242297eecfbSDimitry Andric     Value *NewOp1 =
2243297eecfbSDimitry Andric         Builder.CreateBinOp(I.getOpcode(), X->getOperand(1), Y->getOperand(1));
2244297eecfbSDimitry Andric     Function *F = Intrinsic::getDeclaration(I.getModule(), IID, I.getType());
2245297eecfbSDimitry Andric     return CallInst::Create(F, {NewOp0, NewOp1, X->getOperand(2)});
2246297eecfbSDimitry Andric   }
2247297eecfbSDimitry Andric   case Intrinsic::bswap:
2248297eecfbSDimitry Andric   case Intrinsic::bitreverse: {
2249297eecfbSDimitry Andric     Value *NewOp0 = Builder.CreateBinOp(
2250297eecfbSDimitry Andric         I.getOpcode(), X->getOperand(0),
2251297eecfbSDimitry Andric         Y ? Y->getOperand(0)
2252297eecfbSDimitry Andric           : ConstantInt::get(I.getType(), IID == Intrinsic::bswap
2253297eecfbSDimitry Andric                                               ? RHSC->byteSwap()
2254297eecfbSDimitry Andric                                               : RHSC->reverseBits()));
2255297eecfbSDimitry Andric     Function *F = Intrinsic::getDeclaration(I.getModule(), IID, I.getType());
2256297eecfbSDimitry Andric     return CallInst::Create(F, {NewOp0});
2257297eecfbSDimitry Andric   }
2258297eecfbSDimitry Andric   default:
2259297eecfbSDimitry Andric     return nullptr;
2260297eecfbSDimitry Andric   }
2261297eecfbSDimitry Andric }
2262297eecfbSDimitry Andric 
22630fca6ea1SDimitry Andric // Try to simplify V by replacing occurrences of Op with RepOp, but only look
22640fca6ea1SDimitry Andric // through bitwise operations. In particular, for X | Y we try to replace Y with
22650fca6ea1SDimitry Andric // 0 inside X and for X & Y we try to replace Y with -1 inside X.
22660fca6ea1SDimitry Andric // Return the simplified result of X if successful, and nullptr otherwise.
22670fca6ea1SDimitry Andric // If SimplifyOnly is true, no new instructions will be created.
22680fca6ea1SDimitry Andric static Value *simplifyAndOrWithOpReplaced(Value *V, Value *Op, Value *RepOp,
22690fca6ea1SDimitry Andric                                           bool SimplifyOnly,
22700fca6ea1SDimitry Andric                                           InstCombinerImpl &IC,
22710fca6ea1SDimitry Andric                                           unsigned Depth = 0) {
22720fca6ea1SDimitry Andric   if (Op == RepOp)
22730fca6ea1SDimitry Andric     return nullptr;
22740fca6ea1SDimitry Andric 
22750fca6ea1SDimitry Andric   if (V == Op)
22760fca6ea1SDimitry Andric     return RepOp;
22770fca6ea1SDimitry Andric 
22780fca6ea1SDimitry Andric   auto *I = dyn_cast<BinaryOperator>(V);
22790fca6ea1SDimitry Andric   if (!I || !I->isBitwiseLogicOp() || Depth >= 3)
22800fca6ea1SDimitry Andric     return nullptr;
22810fca6ea1SDimitry Andric 
22820fca6ea1SDimitry Andric   if (!I->hasOneUse())
22830fca6ea1SDimitry Andric     SimplifyOnly = true;
22840fca6ea1SDimitry Andric 
22850fca6ea1SDimitry Andric   Value *NewOp0 = simplifyAndOrWithOpReplaced(I->getOperand(0), Op, RepOp,
22860fca6ea1SDimitry Andric                                               SimplifyOnly, IC, Depth + 1);
22870fca6ea1SDimitry Andric   Value *NewOp1 = simplifyAndOrWithOpReplaced(I->getOperand(1), Op, RepOp,
22880fca6ea1SDimitry Andric                                               SimplifyOnly, IC, Depth + 1);
22890fca6ea1SDimitry Andric   if (!NewOp0 && !NewOp1)
22900fca6ea1SDimitry Andric     return nullptr;
22910fca6ea1SDimitry Andric 
22920fca6ea1SDimitry Andric   if (!NewOp0)
22930fca6ea1SDimitry Andric     NewOp0 = I->getOperand(0);
22940fca6ea1SDimitry Andric   if (!NewOp1)
22950fca6ea1SDimitry Andric     NewOp1 = I->getOperand(1);
22960fca6ea1SDimitry Andric 
22970fca6ea1SDimitry Andric   if (Value *Res = simplifyBinOp(I->getOpcode(), NewOp0, NewOp1,
22980fca6ea1SDimitry Andric                                  IC.getSimplifyQuery().getWithInstruction(I)))
22990fca6ea1SDimitry Andric     return Res;
23000fca6ea1SDimitry Andric 
23010fca6ea1SDimitry Andric   if (SimplifyOnly)
23020fca6ea1SDimitry Andric     return nullptr;
23030fca6ea1SDimitry Andric   return IC.Builder.CreateBinOp(I->getOpcode(), NewOp0, NewOp1);
23040fca6ea1SDimitry Andric }
23050fca6ea1SDimitry Andric 
23060b57cec5SDimitry Andric // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
23070b57cec5SDimitry Andric // here. We should standardize that construct where it is needed or choose some
23080b57cec5SDimitry Andric // other way to ensure that commutated variants of patterns are not missed.
2309e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
2310e8d8bef9SDimitry Andric   Type *Ty = I.getType();
2311e8d8bef9SDimitry Andric 
231281ad6265SDimitry Andric   if (Value *V = simplifyAndInst(I.getOperand(0), I.getOperand(1),
23130b57cec5SDimitry Andric                                  SQ.getWithInstruction(&I)))
23140b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric   if (SimplifyAssociativeOrCommutative(I))
23170b57cec5SDimitry Andric     return &I;
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric   if (Instruction *X = foldVectorBinop(I))
23200b57cec5SDimitry Andric     return X;
23210b57cec5SDimitry Andric 
232204eeddc0SDimitry Andric   if (Instruction *Phi = foldBinopWithPhiOperands(I))
232304eeddc0SDimitry Andric     return Phi;
232404eeddc0SDimitry Andric 
23250b57cec5SDimitry Andric   // See if we can simplify any instructions used by the instruction whose sole
23260b57cec5SDimitry Andric   // purpose is to compute bits we don't care about.
23270b57cec5SDimitry Andric   if (SimplifyDemandedInstructionBits(I))
23280b57cec5SDimitry Andric     return &I;
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric   // Do this before using distributive laws to catch simple and/or/not patterns.
23310b57cec5SDimitry Andric   if (Instruction *Xor = foldAndToXor(I, Builder))
23320b57cec5SDimitry Andric     return Xor;
23330b57cec5SDimitry Andric 
2334349cc55cSDimitry Andric   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
2335349cc55cSDimitry Andric     return X;
2336349cc55cSDimitry Andric 
23370b57cec5SDimitry Andric   // (A|B)&(A|C) -> A|(B&C) etc
2338bdd1243dSDimitry Andric   if (Value *V = foldUsingDistributiveLaws(I))
23390b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
23400b57cec5SDimitry Andric 
234106c3fb27SDimitry Andric   if (Instruction *R = foldBinOpShiftWithShift(I))
234206c3fb27SDimitry Andric     return R;
234306c3fb27SDimitry Andric 
23440b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2345e8d8bef9SDimitry Andric 
23460b57cec5SDimitry Andric   Value *X, *Y;
23470fca6ea1SDimitry Andric   const APInt *C;
23480fca6ea1SDimitry Andric   if ((match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) ||
23490fca6ea1SDimitry Andric        (match(Op0, m_OneUse(m_Shl(m_APInt(C), m_Value(X)))) && (*C)[0])) &&
2350e8d8bef9SDimitry Andric       match(Op1, m_One())) {
23510b57cec5SDimitry Andric     // (1 >> X) & 1 --> zext(X == 0)
23520fca6ea1SDimitry Andric     // (C << X) & 1 --> zext(X == 0), when C is odd
2353e8d8bef9SDimitry Andric     Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
2354e8d8bef9SDimitry Andric     return new ZExtInst(IsZero, Ty);
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric 
2357753f127fSDimitry Andric   // (-(X & 1)) & Y --> (X & 1) == 0 ? 0 : Y
2358753f127fSDimitry Andric   Value *Neg;
2359753f127fSDimitry Andric   if (match(&I,
2360753f127fSDimitry Andric             m_c_And(m_CombineAnd(m_Value(Neg),
2361753f127fSDimitry Andric                                  m_OneUse(m_Neg(m_And(m_Value(), m_One())))),
2362753f127fSDimitry Andric                     m_Value(Y)))) {
2363753f127fSDimitry Andric     Value *Cmp = Builder.CreateIsNull(Neg);
2364753f127fSDimitry Andric     return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Y);
2365753f127fSDimitry Andric   }
2366753f127fSDimitry Andric 
23675f757f3fSDimitry Andric   // Canonicalize:
23685f757f3fSDimitry Andric   // (X +/- Y) & Y --> ~X & Y when Y is a power of 2.
23695f757f3fSDimitry Andric   if (match(&I, m_c_And(m_Value(Y), m_OneUse(m_CombineOr(
23705f757f3fSDimitry Andric                                         m_c_Add(m_Value(X), m_Deferred(Y)),
23715f757f3fSDimitry Andric                                         m_Sub(m_Value(X), m_Deferred(Y)))))) &&
23725f757f3fSDimitry Andric       isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, /*Depth*/ 0, &I))
23735f757f3fSDimitry Andric     return BinaryOperator::CreateAnd(Builder.CreateNot(X), Y);
23745f757f3fSDimitry Andric 
2375e8d8bef9SDimitry Andric   if (match(Op1, m_APInt(C))) {
23760b57cec5SDimitry Andric     const APInt *XorC;
23770b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
23780b57cec5SDimitry Andric       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2379e8d8bef9SDimitry Andric       Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
23800b57cec5SDimitry Andric       Value *And = Builder.CreateAnd(X, Op1);
23810b57cec5SDimitry Andric       And->takeName(Op0);
23820b57cec5SDimitry Andric       return BinaryOperator::CreateXor(And, NewC);
23830b57cec5SDimitry Andric     }
23840b57cec5SDimitry Andric 
23850b57cec5SDimitry Andric     const APInt *OrC;
23860b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
23870b57cec5SDimitry Andric       // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2)
23880b57cec5SDimitry Andric       // NOTE: This reduces the number of bits set in the & mask, which
23890b57cec5SDimitry Andric       // can expose opportunities for store narrowing for scalars.
23900b57cec5SDimitry Andric       // NOTE: SimplifyDemandedBits should have already removed bits from C1
23910b57cec5SDimitry Andric       // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in
23920b57cec5SDimitry Andric       // above, but this feels safer.
23930b57cec5SDimitry Andric       APInt Together = *C & *OrC;
2394e8d8bef9SDimitry Andric       Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
23950b57cec5SDimitry Andric       And->takeName(Op0);
2396e8d8bef9SDimitry Andric       return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
23970b57cec5SDimitry Andric     }
23980b57cec5SDimitry Andric 
2399e8d8bef9SDimitry Andric     unsigned Width = Ty->getScalarSizeInBits();
24005ffd83dbSDimitry Andric     const APInt *ShiftC;
2401753f127fSDimitry Andric     if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC))))) &&
2402753f127fSDimitry Andric         ShiftC->ult(Width)) {
24035ffd83dbSDimitry Andric       if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
24045ffd83dbSDimitry Andric         // We are clearing high bits that were potentially set by sext+ashr:
24055ffd83dbSDimitry Andric         // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC
2406e8d8bef9SDimitry Andric         Value *Sext = Builder.CreateSExt(X, Ty);
2407e8d8bef9SDimitry Andric         Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
24085ffd83dbSDimitry Andric         return BinaryOperator::CreateLShr(Sext, ShAmtC);
24095ffd83dbSDimitry Andric       }
24105ffd83dbSDimitry Andric     }
2411e8d8bef9SDimitry Andric 
24123a9a9c0cSDimitry Andric     // If this 'and' clears the sign-bits added by ashr, replace with lshr:
24133a9a9c0cSDimitry Andric     // and (ashr X, ShiftC), C --> lshr X, ShiftC
24143a9a9c0cSDimitry Andric     if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
24153a9a9c0cSDimitry Andric         C->isMask(Width - ShiftC->getZExtValue()))
24163a9a9c0cSDimitry Andric       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
24173a9a9c0cSDimitry Andric 
2418e8d8bef9SDimitry Andric     const APInt *AddC;
2419e8d8bef9SDimitry Andric     if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
2420e8d8bef9SDimitry Andric       // If we are masking the result of the add down to exactly one bit and
2421e8d8bef9SDimitry Andric       // the constant we are adding has no bits set below that bit, then the
2422e8d8bef9SDimitry Andric       // add is flipping a single bit. Example:
2423e8d8bef9SDimitry Andric       // (X + 4) & 4 --> (X & 4) ^ 4
2424e8d8bef9SDimitry Andric       if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
2425e8d8bef9SDimitry Andric         assert((*C & *AddC) != 0 && "Expected common bit");
2426e8d8bef9SDimitry Andric         Value *NewAnd = Builder.CreateAnd(X, Op1);
2427e8d8bef9SDimitry Andric         return BinaryOperator::CreateXor(NewAnd, Op1);
2428e8d8bef9SDimitry Andric       }
2429e8d8bef9SDimitry Andric     }
24300b57cec5SDimitry Andric 
2431349cc55cSDimitry Andric     // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the
2432349cc55cSDimitry Andric     // bitwidth of X and OP behaves well when given trunc(C1) and X.
243381ad6265SDimitry Andric     auto isNarrowableBinOpcode = [](BinaryOperator *B) {
2434349cc55cSDimitry Andric       switch (B->getOpcode()) {
24350b57cec5SDimitry Andric       case Instruction::Xor:
24360b57cec5SDimitry Andric       case Instruction::Or:
24370b57cec5SDimitry Andric       case Instruction::Mul:
24380b57cec5SDimitry Andric       case Instruction::Add:
24390b57cec5SDimitry Andric       case Instruction::Sub:
2440349cc55cSDimitry Andric         return true;
2441349cc55cSDimitry Andric       default:
2442349cc55cSDimitry Andric         return false;
2443349cc55cSDimitry Andric       }
2444349cc55cSDimitry Andric     };
2445349cc55cSDimitry Andric     BinaryOperator *BO;
244681ad6265SDimitry Andric     if (match(Op0, m_OneUse(m_BinOp(BO))) && isNarrowableBinOpcode(BO)) {
244781ad6265SDimitry Andric       Instruction::BinaryOps BOpcode = BO->getOpcode();
24480b57cec5SDimitry Andric       Value *X;
2449349cc55cSDimitry Andric       const APInt *C1;
2450349cc55cSDimitry Andric       // TODO: The one-use restrictions could be relaxed a little if the AND
24510b57cec5SDimitry Andric       // is going to be removed.
245281ad6265SDimitry Andric       // Try to narrow the 'and' and a binop with constant operand:
245381ad6265SDimitry Andric       // and (bo (zext X), C1), C --> zext (and (bo X, TruncC1), TruncC)
2454349cc55cSDimitry Andric       if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
2455349cc55cSDimitry Andric           C->isIntN(X->getType()->getScalarSizeInBits())) {
2456349cc55cSDimitry Andric         unsigned XWidth = X->getType()->getScalarSizeInBits();
2457349cc55cSDimitry Andric         Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
2458349cc55cSDimitry Andric         Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
245981ad6265SDimitry Andric                            ? Builder.CreateBinOp(BOpcode, X, TruncC1)
246081ad6265SDimitry Andric                            : Builder.CreateBinOp(BOpcode, TruncC1, X);
2461349cc55cSDimitry Andric         Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
2462349cc55cSDimitry Andric         Value *And = Builder.CreateAnd(BinOp, TruncC);
2463e8d8bef9SDimitry Andric         return new ZExtInst(And, Ty);
2464e8d8bef9SDimitry Andric       }
246581ad6265SDimitry Andric 
246681ad6265SDimitry Andric       // Similar to above: if the mask matches the zext input width, then the
246781ad6265SDimitry Andric       // 'and' can be eliminated, so we can truncate the other variable op:
246881ad6265SDimitry Andric       // and (bo (zext X), Y), C --> zext (bo X, (trunc Y))
246981ad6265SDimitry Andric       if (isa<Instruction>(BO->getOperand(0)) &&
247081ad6265SDimitry Andric           match(BO->getOperand(0), m_OneUse(m_ZExt(m_Value(X)))) &&
247181ad6265SDimitry Andric           C->isMask(X->getType()->getScalarSizeInBits())) {
247281ad6265SDimitry Andric         Y = BO->getOperand(1);
247381ad6265SDimitry Andric         Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
247481ad6265SDimitry Andric         Value *NewBO =
247581ad6265SDimitry Andric             Builder.CreateBinOp(BOpcode, X, TrY, BO->getName() + ".narrow");
247681ad6265SDimitry Andric         return new ZExtInst(NewBO, Ty);
247781ad6265SDimitry Andric       }
247881ad6265SDimitry Andric       // and (bo Y, (zext X)), C --> zext (bo (trunc Y), X)
247981ad6265SDimitry Andric       if (isa<Instruction>(BO->getOperand(1)) &&
248081ad6265SDimitry Andric           match(BO->getOperand(1), m_OneUse(m_ZExt(m_Value(X)))) &&
248181ad6265SDimitry Andric           C->isMask(X->getType()->getScalarSizeInBits())) {
248281ad6265SDimitry Andric         Y = BO->getOperand(0);
248381ad6265SDimitry Andric         Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
248481ad6265SDimitry Andric         Value *NewBO =
248581ad6265SDimitry Andric             Builder.CreateBinOp(BOpcode, TrY, X, BO->getName() + ".narrow");
248681ad6265SDimitry Andric         return new ZExtInst(NewBO, Ty);
248781ad6265SDimitry Andric       }
248881ad6265SDimitry Andric     }
248981ad6265SDimitry Andric 
249081ad6265SDimitry Andric     // This is intentionally placed after the narrowing transforms for
249181ad6265SDimitry Andric     // efficiency (transform directly to the narrow logic op if possible).
249281ad6265SDimitry Andric     // If the mask is only needed on one incoming arm, push the 'and' op up.
249381ad6265SDimitry Andric     if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
249481ad6265SDimitry Andric         match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
249581ad6265SDimitry Andric       APInt NotAndMask(~(*C));
249681ad6265SDimitry Andric       BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
249781ad6265SDimitry Andric       if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
249881ad6265SDimitry Andric         // Not masking anything out for the LHS, move mask to RHS.
249981ad6265SDimitry Andric         // and ({x}or X, Y), C --> {x}or X, (and Y, C)
250081ad6265SDimitry Andric         Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
250181ad6265SDimitry Andric         return BinaryOperator::Create(BinOp, X, NewRHS);
250281ad6265SDimitry Andric       }
250381ad6265SDimitry Andric       if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
250481ad6265SDimitry Andric         // Not masking anything out for the RHS, move mask to LHS.
250581ad6265SDimitry Andric         // and ({x}or X, Y), C --> {x}or (and X, C), Y
250681ad6265SDimitry Andric         Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
250781ad6265SDimitry Andric         return BinaryOperator::Create(BinOp, NewLHS, Y);
250881ad6265SDimitry Andric       }
250981ad6265SDimitry Andric     }
251081ad6265SDimitry Andric 
251181ad6265SDimitry Andric     // When the mask is a power-of-2 constant and op0 is a shifted-power-of-2
251281ad6265SDimitry Andric     // constant, test if the shift amount equals the offset bit index:
251381ad6265SDimitry Andric     // (ShiftC << X) & C --> X == (log2(C) - log2(ShiftC)) ? C : 0
251481ad6265SDimitry Andric     // (ShiftC >> X) & C --> X == (log2(ShiftC) - log2(C)) ? C : 0
251581ad6265SDimitry Andric     if (C->isPowerOf2() &&
251681ad6265SDimitry Andric         match(Op0, m_OneUse(m_LogicalShift(m_Power2(ShiftC), m_Value(X))))) {
251781ad6265SDimitry Andric       int Log2ShiftC = ShiftC->exactLogBase2();
251881ad6265SDimitry Andric       int Log2C = C->exactLogBase2();
251981ad6265SDimitry Andric       bool IsShiftLeft =
252081ad6265SDimitry Andric          cast<BinaryOperator>(Op0)->getOpcode() == Instruction::Shl;
252181ad6265SDimitry Andric       int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
252281ad6265SDimitry Andric       assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
252381ad6265SDimitry Andric       Value *Cmp = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, BitNum));
252481ad6265SDimitry Andric       return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C),
252581ad6265SDimitry Andric                                 ConstantInt::getNullValue(Ty));
252681ad6265SDimitry Andric     }
252781ad6265SDimitry Andric 
252881ad6265SDimitry Andric     Constant *C1, *C2;
252981ad6265SDimitry Andric     const APInt *C3 = C;
253081ad6265SDimitry Andric     Value *X;
253181ad6265SDimitry Andric     if (C3->isPowerOf2()) {
253206c3fb27SDimitry Andric       Constant *Log2C3 = ConstantInt::get(Ty, C3->countr_zero());
253381ad6265SDimitry Andric       if (match(Op0, m_OneUse(m_LShr(m_Shl(m_ImmConstant(C1), m_Value(X)),
253481ad6265SDimitry Andric                                      m_ImmConstant(C2)))) &&
253581ad6265SDimitry Andric           match(C1, m_Power2())) {
253681ad6265SDimitry Andric         Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
253781ad6265SDimitry Andric         Constant *LshrC = ConstantExpr::getAdd(C2, Log2C3);
253881ad6265SDimitry Andric         KnownBits KnownLShrc = computeKnownBits(LshrC, 0, nullptr);
253981ad6265SDimitry Andric         if (KnownLShrc.getMaxValue().ult(Width)) {
254081ad6265SDimitry Andric           // iff C1,C3 is pow2 and C2 + cttz(C3) < BitWidth:
254181ad6265SDimitry Andric           // ((C1 << X) >> C2) & C3 -> X == (cttz(C3)+C2-cttz(C1)) ? C3 : 0
254281ad6265SDimitry Andric           Constant *CmpC = ConstantExpr::getSub(LshrC, Log2C1);
254381ad6265SDimitry Andric           Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
254481ad6265SDimitry Andric           return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
254581ad6265SDimitry Andric                                     ConstantInt::getNullValue(Ty));
254681ad6265SDimitry Andric         }
254781ad6265SDimitry Andric       }
254881ad6265SDimitry Andric 
254981ad6265SDimitry Andric       if (match(Op0, m_OneUse(m_Shl(m_LShr(m_ImmConstant(C1), m_Value(X)),
255081ad6265SDimitry Andric                                     m_ImmConstant(C2)))) &&
255181ad6265SDimitry Andric           match(C1, m_Power2())) {
255281ad6265SDimitry Andric         Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
255381ad6265SDimitry Andric         Constant *Cmp =
25540fca6ea1SDimitry Andric             ConstantFoldCompareInstOperands(ICmpInst::ICMP_ULT, Log2C3, C2, DL);
25550fca6ea1SDimitry Andric         if (Cmp && Cmp->isZeroValue()) {
255681ad6265SDimitry Andric           // iff C1,C3 is pow2 and Log2(C3) >= C2:
255781ad6265SDimitry Andric           // ((C1 >> X) << C2) & C3 -> X == (cttz(C1)+C2-cttz(C3)) ? C3 : 0
255881ad6265SDimitry Andric           Constant *ShlC = ConstantExpr::getAdd(C2, Log2C1);
255981ad6265SDimitry Andric           Constant *CmpC = ConstantExpr::getSub(ShlC, Log2C3);
256081ad6265SDimitry Andric           Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
256181ad6265SDimitry Andric           return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
256281ad6265SDimitry Andric                                     ConstantInt::getNullValue(Ty));
256381ad6265SDimitry Andric         }
256481ad6265SDimitry Andric       }
2565e8d8bef9SDimitry Andric     }
25660b57cec5SDimitry Andric   }
25670b57cec5SDimitry Andric 
25685f757f3fSDimitry Andric   // If we are clearing the sign bit of a floating-point value, convert this to
25695f757f3fSDimitry Andric   // fabs, then cast back to integer.
25705f757f3fSDimitry Andric   //
25715f757f3fSDimitry Andric   // This is a generous interpretation for noimplicitfloat, this is not a true
25725f757f3fSDimitry Andric   // floating-point operation.
25735f757f3fSDimitry Andric   //
25745f757f3fSDimitry Andric   // Assumes any IEEE-represented type has the sign bit in the high bit.
25755f757f3fSDimitry Andric   // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
25765f757f3fSDimitry Andric   Value *CastOp;
25770fca6ea1SDimitry Andric   if (match(Op0, m_ElementWiseBitCast(m_Value(CastOp))) &&
25785f757f3fSDimitry Andric       match(Op1, m_MaxSignedValue()) &&
25795f757f3fSDimitry Andric       !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
25805f757f3fSDimitry Andric           Attribute::NoImplicitFloat)) {
25815f757f3fSDimitry Andric     Type *EltTy = CastOp->getType()->getScalarType();
25820fca6ea1SDimitry Andric     if (EltTy->isFloatingPointTy() && EltTy->isIEEE()) {
25835f757f3fSDimitry Andric       Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, CastOp);
25845f757f3fSDimitry Andric       return new BitCastInst(FAbs, I.getType());
25855f757f3fSDimitry Andric     }
25865f757f3fSDimitry Andric   }
25875f757f3fSDimitry Andric 
25880fca6ea1SDimitry Andric   // and(shl(zext(X), Y), SignMask) -> and(sext(X), SignMask)
25890fca6ea1SDimitry Andric   // where Y is a valid shift amount.
2590e8d8bef9SDimitry Andric   if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
2591e8d8bef9SDimitry Andric                       m_SignMask())) &&
2592e8d8bef9SDimitry Andric       match(Y, m_SpecificInt_ICMP(
2593e8d8bef9SDimitry Andric                    ICmpInst::Predicate::ICMP_EQ,
2594e8d8bef9SDimitry Andric                    APInt(Ty->getScalarSizeInBits(),
2595e8d8bef9SDimitry Andric                          Ty->getScalarSizeInBits() -
2596e8d8bef9SDimitry Andric                              X->getType()->getScalarSizeInBits())))) {
2597e8d8bef9SDimitry Andric     auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
25980fca6ea1SDimitry Andric     return BinaryOperator::CreateAnd(SExt, Op1);
25990b57cec5SDimitry Andric   }
26000b57cec5SDimitry Andric 
26010b57cec5SDimitry Andric   if (Instruction *Z = narrowMaskedBinOp(I))
26020b57cec5SDimitry Andric     return Z;
26030b57cec5SDimitry Andric 
2604fe6060f1SDimitry Andric   if (I.getType()->isIntOrIntVectorTy(1)) {
2605fe6060f1SDimitry Andric     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
26065f757f3fSDimitry Andric       if (auto *R =
2607fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true))
26085f757f3fSDimitry Andric         return R;
2609fe6060f1SDimitry Andric     }
2610fe6060f1SDimitry Andric     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
26115f757f3fSDimitry Andric       if (auto *R =
2612fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true))
26135f757f3fSDimitry Andric         return R;
2614fe6060f1SDimitry Andric     }
2615fe6060f1SDimitry Andric   }
2616fe6060f1SDimitry Andric 
26170b57cec5SDimitry Andric   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
26180b57cec5SDimitry Andric     return FoldedLogic;
26190b57cec5SDimitry Andric 
26205f757f3fSDimitry Andric   if (Instruction *DeMorgan = matchDeMorgansLaws(I, *this))
26210b57cec5SDimitry Andric     return DeMorgan;
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric   {
26240b57cec5SDimitry Andric     Value *A, *B, *C;
2625e8d8bef9SDimitry Andric     // A & ~(A ^ B) --> A & B
2626e8d8bef9SDimitry Andric     if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
2627e8d8bef9SDimitry Andric       return BinaryOperator::CreateAnd(Op0, B);
2628e8d8bef9SDimitry Andric     // ~(A ^ B) & A --> A & B
2629e8d8bef9SDimitry Andric     if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
2630e8d8bef9SDimitry Andric       return BinaryOperator::CreateAnd(Op1, B);
2631e8d8bef9SDimitry Andric 
26320b57cec5SDimitry Andric     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
26335f757f3fSDimitry Andric     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
26345f757f3fSDimitry Andric         match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A)))) {
26355f757f3fSDimitry Andric       Value *NotC = Op1->hasOneUse()
26365f757f3fSDimitry Andric                         ? Builder.CreateNot(C)
26375f757f3fSDimitry Andric                         : getFreelyInverted(C, C->hasOneUse(), &Builder);
26385f757f3fSDimitry Andric       if (NotC != nullptr)
26395f757f3fSDimitry Andric         return BinaryOperator::CreateAnd(Op0, NotC);
26405f757f3fSDimitry Andric     }
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
26435f757f3fSDimitry Andric     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))) &&
26445f757f3fSDimitry Andric         match(Op1, m_Xor(m_Specific(B), m_Specific(A)))) {
26455f757f3fSDimitry Andric       Value *NotC = Op0->hasOneUse()
26465f757f3fSDimitry Andric                         ? Builder.CreateNot(C)
26475f757f3fSDimitry Andric                         : getFreelyInverted(C, C->hasOneUse(), &Builder);
26485f757f3fSDimitry Andric       if (NotC != nullptr)
26490b57cec5SDimitry Andric         return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
26505f757f3fSDimitry Andric     }
26510b57cec5SDimitry Andric 
265204eeddc0SDimitry Andric     // (A | B) & (~A ^ B) -> A & B
265304eeddc0SDimitry Andric     // (A | B) & (B ^ ~A) -> A & B
265404eeddc0SDimitry Andric     // (B | A) & (~A ^ B) -> A & B
265504eeddc0SDimitry Andric     // (B | A) & (B ^ ~A) -> A & B
26560b57cec5SDimitry Andric     if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
26570b57cec5SDimitry Andric         match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
26580b57cec5SDimitry Andric       return BinaryOperator::CreateAnd(A, B);
26590b57cec5SDimitry Andric 
266004eeddc0SDimitry Andric     // (~A ^ B) & (A | B) -> A & B
266104eeddc0SDimitry Andric     // (~A ^ B) & (B | A) -> A & B
266204eeddc0SDimitry Andric     // (B ^ ~A) & (A | B) -> A & B
266304eeddc0SDimitry Andric     // (B ^ ~A) & (B | A) -> A & B
26640b57cec5SDimitry Andric     if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
26650b57cec5SDimitry Andric         match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
26660b57cec5SDimitry Andric       return BinaryOperator::CreateAnd(A, B);
266704eeddc0SDimitry Andric 
266804eeddc0SDimitry Andric     // (~A | B) & (A ^ B) -> ~A & B
266904eeddc0SDimitry Andric     // (~A | B) & (B ^ A) -> ~A & B
267004eeddc0SDimitry Andric     // (B | ~A) & (A ^ B) -> ~A & B
267104eeddc0SDimitry Andric     // (B | ~A) & (B ^ A) -> ~A & B
267204eeddc0SDimitry Andric     if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
267304eeddc0SDimitry Andric         match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
267404eeddc0SDimitry Andric       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
267504eeddc0SDimitry Andric 
267604eeddc0SDimitry Andric     // (A ^ B) & (~A | B) -> ~A & B
267704eeddc0SDimitry Andric     // (B ^ A) & (~A | B) -> ~A & B
267804eeddc0SDimitry Andric     // (A ^ B) & (B | ~A) -> ~A & B
267904eeddc0SDimitry Andric     // (B ^ A) & (B | ~A) -> ~A & B
268004eeddc0SDimitry Andric     if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
268104eeddc0SDimitry Andric         match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
268204eeddc0SDimitry Andric       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
26830b57cec5SDimitry Andric   }
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric   {
26860b57cec5SDimitry Andric     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
26870b57cec5SDimitry Andric     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
26880b57cec5SDimitry Andric     if (LHS && RHS)
268981ad6265SDimitry Andric       if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ true))
26900b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric     // TODO: Make this recursive; it's a little tricky because an arbitrary
26930b57cec5SDimitry Andric     // number of 'and' instructions might have to be created.
269481ad6265SDimitry Andric     if (LHS && match(Op1, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
269581ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op1);
269681ad6265SDimitry Andric       // LHS & (X && Y) --> (LHS && X) && Y
26970b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
269881ad6265SDimitry Andric         if (Value *Res =
269981ad6265SDimitry Andric                 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true, IsLogical))
270081ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
270181ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(Res, Y)
270281ad6265SDimitry Andric                                             : Builder.CreateAnd(Res, Y));
270381ad6265SDimitry Andric       // LHS & (X && Y) --> X && (LHS & Y)
27040b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
270581ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true,
270681ad6265SDimitry Andric                                           /* IsLogical */ false))
270781ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
270881ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(X, Res)
270981ad6265SDimitry Andric                                             : Builder.CreateAnd(X, Res));
27100b57cec5SDimitry Andric     }
271181ad6265SDimitry Andric     if (RHS && match(Op0, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
271281ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op0);
271381ad6265SDimitry Andric       // (X && Y) & RHS --> (X && RHS) && Y
27140b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
271581ad6265SDimitry Andric         if (Value *Res =
271681ad6265SDimitry Andric                 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true, IsLogical))
271781ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
271881ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(Res, Y)
271981ad6265SDimitry Andric                                             : Builder.CreateAnd(Res, Y));
272081ad6265SDimitry Andric       // (X && Y) & RHS --> X && (Y & RHS)
27210b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
272281ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true,
272381ad6265SDimitry Andric                                           /* IsLogical */ false))
272481ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
272581ad6265SDimitry Andric                                             ? Builder.CreateLogicalAnd(X, Res)
272681ad6265SDimitry Andric                                             : Builder.CreateAnd(X, Res));
27270b57cec5SDimitry Andric     }
27280b57cec5SDimitry Andric   }
27290b57cec5SDimitry Andric 
27300b57cec5SDimitry Andric   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
27310b57cec5SDimitry Andric     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
273281ad6265SDimitry Andric       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true))
27330b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
27360b57cec5SDimitry Andric     return FoldedFCmps;
27370b57cec5SDimitry Andric 
27380b57cec5SDimitry Andric   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
27390b57cec5SDimitry Andric     return CastedAnd;
27400b57cec5SDimitry Andric 
27414824e7fdSDimitry Andric   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
27424824e7fdSDimitry Andric     return Sel;
27434824e7fdSDimitry Andric 
27440b57cec5SDimitry Andric   // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>.
27454824e7fdSDimitry Andric   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
27464824e7fdSDimitry Andric   //       with binop identity constant. But creating a select with non-constant
27474824e7fdSDimitry Andric   //       arm may not be reversible due to poison semantics. Is that a good
27484824e7fdSDimitry Andric   //       canonicalization?
27495f757f3fSDimitry Andric   Value *A, *B;
27500fca6ea1SDimitry Andric   if (match(&I, m_c_And(m_SExt(m_Value(A)), m_Value(B))) &&
27510b57cec5SDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
27525f757f3fSDimitry Andric     return SelectInst::Create(A, B, Constant::getNullValue(Ty));
27530b57cec5SDimitry Andric 
2754bdd1243dSDimitry Andric   // Similarly, a 'not' of the bool translates to a swap of the select arms:
27555f757f3fSDimitry Andric   // ~sext(A) & B / B & ~sext(A) --> A ? 0 : B
27565f757f3fSDimitry Andric   if (match(&I, m_c_And(m_Not(m_SExt(m_Value(A))), m_Value(B))) &&
2757bdd1243dSDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
27585f757f3fSDimitry Andric     return SelectInst::Create(A, Constant::getNullValue(Ty), B);
27595f757f3fSDimitry Andric 
27605f757f3fSDimitry Andric   // and(zext(A), B) -> A ? (B & 1) : 0
27615f757f3fSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_ZExt(m_Value(A))), m_Value(B))) &&
2762bdd1243dSDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
27635f757f3fSDimitry Andric     return SelectInst::Create(A, Builder.CreateAnd(B, ConstantInt::get(Ty, 1)),
27645f757f3fSDimitry Andric                               Constant::getNullValue(Ty));
27655f757f3fSDimitry Andric 
27665f757f3fSDimitry Andric   // (-1 + A) & B --> A ? 0 : B where A is 0/1.
27675f757f3fSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_Add(m_ZExtOrSelf(m_Value(A)), m_AllOnes())),
27685f757f3fSDimitry Andric                         m_Value(B)))) {
27695f757f3fSDimitry Andric     if (A->getType()->isIntOrIntVectorTy(1))
27705f757f3fSDimitry Andric       return SelectInst::Create(A, Constant::getNullValue(Ty), B);
27715f757f3fSDimitry Andric     if (computeKnownBits(A, /* Depth */ 0, &I).countMaxActiveBits() <= 1) {
27725f757f3fSDimitry Andric       return SelectInst::Create(
27735f757f3fSDimitry Andric           Builder.CreateICmpEQ(A, Constant::getNullValue(A->getType())), B,
27745f757f3fSDimitry Andric           Constant::getNullValue(Ty));
27755f757f3fSDimitry Andric     }
27765f757f3fSDimitry Andric   }
2777bdd1243dSDimitry Andric 
2778bdd1243dSDimitry Andric   // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 -- with optional sext
2779bdd1243dSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
27800fca6ea1SDimitry Andric                             m_AShr(m_Value(X), m_APIntAllowPoison(C)))),
2781bdd1243dSDimitry Andric                         m_Value(Y))) &&
2782bdd1243dSDimitry Andric       *C == X->getType()->getScalarSizeInBits() - 1) {
278381ad6265SDimitry Andric     Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
278481ad6265SDimitry Andric     return SelectInst::Create(IsNeg, Y, ConstantInt::getNullValue(Ty));
27858bcb0991SDimitry Andric   }
27860eae32dcSDimitry Andric   // If there's a 'not' of the shifted value, swap the select operands:
2787bdd1243dSDimitry Andric   // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y -- with optional sext
2788bdd1243dSDimitry Andric   if (match(&I, m_c_And(m_OneUse(m_SExtOrSelf(
27890fca6ea1SDimitry Andric                             m_Not(m_AShr(m_Value(X), m_APIntAllowPoison(C))))),
2790bdd1243dSDimitry Andric                         m_Value(Y))) &&
2791bdd1243dSDimitry Andric       *C == X->getType()->getScalarSizeInBits() - 1) {
279281ad6265SDimitry Andric     Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
279381ad6265SDimitry Andric     return SelectInst::Create(IsNeg, ConstantInt::getNullValue(Ty), Y);
27940eae32dcSDimitry Andric   }
2795e8d8bef9SDimitry Andric 
2796e8d8bef9SDimitry Andric   // (~x) & y  -->  ~(x | (~y))  iff that gets rid of inversions
2797bdd1243dSDimitry Andric   if (sinkNotIntoOtherHandOfLogicalOp(I))
2798e8d8bef9SDimitry Andric     return &I;
27998bcb0991SDimitry Andric 
2800fe6060f1SDimitry Andric   // An and recurrence w/loop invariant step is equivelent to (and start, step)
2801fe6060f1SDimitry Andric   PHINode *PN = nullptr;
2802fe6060f1SDimitry Andric   Value *Start = nullptr, *Step = nullptr;
2803fe6060f1SDimitry Andric   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
2804fe6060f1SDimitry Andric     return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
2805fe6060f1SDimitry Andric 
2806bdd1243dSDimitry Andric   if (Instruction *R = reassociateForUses(I, Builder))
2807bdd1243dSDimitry Andric     return R;
2808bdd1243dSDimitry Andric 
2809bdd1243dSDimitry Andric   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
2810bdd1243dSDimitry Andric     return Canonicalized;
2811bdd1243dSDimitry Andric 
2812bdd1243dSDimitry Andric   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
2813bdd1243dSDimitry Andric     return Folded;
2814bdd1243dSDimitry Andric 
281506c3fb27SDimitry Andric   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
281606c3fb27SDimitry Andric     return Res;
281706c3fb27SDimitry Andric 
2818297eecfbSDimitry Andric   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
2819297eecfbSDimitry Andric     return Res;
2820297eecfbSDimitry Andric 
28210fca6ea1SDimitry Andric   if (Value *V =
28220fca6ea1SDimitry Andric           simplifyAndOrWithOpReplaced(Op0, Op1, Constant::getAllOnesValue(Ty),
28230fca6ea1SDimitry Andric                                       /*SimplifyOnly*/ false, *this))
28240fca6ea1SDimitry Andric     return BinaryOperator::CreateAnd(V, Op1);
28250fca6ea1SDimitry Andric   if (Value *V =
28260fca6ea1SDimitry Andric           simplifyAndOrWithOpReplaced(Op1, Op0, Constant::getAllOnesValue(Ty),
28270fca6ea1SDimitry Andric                                       /*SimplifyOnly*/ false, *this))
28280fca6ea1SDimitry Andric     return BinaryOperator::CreateAnd(Op0, V);
28290fca6ea1SDimitry Andric 
28300b57cec5SDimitry Andric   return nullptr;
28310b57cec5SDimitry Andric }
28320b57cec5SDimitry Andric 
2833fe6060f1SDimitry Andric Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
2834e8d8bef9SDimitry Andric                                                       bool MatchBSwaps,
2835e8d8bef9SDimitry Andric                                                       bool MatchBitReversals) {
28360b57cec5SDimitry Andric   SmallVector<Instruction *, 4> Insts;
2837fe6060f1SDimitry Andric   if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
2838e8d8bef9SDimitry Andric                                        Insts))
28390b57cec5SDimitry Andric     return nullptr;
28400b57cec5SDimitry Andric   Instruction *LastInst = Insts.pop_back_val();
28410b57cec5SDimitry Andric   LastInst->removeFromParent();
28420b57cec5SDimitry Andric 
28430b57cec5SDimitry Andric   for (auto *Inst : Insts)
28445ffd83dbSDimitry Andric     Worklist.push(Inst);
28450b57cec5SDimitry Andric   return LastInst;
28460b57cec5SDimitry Andric }
28470b57cec5SDimitry Andric 
28480fca6ea1SDimitry Andric std::optional<std::pair<Intrinsic::ID, SmallVector<Value *, 3>>>
28490fca6ea1SDimitry Andric InstCombinerImpl::convertOrOfShiftsToFunnelShift(Instruction &Or) {
28500b57cec5SDimitry Andric   // TODO: Can we reduce the code duplication between this and the related
28510b57cec5SDimitry Andric   // rotate matching code under visitSelect and visitTrunc?
28520fca6ea1SDimitry Andric   assert(Or.getOpcode() == BinaryOperator::Or && "Expecting or instruction");
28530fca6ea1SDimitry Andric 
28540b57cec5SDimitry Andric   unsigned Width = Or.getType()->getScalarSizeInBits();
28550b57cec5SDimitry Andric 
28565f757f3fSDimitry Andric   Instruction *Or0, *Or1;
28575f757f3fSDimitry Andric   if (!match(Or.getOperand(0), m_Instruction(Or0)) ||
28585f757f3fSDimitry Andric       !match(Or.getOperand(1), m_Instruction(Or1)))
28590fca6ea1SDimitry Andric     return std::nullopt;
28600b57cec5SDimitry Andric 
28615f757f3fSDimitry Andric   bool IsFshl = true; // Sub on LSHR.
28625f757f3fSDimitry Andric   SmallVector<Value *, 3> FShiftArgs;
28635f757f3fSDimitry Andric 
28645f757f3fSDimitry Andric   // First, find an or'd pair of opposite shifts:
28655f757f3fSDimitry Andric   // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1)
28665f757f3fSDimitry Andric   if (isa<BinaryOperator>(Or0) && isa<BinaryOperator>(Or1)) {
2867e8d8bef9SDimitry Andric     Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
28685f757f3fSDimitry Andric     if (!match(Or0,
28695f757f3fSDimitry Andric                m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
28705f757f3fSDimitry Andric         !match(Or1,
28715f757f3fSDimitry Andric                m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
2872e8d8bef9SDimitry Andric         Or0->getOpcode() == Or1->getOpcode())
28730fca6ea1SDimitry Andric       return std::nullopt;
28740b57cec5SDimitry Andric 
2875e8d8bef9SDimitry Andric     // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)).
2876e8d8bef9SDimitry Andric     if (Or0->getOpcode() == BinaryOperator::LShr) {
2877e8d8bef9SDimitry Andric       std::swap(Or0, Or1);
2878e8d8bef9SDimitry Andric       std::swap(ShVal0, ShVal1);
2879e8d8bef9SDimitry Andric       std::swap(ShAmt0, ShAmt1);
2880e8d8bef9SDimitry Andric     }
2881e8d8bef9SDimitry Andric     assert(Or0->getOpcode() == BinaryOperator::Shl &&
2882e8d8bef9SDimitry Andric            Or1->getOpcode() == BinaryOperator::LShr &&
2883e8d8bef9SDimitry Andric            "Illegal or(shift,shift) pair");
2884e8d8bef9SDimitry Andric 
2885e8d8bef9SDimitry Andric     // Match the shift amount operands for a funnel shift pattern. This always
2886e8d8bef9SDimitry Andric     // matches a subtraction on the R operand.
2887e8d8bef9SDimitry Andric     auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
2888e8d8bef9SDimitry Andric       // Check for constant shift amounts that sum to the bitwidth.
2889e8d8bef9SDimitry Andric       const APInt *LI, *RI;
28900fca6ea1SDimitry Andric       if (match(L, m_APIntAllowPoison(LI)) && match(R, m_APIntAllowPoison(RI)))
2891e8d8bef9SDimitry Andric         if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
2892e8d8bef9SDimitry Andric           return ConstantInt::get(L->getType(), *LI);
2893e8d8bef9SDimitry Andric 
2894e8d8bef9SDimitry Andric       Constant *LC, *RC;
2895e8d8bef9SDimitry Andric       if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
28965f757f3fSDimitry Andric           match(L,
28975f757f3fSDimitry Andric                 m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
28985f757f3fSDimitry Andric           match(R,
28995f757f3fSDimitry Andric                 m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
29000fca6ea1SDimitry Andric           match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowPoison(Width)))
2901e8d8bef9SDimitry Andric         return ConstantExpr::mergeUndefsWith(LC, RC);
2902e8d8bef9SDimitry Andric 
2903e8d8bef9SDimitry Andric       // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width.
29045f757f3fSDimitry Andric       // We limit this to X < Width in case the backend re-expands the
29055f757f3fSDimitry Andric       // intrinsic, and has to reintroduce a shift modulo operation (InstCombine
29065f757f3fSDimitry Andric       // might remove it after this fold). This still doesn't guarantee that the
29075f757f3fSDimitry Andric       // final codegen will match this original pattern.
2908e8d8bef9SDimitry Andric       if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
29090fca6ea1SDimitry Andric         KnownBits KnownL = computeKnownBits(L, /*Depth*/ 0, &Or);
2910e8d8bef9SDimitry Andric         return KnownL.getMaxValue().ult(Width) ? L : nullptr;
2911e8d8bef9SDimitry Andric       }
2912e8d8bef9SDimitry Andric 
2913e8d8bef9SDimitry Andric       // For non-constant cases, the following patterns currently only work for
2914e8d8bef9SDimitry Andric       // rotation patterns.
2915e8d8bef9SDimitry Andric       // TODO: Add general funnel-shift compatible patterns.
2916e8d8bef9SDimitry Andric       if (ShVal0 != ShVal1)
29170b57cec5SDimitry Andric         return nullptr;
29180b57cec5SDimitry Andric 
2919e8d8bef9SDimitry Andric       // For non-constant cases we don't support non-pow2 shift masks.
2920e8d8bef9SDimitry Andric       // TODO: Is it worth matching urem as well?
2921e8d8bef9SDimitry Andric       if (!isPowerOf2_32(Width))
2922e8d8bef9SDimitry Andric         return nullptr;
2923e8d8bef9SDimitry Andric 
29240b57cec5SDimitry Andric       // The shift amount may be masked with negation:
29250b57cec5SDimitry Andric       // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1)))
29260b57cec5SDimitry Andric       Value *X;
29270b57cec5SDimitry Andric       unsigned Mask = Width - 1;
29280b57cec5SDimitry Andric       if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
29290b57cec5SDimitry Andric           match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
29300b57cec5SDimitry Andric         return X;
29310b57cec5SDimitry Andric 
29327a6dacacSDimitry Andric       // (shl ShVal, X) | (lshr ShVal, ((-X) & (Width - 1)))
29337a6dacacSDimitry Andric       if (match(R, m_And(m_Neg(m_Specific(L)), m_SpecificInt(Mask))))
29347a6dacacSDimitry Andric         return L;
29357a6dacacSDimitry Andric 
29360b57cec5SDimitry Andric       // Similar to above, but the shift amount may be extended after masking,
29370b57cec5SDimitry Andric       // so return the extended value as the parameter for the intrinsic.
29380b57cec5SDimitry Andric       if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
29395f757f3fSDimitry Andric           match(R,
29405f757f3fSDimitry Andric                 m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
29410b57cec5SDimitry Andric                       m_SpecificInt(Mask))))
29420b57cec5SDimitry Andric         return L;
29430b57cec5SDimitry Andric 
2944e8d8bef9SDimitry Andric       if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
2945e8d8bef9SDimitry Andric           match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
2946e8d8bef9SDimitry Andric         return L;
2947e8d8bef9SDimitry Andric 
29480b57cec5SDimitry Andric       return nullptr;
29490b57cec5SDimitry Andric     };
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric     Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
29520b57cec5SDimitry Andric     if (!ShAmt) {
29530b57cec5SDimitry Andric       ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
2954e8d8bef9SDimitry Andric       IsFshl = false; // Sub on SHL.
29550b57cec5SDimitry Andric     }
29560b57cec5SDimitry Andric     if (!ShAmt)
29570fca6ea1SDimitry Andric       return std::nullopt;
29580b57cec5SDimitry Andric 
29595f757f3fSDimitry Andric     FShiftArgs = {ShVal0, ShVal1, ShAmt};
29605f757f3fSDimitry Andric   } else if (isa<ZExtInst>(Or0) || isa<ZExtInst>(Or1)) {
29615f757f3fSDimitry Andric     // If there are two 'or' instructions concat variables in opposite order:
29625f757f3fSDimitry Andric     //
29635f757f3fSDimitry Andric     // Slot1 and Slot2 are all zero bits.
29645f757f3fSDimitry Andric     // | Slot1 | Low | Slot2 | High |
29655f757f3fSDimitry Andric     // LowHigh = or (shl (zext Low), ZextLowShlAmt), (zext High)
29665f757f3fSDimitry Andric     // | Slot2 | High | Slot1 | Low |
29675f757f3fSDimitry Andric     // HighLow = or (shl (zext High), ZextHighShlAmt), (zext Low)
29685f757f3fSDimitry Andric     //
29695f757f3fSDimitry Andric     // the latter 'or' can be safely convert to
29705f757f3fSDimitry Andric     // -> HighLow = fshl LowHigh, LowHigh, ZextHighShlAmt
29715f757f3fSDimitry Andric     // if ZextLowShlAmt + ZextHighShlAmt == Width.
29725f757f3fSDimitry Andric     if (!isa<ZExtInst>(Or1))
29735f757f3fSDimitry Andric       std::swap(Or0, Or1);
29745f757f3fSDimitry Andric 
29755f757f3fSDimitry Andric     Value *High, *ZextHigh, *Low;
29765f757f3fSDimitry Andric     const APInt *ZextHighShlAmt;
29775f757f3fSDimitry Andric     if (!match(Or0,
29785f757f3fSDimitry Andric                m_OneUse(m_Shl(m_Value(ZextHigh), m_APInt(ZextHighShlAmt)))))
29790fca6ea1SDimitry Andric       return std::nullopt;
29805f757f3fSDimitry Andric 
29815f757f3fSDimitry Andric     if (!match(Or1, m_ZExt(m_Value(Low))) ||
29825f757f3fSDimitry Andric         !match(ZextHigh, m_ZExt(m_Value(High))))
29830fca6ea1SDimitry Andric       return std::nullopt;
29845f757f3fSDimitry Andric 
29855f757f3fSDimitry Andric     unsigned HighSize = High->getType()->getScalarSizeInBits();
29865f757f3fSDimitry Andric     unsigned LowSize = Low->getType()->getScalarSizeInBits();
29875f757f3fSDimitry Andric     // Make sure High does not overlap with Low and most significant bits of
29885f757f3fSDimitry Andric     // High aren't shifted out.
29895f757f3fSDimitry Andric     if (ZextHighShlAmt->ult(LowSize) || ZextHighShlAmt->ugt(Width - HighSize))
29900fca6ea1SDimitry Andric       return std::nullopt;
29915f757f3fSDimitry Andric 
29925f757f3fSDimitry Andric     for (User *U : ZextHigh->users()) {
29935f757f3fSDimitry Andric       Value *X, *Y;
29945f757f3fSDimitry Andric       if (!match(U, m_Or(m_Value(X), m_Value(Y))))
29955f757f3fSDimitry Andric         continue;
29965f757f3fSDimitry Andric 
29975f757f3fSDimitry Andric       if (!isa<ZExtInst>(Y))
29985f757f3fSDimitry Andric         std::swap(X, Y);
29995f757f3fSDimitry Andric 
30005f757f3fSDimitry Andric       const APInt *ZextLowShlAmt;
30015f757f3fSDimitry Andric       if (!match(X, m_Shl(m_Specific(Or1), m_APInt(ZextLowShlAmt))) ||
30025f757f3fSDimitry Andric           !match(Y, m_Specific(ZextHigh)) || !DT.dominates(U, &Or))
30035f757f3fSDimitry Andric         continue;
30045f757f3fSDimitry Andric 
30055f757f3fSDimitry Andric       // HighLow is good concat. If sum of two shifts amount equals to Width,
30065f757f3fSDimitry Andric       // LowHigh must also be a good concat.
30075f757f3fSDimitry Andric       if (*ZextLowShlAmt + *ZextHighShlAmt != Width)
30085f757f3fSDimitry Andric         continue;
30095f757f3fSDimitry Andric 
30105f757f3fSDimitry Andric       // Low must not overlap with High and most significant bits of Low must
30115f757f3fSDimitry Andric       // not be shifted out.
30125f757f3fSDimitry Andric       assert(ZextLowShlAmt->uge(HighSize) &&
30135f757f3fSDimitry Andric              ZextLowShlAmt->ule(Width - LowSize) && "Invalid concat");
30145f757f3fSDimitry Andric 
30155f757f3fSDimitry Andric       FShiftArgs = {U, U, ConstantInt::get(Or0->getType(), *ZextHighShlAmt)};
30165f757f3fSDimitry Andric       break;
30175f757f3fSDimitry Andric     }
30185f757f3fSDimitry Andric   }
30195f757f3fSDimitry Andric 
30205f757f3fSDimitry Andric   if (FShiftArgs.empty())
30210fca6ea1SDimitry Andric     return std::nullopt;
30225f757f3fSDimitry Andric 
30230b57cec5SDimitry Andric   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
30240fca6ea1SDimitry Andric   return std::make_pair(IID, FShiftArgs);
30250fca6ea1SDimitry Andric }
30260fca6ea1SDimitry Andric 
30270fca6ea1SDimitry Andric /// Match UB-safe variants of the funnel shift intrinsic.
30280fca6ea1SDimitry Andric static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
30290fca6ea1SDimitry Andric   if (auto Opt = IC.convertOrOfShiftsToFunnelShift(Or)) {
30300fca6ea1SDimitry Andric     auto [IID, FShiftArgs] = *Opt;
30310b57cec5SDimitry Andric     Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
30325f757f3fSDimitry Andric     return CallInst::Create(F, FShiftArgs);
30330b57cec5SDimitry Andric   }
30340b57cec5SDimitry Andric 
30350fca6ea1SDimitry Andric   return nullptr;
30360fca6ea1SDimitry Andric }
30370fca6ea1SDimitry Andric 
30385ffd83dbSDimitry Andric /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns.
30395ffd83dbSDimitry Andric static Instruction *matchOrConcat(Instruction &Or,
30405ffd83dbSDimitry Andric                                   InstCombiner::BuilderTy &Builder) {
30415ffd83dbSDimitry Andric   assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
30425ffd83dbSDimitry Andric   Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
30435ffd83dbSDimitry Andric   Type *Ty = Or.getType();
30445ffd83dbSDimitry Andric 
30455ffd83dbSDimitry Andric   unsigned Width = Ty->getScalarSizeInBits();
30465ffd83dbSDimitry Andric   if ((Width & 1) != 0)
30475ffd83dbSDimitry Andric     return nullptr;
30485ffd83dbSDimitry Andric   unsigned HalfWidth = Width / 2;
30495ffd83dbSDimitry Andric 
30505ffd83dbSDimitry Andric   // Canonicalize zext (lower half) to LHS.
30515ffd83dbSDimitry Andric   if (!isa<ZExtInst>(Op0))
30525ffd83dbSDimitry Andric     std::swap(Op0, Op1);
30535ffd83dbSDimitry Andric 
30545ffd83dbSDimitry Andric   // Find lower/upper half.
30555ffd83dbSDimitry Andric   Value *LowerSrc, *ShlVal, *UpperSrc;
30565ffd83dbSDimitry Andric   const APInt *C;
30575ffd83dbSDimitry Andric   if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
30585ffd83dbSDimitry Andric       !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
30595ffd83dbSDimitry Andric       !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
30605ffd83dbSDimitry Andric     return nullptr;
30615ffd83dbSDimitry Andric   if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
30625ffd83dbSDimitry Andric       LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
30635ffd83dbSDimitry Andric     return nullptr;
30645ffd83dbSDimitry Andric 
30655ffd83dbSDimitry Andric   auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
30665ffd83dbSDimitry Andric     Value *NewLower = Builder.CreateZExt(Lo, Ty);
30675ffd83dbSDimitry Andric     Value *NewUpper = Builder.CreateZExt(Hi, Ty);
30685ffd83dbSDimitry Andric     NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
30695ffd83dbSDimitry Andric     Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
30705ffd83dbSDimitry Andric     Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
30715ffd83dbSDimitry Andric     return Builder.CreateCall(F, BinOp);
30725ffd83dbSDimitry Andric   };
30735ffd83dbSDimitry Andric 
30745ffd83dbSDimitry Andric   // BSWAP: Push the concat down, swapping the lower/upper sources.
30755ffd83dbSDimitry Andric   // concat(bswap(x),bswap(y)) -> bswap(concat(x,y))
30765ffd83dbSDimitry Andric   Value *LowerBSwap, *UpperBSwap;
30775ffd83dbSDimitry Andric   if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
30785ffd83dbSDimitry Andric       match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
30795ffd83dbSDimitry Andric     return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
30805ffd83dbSDimitry Andric 
30815ffd83dbSDimitry Andric   // BITREVERSE: Push the concat down, swapping the lower/upper sources.
30825ffd83dbSDimitry Andric   // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y))
30835ffd83dbSDimitry Andric   Value *LowerBRev, *UpperBRev;
30845ffd83dbSDimitry Andric   if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
30855ffd83dbSDimitry Andric       match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
30865ffd83dbSDimitry Andric     return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
30875ffd83dbSDimitry Andric 
30885ffd83dbSDimitry Andric   return nullptr;
30895ffd83dbSDimitry Andric }
30905ffd83dbSDimitry Andric 
30910b57cec5SDimitry Andric /// If all elements of two constant vectors are 0/-1 and inverses, return true.
30920b57cec5SDimitry Andric static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
3093e8d8bef9SDimitry Andric   unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
30940b57cec5SDimitry Andric   for (unsigned i = 0; i != NumElts; ++i) {
30950b57cec5SDimitry Andric     Constant *EltC1 = C1->getAggregateElement(i);
30960b57cec5SDimitry Andric     Constant *EltC2 = C2->getAggregateElement(i);
30970b57cec5SDimitry Andric     if (!EltC1 || !EltC2)
30980b57cec5SDimitry Andric       return false;
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric     // One element must be all ones, and the other must be all zeros.
31010b57cec5SDimitry Andric     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
31020b57cec5SDimitry Andric           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
31030b57cec5SDimitry Andric       return false;
31040b57cec5SDimitry Andric   }
31050b57cec5SDimitry Andric   return true;
31060b57cec5SDimitry Andric }
31070b57cec5SDimitry Andric 
31080b57cec5SDimitry Andric /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
31090b57cec5SDimitry Andric /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
31100b57cec5SDimitry Andric /// B, it can be used as the condition operand of a select instruction.
3111bdd1243dSDimitry Andric /// We will detect (A & C) | ~(B | D) when the flag ABIsTheSame enabled.
3112bdd1243dSDimitry Andric Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B,
3113bdd1243dSDimitry Andric                                             bool ABIsTheSame) {
3114349cc55cSDimitry Andric   // We may have peeked through bitcasts in the caller.
31150b57cec5SDimitry Andric   // Exit immediately if we don't have (vector) integer types.
31160b57cec5SDimitry Andric   Type *Ty = A->getType();
31170b57cec5SDimitry Andric   if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
31180b57cec5SDimitry Andric     return nullptr;
31190b57cec5SDimitry Andric 
3120349cc55cSDimitry Andric   // If A is the 'not' operand of B and has enough signbits, we have our answer.
3121bdd1243dSDimitry Andric   if (ABIsTheSame ? (A == B) : match(B, m_Not(m_Specific(A)))) {
31220b57cec5SDimitry Andric     // If these are scalars or vectors of i1, A can be used directly.
31230b57cec5SDimitry Andric     if (Ty->isIntOrIntVectorTy(1))
31240b57cec5SDimitry Andric       return A;
3125349cc55cSDimitry Andric 
3126349cc55cSDimitry Andric     // If we look through a vector bitcast, the caller will bitcast the operands
3127349cc55cSDimitry Andric     // to match the condition's number of bits (N x i1).
3128349cc55cSDimitry Andric     // To make this poison-safe, disallow bitcast from wide element to narrow
3129349cc55cSDimitry Andric     // element. That could allow poison in lanes where it was not present in the
3130349cc55cSDimitry Andric     // original code.
3131349cc55cSDimitry Andric     A = peekThroughBitcast(A);
3132349cc55cSDimitry Andric     if (A->getType()->isIntOrIntVectorTy()) {
3133349cc55cSDimitry Andric       unsigned NumSignBits = ComputeNumSignBits(A);
3134349cc55cSDimitry Andric       if (NumSignBits == A->getType()->getScalarSizeInBits() &&
3135349cc55cSDimitry Andric           NumSignBits <= Ty->getScalarSizeInBits())
3136349cc55cSDimitry Andric         return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
3137349cc55cSDimitry Andric     }
3138349cc55cSDimitry Andric     return nullptr;
31390b57cec5SDimitry Andric   }
31400b57cec5SDimitry Andric 
3141bdd1243dSDimitry Andric   // TODO: add support for sext and constant case
3142bdd1243dSDimitry Andric   if (ABIsTheSame)
3143bdd1243dSDimitry Andric     return nullptr;
3144bdd1243dSDimitry Andric 
31450b57cec5SDimitry Andric   // If both operands are constants, see if the constants are inverse bitmasks.
31460b57cec5SDimitry Andric   Constant *AConst, *BConst;
31470b57cec5SDimitry Andric   if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
3148349cc55cSDimitry Andric     if (AConst == ConstantExpr::getNot(BConst) &&
3149349cc55cSDimitry Andric         ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
31500b57cec5SDimitry Andric       return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric   // Look for more complex patterns. The 'not' op may be hidden behind various
31530b57cec5SDimitry Andric   // casts. Look through sexts and bitcasts to find the booleans.
31540b57cec5SDimitry Andric   Value *Cond;
31550b57cec5SDimitry Andric   Value *NotB;
31560b57cec5SDimitry Andric   if (match(A, m_SExt(m_Value(Cond))) &&
31574824e7fdSDimitry Andric       Cond->getType()->isIntOrIntVectorTy(1)) {
31584824e7fdSDimitry Andric     // A = sext i1 Cond; B = sext (not (i1 Cond))
31594824e7fdSDimitry Andric     if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
31604824e7fdSDimitry Andric       return Cond;
31614824e7fdSDimitry Andric 
31624824e7fdSDimitry Andric     // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond)))
31634824e7fdSDimitry Andric     // TODO: The one-use checks are unnecessary or misplaced. If the caller
31644824e7fdSDimitry Andric     //       checked for uses on logic ops/casts, that should be enough to
31654824e7fdSDimitry Andric     //       make this transform worthwhile.
31664824e7fdSDimitry Andric     if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
31670b57cec5SDimitry Andric       NotB = peekThroughBitcast(NotB, true);
31680b57cec5SDimitry Andric       if (match(NotB, m_SExt(m_Specific(Cond))))
31690b57cec5SDimitry Andric         return Cond;
31700b57cec5SDimitry Andric     }
31714824e7fdSDimitry Andric   }
31720b57cec5SDimitry Andric 
31730b57cec5SDimitry Andric   // All scalar (and most vector) possibilities should be handled now.
31740b57cec5SDimitry Andric   // Try more matches that only apply to non-splat constant vectors.
31750b57cec5SDimitry Andric   if (!Ty->isVectorTy())
31760b57cec5SDimitry Andric     return nullptr;
31770b57cec5SDimitry Andric 
31780b57cec5SDimitry Andric   // If both operands are xor'd with constants using the same sexted boolean
31790b57cec5SDimitry Andric   // operand, see if the constants are inverse bitmasks.
31800b57cec5SDimitry Andric   // TODO: Use ConstantExpr::getNot()?
31810b57cec5SDimitry Andric   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
31820b57cec5SDimitry Andric       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
31830b57cec5SDimitry Andric       Cond->getType()->isIntOrIntVectorTy(1) &&
31840b57cec5SDimitry Andric       areInverseVectorBitmasks(AConst, BConst)) {
31850b57cec5SDimitry Andric     AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
31860b57cec5SDimitry Andric     return Builder.CreateXor(Cond, AConst);
31870b57cec5SDimitry Andric   }
31880b57cec5SDimitry Andric   return nullptr;
31890b57cec5SDimitry Andric }
31900b57cec5SDimitry Andric 
31910fca6ea1SDimitry Andric /// We have an expression of the form (A & B) | (C & D). Try to simplify this
31920fca6ea1SDimitry Andric /// to "A' ? B : D", where A' is a boolean or vector of booleans.
3193bdd1243dSDimitry Andric /// When InvertFalseVal is set to true, we try to match the pattern
31940fca6ea1SDimitry Andric /// where we have peeked through a 'not' op and A and C are the same:
31950fca6ea1SDimitry Andric /// (A & B) | ~(A | D) --> (A & B) | (~A & ~D) --> A' ? B : ~D
31960fca6ea1SDimitry Andric Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *B, Value *C,
3197bdd1243dSDimitry Andric                                               Value *D, bool InvertFalseVal) {
31980b57cec5SDimitry Andric   // The potential condition of the select may be bitcasted. In that case, look
31990b57cec5SDimitry Andric   // through its bitcast and the corresponding bitcast of the 'not' condition.
32000b57cec5SDimitry Andric   Type *OrigType = A->getType();
32010b57cec5SDimitry Andric   A = peekThroughBitcast(A, true);
32020fca6ea1SDimitry Andric   C = peekThroughBitcast(C, true);
32030fca6ea1SDimitry Andric   if (Value *Cond = getSelectCondition(A, C, InvertFalseVal)) {
32040fca6ea1SDimitry Andric     // ((bc Cond) & B) | ((bc ~Cond) & D) --> bc (select Cond, (bc B), (bc D))
3205349cc55cSDimitry Andric     // If this is a vector, we may need to cast to match the condition's length.
32060b57cec5SDimitry Andric     // The bitcasts will either all exist or all not exist. The builder will
32070b57cec5SDimitry Andric     // not create unnecessary casts if the types already match.
3208349cc55cSDimitry Andric     Type *SelTy = A->getType();
3209349cc55cSDimitry Andric     if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
32102a66634dSDimitry Andric       // For a fixed or scalable vector get N from <{vscale x} N x iM>
3211349cc55cSDimitry Andric       unsigned Elts = VecTy->getElementCount().getKnownMinValue();
32122a66634dSDimitry Andric       // For a fixed or scalable vector, get the size in bits of N x iM; for a
32132a66634dSDimitry Andric       // scalar this is just M.
3214bdd1243dSDimitry Andric       unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinValue();
32152a66634dSDimitry Andric       Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
3216349cc55cSDimitry Andric       SelTy = VectorType::get(EltTy, VecTy->getElementCount());
3217349cc55cSDimitry Andric     }
32180fca6ea1SDimitry Andric     Value *BitcastB = Builder.CreateBitCast(B, SelTy);
3219bdd1243dSDimitry Andric     if (InvertFalseVal)
3220bdd1243dSDimitry Andric       D = Builder.CreateNot(D);
3221349cc55cSDimitry Andric     Value *BitcastD = Builder.CreateBitCast(D, SelTy);
32220fca6ea1SDimitry Andric     Value *Select = Builder.CreateSelect(Cond, BitcastB, BitcastD);
32230b57cec5SDimitry Andric     return Builder.CreateBitCast(Select, OrigType);
32240b57cec5SDimitry Andric   }
32250b57cec5SDimitry Andric 
32260b57cec5SDimitry Andric   return nullptr;
32270b57cec5SDimitry Andric }
32280b57cec5SDimitry Andric 
322906c3fb27SDimitry Andric // (icmp eq X, C) | (icmp ult Other, (X - C)) -> (icmp ule Other, (X - (C + 1)))
323006c3fb27SDimitry Andric // (icmp ne X, C) & (icmp uge Other, (X - C)) -> (icmp ugt Other, (X - (C + 1)))
323106c3fb27SDimitry Andric static Value *foldAndOrOfICmpEqConstantAndICmp(ICmpInst *LHS, ICmpInst *RHS,
3232bdd1243dSDimitry Andric                                                bool IsAnd, bool IsLogical,
323381ad6265SDimitry Andric                                                IRBuilderBase &Builder) {
323406c3fb27SDimitry Andric   Value *LHS0 = LHS->getOperand(0);
323506c3fb27SDimitry Andric   Value *RHS0 = RHS->getOperand(0);
323606c3fb27SDimitry Andric   Value *RHS1 = RHS->getOperand(1);
323706c3fb27SDimitry Andric 
323881ad6265SDimitry Andric   ICmpInst::Predicate LPred =
323981ad6265SDimitry Andric       IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
324081ad6265SDimitry Andric   ICmpInst::Predicate RPred =
324181ad6265SDimitry Andric       IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
324206c3fb27SDimitry Andric 
324306c3fb27SDimitry Andric   const APInt *CInt;
324406c3fb27SDimitry Andric   if (LPred != ICmpInst::ICMP_EQ ||
32450fca6ea1SDimitry Andric       !match(LHS->getOperand(1), m_APIntAllowPoison(CInt)) ||
324681ad6265SDimitry Andric       !LHS0->getType()->isIntOrIntVectorTy() ||
324781ad6265SDimitry Andric       !(LHS->hasOneUse() || RHS->hasOneUse()))
324881ad6265SDimitry Andric     return nullptr;
324981ad6265SDimitry Andric 
325006c3fb27SDimitry Andric   auto MatchRHSOp = [LHS0, CInt](const Value *RHSOp) {
325106c3fb27SDimitry Andric     return match(RHSOp,
32520fca6ea1SDimitry Andric                  m_Add(m_Specific(LHS0), m_SpecificIntAllowPoison(-*CInt))) ||
325306c3fb27SDimitry Andric            (CInt->isZero() && RHSOp == LHS0);
325406c3fb27SDimitry Andric   };
325506c3fb27SDimitry Andric 
325681ad6265SDimitry Andric   Value *Other;
325706c3fb27SDimitry Andric   if (RPred == ICmpInst::ICMP_ULT && MatchRHSOp(RHS1))
325806c3fb27SDimitry Andric     Other = RHS0;
325906c3fb27SDimitry Andric   else if (RPred == ICmpInst::ICMP_UGT && MatchRHSOp(RHS0))
326006c3fb27SDimitry Andric     Other = RHS1;
326181ad6265SDimitry Andric   else
326281ad6265SDimitry Andric     return nullptr;
326381ad6265SDimitry Andric 
3264bdd1243dSDimitry Andric   if (IsLogical)
3265bdd1243dSDimitry Andric     Other = Builder.CreateFreeze(Other);
326606c3fb27SDimitry Andric 
326781ad6265SDimitry Andric   return Builder.CreateICmp(
326881ad6265SDimitry Andric       IsAnd ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE,
326906c3fb27SDimitry Andric       Builder.CreateSub(LHS0, ConstantInt::get(LHS0->getType(), *CInt + 1)),
327081ad6265SDimitry Andric       Other);
327181ad6265SDimitry Andric }
327281ad6265SDimitry Andric 
327381ad6265SDimitry Andric /// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible.
327481ad6265SDimitry Andric /// If IsLogical is true, then the and/or is in select form and the transform
327581ad6265SDimitry Andric /// must be poison-safe.
327681ad6265SDimitry Andric Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
327781ad6265SDimitry Andric                                           Instruction &I, bool IsAnd,
327881ad6265SDimitry Andric                                           bool IsLogical) {
327981ad6265SDimitry Andric   const SimplifyQuery Q = SQ.getWithInstruction(&I);
32808bcb0991SDimitry Andric 
32810b57cec5SDimitry Andric   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
328281ad6265SDimitry Andric   // Fold (!iszero(A & K1) & !iszero(A & K2)) ->  (A & (K1 | K2)) == (K1 | K2)
32830b57cec5SDimitry Andric   // if K1 and K2 are a one-bit mask.
328481ad6265SDimitry Andric   if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &I, IsAnd, IsLogical))
32850b57cec5SDimitry Andric     return V;
32860b57cec5SDimitry Andric 
32870b57cec5SDimitry Andric   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
3288e8d8bef9SDimitry Andric   Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
3289e8d8bef9SDimitry Andric   Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
32900fca6ea1SDimitry Andric 
3291349cc55cSDimitry Andric   const APInt *LHSC = nullptr, *RHSC = nullptr;
3292349cc55cSDimitry Andric   match(LHS1, m_APInt(LHSC));
3293349cc55cSDimitry Andric   match(RHS1, m_APInt(RHSC));
32940b57cec5SDimitry Andric 
32950b57cec5SDimitry Andric   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
329681ad6265SDimitry Andric   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
32970b57cec5SDimitry Andric   if (predicatesFoldable(PredL, PredR)) {
329881ad6265SDimitry Andric     if (LHS0 == RHS1 && LHS1 == RHS0) {
329981ad6265SDimitry Andric       PredL = ICmpInst::getSwappedPredicate(PredL);
330081ad6265SDimitry Andric       std::swap(LHS0, LHS1);
330181ad6265SDimitry Andric     }
3302e8d8bef9SDimitry Andric     if (LHS0 == RHS0 && LHS1 == RHS1) {
330381ad6265SDimitry Andric       unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR)
330481ad6265SDimitry Andric                             : getICmpCode(PredL) | getICmpCode(PredR);
33050b57cec5SDimitry Andric       bool IsSigned = LHS->isSigned() || RHS->isSigned();
3306e8d8bef9SDimitry Andric       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
33070b57cec5SDimitry Andric     }
33080b57cec5SDimitry Andric   }
33090b57cec5SDimitry Andric 
33100b57cec5SDimitry Andric   // handle (roughly):
33110b57cec5SDimitry Andric   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
331281ad6265SDimitry Andric   // (icmp eq (A & B), C) & (icmp eq (A & D), E)
331381ad6265SDimitry Andric   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder))
33140b57cec5SDimitry Andric     return V;
33150b57cec5SDimitry Andric 
3316bdd1243dSDimitry Andric   if (Value *V =
331706c3fb27SDimitry Andric           foldAndOrOfICmpEqConstantAndICmp(LHS, RHS, IsAnd, IsLogical, Builder))
331881ad6265SDimitry Andric     return V;
3319bdd1243dSDimitry Andric   // We can treat logical like bitwise here, because both operands are used on
3320bdd1243dSDimitry Andric   // the LHS, and as such poison from both will propagate.
332106c3fb27SDimitry Andric   if (Value *V = foldAndOrOfICmpEqConstantAndICmp(RHS, LHS, IsAnd,
3322bdd1243dSDimitry Andric                                                   /*IsLogical*/ false, Builder))
332381ad6265SDimitry Andric     return V;
33240b57cec5SDimitry Andric 
3325bdd1243dSDimitry Andric   if (Value *V =
3326bdd1243dSDimitry Andric           foldAndOrOfICmpsWithConstEq(LHS, RHS, IsAnd, IsLogical, Builder, Q))
33275ffd83dbSDimitry Andric     return V;
3328bdd1243dSDimitry Andric   // We can convert this case to bitwise and, because both operands are used
3329bdd1243dSDimitry Andric   // on the LHS, and as such poison from both will propagate.
3330bdd1243dSDimitry Andric   if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, IsAnd,
3331bdd1243dSDimitry Andric                                              /*IsLogical*/ false, Builder, Q))
333281ad6265SDimitry Andric     return V;
333381ad6265SDimitry Andric 
333481ad6265SDimitry Andric   if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder))
333581ad6265SDimitry Andric     return V;
333681ad6265SDimitry Andric   if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder))
33375ffd83dbSDimitry Andric     return V;
33385ffd83dbSDimitry Andric 
333981ad6265SDimitry Andric   // TODO: One of these directions is fine with logical and/or, the other could
334081ad6265SDimitry Andric   // be supported by inserting freeze.
334181ad6265SDimitry Andric   if (!IsLogical) {
33420b57cec5SDimitry Andric     // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
334381ad6265SDimitry Andric     // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
334481ad6265SDimitry Andric     if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/!IsAnd))
33450b57cec5SDimitry Andric       return V;
33460b57cec5SDimitry Andric 
33470b57cec5SDimitry Andric     // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
334881ad6265SDimitry Andric     // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
334981ad6265SDimitry Andric     if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/!IsAnd))
335081ad6265SDimitry Andric       return V;
335181ad6265SDimitry Andric   }
335281ad6265SDimitry Andric 
335381ad6265SDimitry Andric   // TODO: Add conjugated or fold, check whether it is safe for logical and/or.
335481ad6265SDimitry Andric   if (IsAnd && !IsLogical)
335581ad6265SDimitry Andric     if (Value *V = foldSignedTruncationCheck(LHS, RHS, I, Builder))
33560b57cec5SDimitry Andric       return V;
33570b57cec5SDimitry Andric 
3358*5deeebd8SDimitry Andric   if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder, *this))
33590b57cec5SDimitry Andric     return V;
33600b57cec5SDimitry Andric 
336106c3fb27SDimitry Andric   if (Value *V = foldPowerOf2AndShiftedMask(LHS, RHS, IsAnd, Builder))
336206c3fb27SDimitry Andric     return V;
336306c3fb27SDimitry Andric 
336481ad6265SDimitry Andric   // TODO: Verify whether this is safe for logical and/or.
336581ad6265SDimitry Andric   if (!IsLogical) {
336681ad6265SDimitry Andric     if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder))
33678bcb0991SDimitry Andric       return X;
336881ad6265SDimitry Andric     if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder))
33698bcb0991SDimitry Andric       return X;
337081ad6265SDimitry Andric   }
33718bcb0991SDimitry Andric 
337281ad6265SDimitry Andric   if (Value *X = foldEqOfParts(LHS, RHS, IsAnd))
3373fe6060f1SDimitry Andric     return X;
3374fe6060f1SDimitry Andric 
3375e8d8bef9SDimitry Andric   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
337681ad6265SDimitry Andric   // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
337706c3fb27SDimitry Andric   // TODO: Remove this and below when foldLogOpOfMaskedICmps can handle undefs.
337881ad6265SDimitry Andric   if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
337981ad6265SDimitry Andric       PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) &&
3380e8d8bef9SDimitry Andric       LHS0->getType() == RHS0->getType()) {
3381e8d8bef9SDimitry Andric     Value *NewOr = Builder.CreateOr(LHS0, RHS0);
3382e8d8bef9SDimitry Andric     return Builder.CreateICmp(PredL, NewOr,
3383e8d8bef9SDimitry Andric                               Constant::getNullValue(NewOr->getType()));
3384e8d8bef9SDimitry Andric   }
3385e8d8bef9SDimitry Andric 
338606c3fb27SDimitry Andric   // (icmp ne A, -1) | (icmp ne B, -1) --> (icmp ne (A&B), -1)
338706c3fb27SDimitry Andric   // (icmp eq A, -1) & (icmp eq B, -1) --> (icmp eq (A&B), -1)
338806c3fb27SDimitry Andric   if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
338906c3fb27SDimitry Andric       PredL == PredR && match(LHS1, m_AllOnes()) && match(RHS1, m_AllOnes()) &&
339006c3fb27SDimitry Andric       LHS0->getType() == RHS0->getType()) {
339106c3fb27SDimitry Andric     Value *NewAnd = Builder.CreateAnd(LHS0, RHS0);
339206c3fb27SDimitry Andric     return Builder.CreateICmp(PredL, NewAnd,
339306c3fb27SDimitry Andric                               Constant::getAllOnesValue(LHS0->getType()));
339406c3fb27SDimitry Andric   }
339506c3fb27SDimitry Andric 
33960fca6ea1SDimitry Andric   if (!IsLogical)
33970fca6ea1SDimitry Andric     if (Value *V =
33980fca6ea1SDimitry Andric             foldAndOrOfICmpsWithPow2AndWithZero(Builder, LHS, RHS, IsAnd, Q))
33990fca6ea1SDimitry Andric       return V;
34000fca6ea1SDimitry Andric 
34010b57cec5SDimitry Andric   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
34020b57cec5SDimitry Andric   if (!LHSC || !RHSC)
34030b57cec5SDimitry Andric     return nullptr;
34040b57cec5SDimitry Andric 
340581ad6265SDimitry Andric   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
340681ad6265SDimitry Andric   // (trunc x) != C1 | (and x, CA) != C2 -> (and x, CA|CMAX) != C1|C2
340781ad6265SDimitry Andric   // where CMAX is the all ones value for the truncated type,
340881ad6265SDimitry Andric   // iff the lower bits of C2 and CA are zero.
340981ad6265SDimitry Andric   if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
341081ad6265SDimitry Andric       PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
341181ad6265SDimitry Andric     Value *V;
341281ad6265SDimitry Andric     const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
341381ad6265SDimitry Andric 
341481ad6265SDimitry Andric     // (trunc x) == C1 & (and x, CA) == C2
341581ad6265SDimitry Andric     // (and x, CA) == C2 & (trunc x) == C1
341681ad6265SDimitry Andric     if (match(RHS0, m_Trunc(m_Value(V))) &&
341781ad6265SDimitry Andric         match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
341881ad6265SDimitry Andric       SmallC = RHSC;
341981ad6265SDimitry Andric       BigC = LHSC;
342081ad6265SDimitry Andric     } else if (match(LHS0, m_Trunc(m_Value(V))) &&
342181ad6265SDimitry Andric                match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
342281ad6265SDimitry Andric       SmallC = LHSC;
342381ad6265SDimitry Andric       BigC = RHSC;
342481ad6265SDimitry Andric     }
342581ad6265SDimitry Andric 
342681ad6265SDimitry Andric     if (SmallC && BigC) {
342781ad6265SDimitry Andric       unsigned BigBitSize = BigC->getBitWidth();
342881ad6265SDimitry Andric       unsigned SmallBitSize = SmallC->getBitWidth();
342981ad6265SDimitry Andric 
343081ad6265SDimitry Andric       // Check that the low bits are zero.
343181ad6265SDimitry Andric       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
343281ad6265SDimitry Andric       if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
343381ad6265SDimitry Andric         Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
343481ad6265SDimitry Andric         APInt N = SmallC->zext(BigBitSize) | *BigC;
343581ad6265SDimitry Andric         Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
343681ad6265SDimitry Andric         return Builder.CreateICmp(PredL, NewAnd, NewVal);
343781ad6265SDimitry Andric       }
343881ad6265SDimitry Andric     }
343981ad6265SDimitry Andric   }
344081ad6265SDimitry Andric 
344181ad6265SDimitry Andric   // Match naive pattern (and its inverted form) for checking if two values
344281ad6265SDimitry Andric   // share same sign. An example of the pattern:
344381ad6265SDimitry Andric   // (icmp slt (X & Y), 0) | (icmp sgt (X | Y), -1) -> (icmp sgt (X ^ Y), -1)
344481ad6265SDimitry Andric   // Inverted form (example):
344581ad6265SDimitry Andric   // (icmp slt (X | Y), 0) & (icmp sgt (X & Y), -1) -> (icmp slt (X ^ Y), 0)
344681ad6265SDimitry Andric   bool TrueIfSignedL, TrueIfSignedR;
3447fcaf7f86SDimitry Andric   if (isSignBitCheck(PredL, *LHSC, TrueIfSignedL) &&
3448fcaf7f86SDimitry Andric       isSignBitCheck(PredR, *RHSC, TrueIfSignedR) &&
344981ad6265SDimitry Andric       (RHS->hasOneUse() || LHS->hasOneUse())) {
345081ad6265SDimitry Andric     Value *X, *Y;
345181ad6265SDimitry Andric     if (IsAnd) {
345281ad6265SDimitry Andric       if ((TrueIfSignedL && !TrueIfSignedR &&
345381ad6265SDimitry Andric            match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
345481ad6265SDimitry Andric            match(RHS0, m_c_And(m_Specific(X), m_Specific(Y)))) ||
345581ad6265SDimitry Andric           (!TrueIfSignedL && TrueIfSignedR &&
345681ad6265SDimitry Andric            match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
345781ad6265SDimitry Andric            match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y))))) {
345881ad6265SDimitry Andric         Value *NewXor = Builder.CreateXor(X, Y);
345981ad6265SDimitry Andric         return Builder.CreateIsNeg(NewXor);
346081ad6265SDimitry Andric       }
346181ad6265SDimitry Andric     } else {
346281ad6265SDimitry Andric       if ((TrueIfSignedL && !TrueIfSignedR &&
346381ad6265SDimitry Andric             match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
346481ad6265SDimitry Andric             match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y)))) ||
346581ad6265SDimitry Andric           (!TrueIfSignedL && TrueIfSignedR &&
346681ad6265SDimitry Andric            match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
346781ad6265SDimitry Andric            match(RHS0, m_c_And(m_Specific(X), m_Specific(Y))))) {
346881ad6265SDimitry Andric         Value *NewXor = Builder.CreateXor(X, Y);
346981ad6265SDimitry Andric         return Builder.CreateIsNotNeg(NewXor);
347081ad6265SDimitry Andric       }
347181ad6265SDimitry Andric     }
347281ad6265SDimitry Andric   }
347381ad6265SDimitry Andric 
347481ad6265SDimitry Andric   return foldAndOrOfICmpsUsingRanges(LHS, RHS, IsAnd);
34750b57cec5SDimitry Andric }
34760b57cec5SDimitry Andric 
34770fca6ea1SDimitry Andric static Value *foldOrOfInversions(BinaryOperator &I,
34780fca6ea1SDimitry Andric                                  InstCombiner::BuilderTy &Builder) {
34790fca6ea1SDimitry Andric   assert(I.getOpcode() == Instruction::Or &&
34800fca6ea1SDimitry Andric          "Simplification only supports or at the moment.");
34810fca6ea1SDimitry Andric 
34820fca6ea1SDimitry Andric   Value *Cmp1, *Cmp2, *Cmp3, *Cmp4;
34830fca6ea1SDimitry Andric   if (!match(I.getOperand(0), m_And(m_Value(Cmp1), m_Value(Cmp2))) ||
34840fca6ea1SDimitry Andric       !match(I.getOperand(1), m_And(m_Value(Cmp3), m_Value(Cmp4))))
34850fca6ea1SDimitry Andric     return nullptr;
34860fca6ea1SDimitry Andric 
34870fca6ea1SDimitry Andric   // Check if any two pairs of the and operations are inversions of each other.
34880fca6ea1SDimitry Andric   if (isKnownInversion(Cmp1, Cmp3) && isKnownInversion(Cmp2, Cmp4))
34890fca6ea1SDimitry Andric     return Builder.CreateXor(Cmp1, Cmp4);
34900fca6ea1SDimitry Andric   if (isKnownInversion(Cmp1, Cmp4) && isKnownInversion(Cmp2, Cmp3))
34910fca6ea1SDimitry Andric     return Builder.CreateXor(Cmp1, Cmp3);
34920fca6ea1SDimitry Andric 
34930fca6ea1SDimitry Andric   return nullptr;
34940fca6ea1SDimitry Andric }
34950fca6ea1SDimitry Andric 
34960b57cec5SDimitry Andric // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
34970b57cec5SDimitry Andric // here. We should standardize that construct where it is needed or choose some
34980b57cec5SDimitry Andric // other way to ensure that commutated variants of patterns are not missed.
3499e8d8bef9SDimitry Andric Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
350081ad6265SDimitry Andric   if (Value *V = simplifyOrInst(I.getOperand(0), I.getOperand(1),
35010b57cec5SDimitry Andric                                 SQ.getWithInstruction(&I)))
35020b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric   if (SimplifyAssociativeOrCommutative(I))
35050b57cec5SDimitry Andric     return &I;
35060b57cec5SDimitry Andric 
35070b57cec5SDimitry Andric   if (Instruction *X = foldVectorBinop(I))
35080b57cec5SDimitry Andric     return X;
35090b57cec5SDimitry Andric 
351004eeddc0SDimitry Andric   if (Instruction *Phi = foldBinopWithPhiOperands(I))
351104eeddc0SDimitry Andric     return Phi;
351204eeddc0SDimitry Andric 
35130b57cec5SDimitry Andric   // See if we can simplify any instructions used by the instruction whose sole
35140b57cec5SDimitry Andric   // purpose is to compute bits we don't care about.
35150b57cec5SDimitry Andric   if (SimplifyDemandedInstructionBits(I))
35160b57cec5SDimitry Andric     return &I;
35170b57cec5SDimitry Andric 
35180b57cec5SDimitry Andric   // Do this before using distributive laws to catch simple and/or/not patterns.
35190b57cec5SDimitry Andric   if (Instruction *Xor = foldOrToXor(I, Builder))
35200b57cec5SDimitry Andric     return Xor;
35210b57cec5SDimitry Andric 
3522349cc55cSDimitry Andric   if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
3523349cc55cSDimitry Andric     return X;
3524349cc55cSDimitry Andric 
35250fca6ea1SDimitry Andric   // (A & B) | (C & D) -> A ^ D where A == ~C && B == ~D
35260fca6ea1SDimitry Andric   // (A & B) | (C & D) -> A ^ C where A == ~D && B == ~C
35270fca6ea1SDimitry Andric   if (Value *V = foldOrOfInversions(I, Builder))
35280fca6ea1SDimitry Andric     return replaceInstUsesWith(I, V);
35290fca6ea1SDimitry Andric 
35300b57cec5SDimitry Andric   // (A&B)|(A&C) -> A&(B|C) etc
3531bdd1243dSDimitry Andric   if (Value *V = foldUsingDistributiveLaws(I))
35320b57cec5SDimitry Andric     return replaceInstUsesWith(I, V);
35330b57cec5SDimitry Andric 
3534fe6060f1SDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
35354824e7fdSDimitry Andric   Type *Ty = I.getType();
35364824e7fdSDimitry Andric   if (Ty->isIntOrIntVectorTy(1)) {
3537fe6060f1SDimitry Andric     if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
35385f757f3fSDimitry Andric       if (auto *R =
3539fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false))
35405f757f3fSDimitry Andric         return R;
3541fe6060f1SDimitry Andric     }
3542fe6060f1SDimitry Andric     if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
35435f757f3fSDimitry Andric       if (auto *R =
3544fe6060f1SDimitry Andric               foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false))
35455f757f3fSDimitry Andric         return R;
3546fe6060f1SDimitry Andric     }
3547fe6060f1SDimitry Andric   }
3548fe6060f1SDimitry Andric 
35490b57cec5SDimitry Andric   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
35500b57cec5SDimitry Andric     return FoldedLogic;
35510b57cec5SDimitry Andric 
3552fe6060f1SDimitry Andric   if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true,
3553fe6060f1SDimitry Andric                                                   /*MatchBitReversals*/ true))
3554fe6060f1SDimitry Andric     return BitOp;
35550b57cec5SDimitry Andric 
35560fca6ea1SDimitry Andric   if (Instruction *Funnel = matchFunnelShift(I, *this))
3557e8d8bef9SDimitry Andric     return Funnel;
35580b57cec5SDimitry Andric 
35595ffd83dbSDimitry Andric   if (Instruction *Concat = matchOrConcat(I, Builder))
35605ffd83dbSDimitry Andric     return replaceInstUsesWith(I, Concat);
35615ffd83dbSDimitry Andric 
356206c3fb27SDimitry Andric   if (Instruction *R = foldBinOpShiftWithShift(I))
356306c3fb27SDimitry Andric     return R;
356406c3fb27SDimitry Andric 
35657a6dacacSDimitry Andric   if (Instruction *R = tryFoldInstWithCtpopWithNot(&I))
35667a6dacacSDimitry Andric     return R;
35677a6dacacSDimitry Andric 
35680b57cec5SDimitry Andric   Value *X, *Y;
35690b57cec5SDimitry Andric   const APInt *CV;
35700b57cec5SDimitry Andric   if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
3571349cc55cSDimitry Andric       !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
35720b57cec5SDimitry Andric     // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0
35730b57cec5SDimitry Andric     // The check for a 'not' op is for efficiency (if Y is known zero --> ~X).
35740b57cec5SDimitry Andric     Value *Or = Builder.CreateOr(X, Y);
35754824e7fdSDimitry Andric     return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
35764824e7fdSDimitry Andric   }
35774824e7fdSDimitry Andric 
35784824e7fdSDimitry Andric   // If the operands have no common bits set:
35794824e7fdSDimitry Andric   // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1)
35805f757f3fSDimitry Andric   if (match(&I, m_c_DisjointOr(m_OneUse(m_Mul(m_Value(X), m_Value(Y))),
35815f757f3fSDimitry Andric                                m_Deferred(X)))) {
35824824e7fdSDimitry Andric     Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
35834824e7fdSDimitry Andric     return BinaryOperator::CreateMul(X, IncrementY);
35840b57cec5SDimitry Andric   }
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric   // (A & C) | (B & D)
35870b57cec5SDimitry Andric   Value *A, *B, *C, *D;
35880b57cec5SDimitry Andric   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
35890b57cec5SDimitry Andric       match(Op1, m_And(m_Value(B), m_Value(D)))) {
35900b57cec5SDimitry Andric 
3591349cc55cSDimitry Andric     // (A & C0) | (B & C1)
3592349cc55cSDimitry Andric     const APInt *C0, *C1;
3593349cc55cSDimitry Andric     if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
35940b57cec5SDimitry Andric       Value *X;
3595349cc55cSDimitry Andric       if (*C0 == ~*C1) {
3596349cc55cSDimitry Andric         // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B
35970b57cec5SDimitry Andric         if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
3598349cc55cSDimitry Andric           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
3599349cc55cSDimitry Andric         // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A
36000b57cec5SDimitry Andric         if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
3601349cc55cSDimitry Andric           return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
36020b57cec5SDimitry Andric 
3603349cc55cSDimitry Andric         // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B
36040b57cec5SDimitry Andric         if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
3605349cc55cSDimitry Andric           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
3606349cc55cSDimitry Andric         // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A
36070b57cec5SDimitry Andric         if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
3608349cc55cSDimitry Andric           return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
3609349cc55cSDimitry Andric       }
3610349cc55cSDimitry Andric 
3611349cc55cSDimitry Andric       if ((*C0 & *C1).isZero()) {
3612349cc55cSDimitry Andric         // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1)
3613349cc55cSDimitry Andric         // iff (C0 & C1) == 0 and (X & ~C0) == 0
3614349cc55cSDimitry Andric         if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
3615349cc55cSDimitry Andric             MaskedValueIsZero(X, ~*C0, 0, &I)) {
36164824e7fdSDimitry Andric           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3617349cc55cSDimitry Andric           return BinaryOperator::CreateAnd(A, C01);
3618349cc55cSDimitry Andric         }
3619349cc55cSDimitry Andric         // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1)
3620349cc55cSDimitry Andric         // iff (C0 & C1) == 0 and (X & ~C1) == 0
3621349cc55cSDimitry Andric         if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
3622349cc55cSDimitry Andric             MaskedValueIsZero(X, ~*C1, 0, &I)) {
36234824e7fdSDimitry Andric           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3624349cc55cSDimitry Andric           return BinaryOperator::CreateAnd(B, C01);
3625349cc55cSDimitry Andric         }
3626349cc55cSDimitry Andric         // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1)
3627349cc55cSDimitry Andric         // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0.
3628349cc55cSDimitry Andric         const APInt *C2, *C3;
3629349cc55cSDimitry Andric         if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
3630349cc55cSDimitry Andric             match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
3631349cc55cSDimitry Andric             (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
3632349cc55cSDimitry Andric           Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
36334824e7fdSDimitry Andric           Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
3634349cc55cSDimitry Andric           return BinaryOperator::CreateAnd(Or, C01);
3635349cc55cSDimitry Andric         }
36360b57cec5SDimitry Andric       }
36370b57cec5SDimitry Andric     }
36380b57cec5SDimitry Andric 
36390b57cec5SDimitry Andric     // Don't try to form a select if it's unlikely that we'll get rid of at
36400b57cec5SDimitry Andric     // least one of the operands. A select is generally more expensive than the
36410b57cec5SDimitry Andric     // 'or' that it is replacing.
36420b57cec5SDimitry Andric     if (Op0->hasOneUse() || Op1->hasOneUse()) {
36430b57cec5SDimitry Andric       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
36440b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(A, C, B, D))
36450b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36460b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(A, C, D, B))
36470b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36480b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(C, A, B, D))
36490b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36500b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(C, A, D, B))
36510b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36520b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(B, D, A, C))
36530b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36540b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(B, D, C, A))
36550b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36560b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(D, B, A, C))
36570b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36580b57cec5SDimitry Andric       if (Value *V = matchSelectFromAndOr(D, B, C, A))
36590b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
36600b57cec5SDimitry Andric     }
36610b57cec5SDimitry Andric   }
36620b57cec5SDimitry Andric 
3663bdd1243dSDimitry Andric   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3664bdd1243dSDimitry Andric       match(Op1, m_Not(m_Or(m_Value(B), m_Value(D)))) &&
3665bdd1243dSDimitry Andric       (Op0->hasOneUse() || Op1->hasOneUse())) {
3666bdd1243dSDimitry Andric     // (Cond & C) | ~(Cond | D) -> Cond ? C : ~D
3667bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(A, C, B, D, true))
3668bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3669bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(A, C, D, B, true))
3670bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3671bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(C, A, B, D, true))
3672bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3673bdd1243dSDimitry Andric     if (Value *V = matchSelectFromAndOr(C, A, D, B, true))
3674bdd1243dSDimitry Andric       return replaceInstUsesWith(I, V);
3675bdd1243dSDimitry Andric   }
3676bdd1243dSDimitry Andric 
36770b57cec5SDimitry Andric   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
36780b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
36790fca6ea1SDimitry Andric     if (match(Op1,
36800fca6ea1SDimitry Andric               m_c_Xor(m_c_Xor(m_Specific(B), m_Value(C)), m_Specific(A))) ||
36810fca6ea1SDimitry Andric         match(Op1, m_c_Xor(m_c_Xor(m_Specific(A), m_Value(C)), m_Specific(B))))
36820b57cec5SDimitry Andric       return BinaryOperator::CreateOr(Op0, C);
36830b57cec5SDimitry Andric 
36840fca6ea1SDimitry Andric   // ((B ^ C) ^ A) | (A ^ B) -> (A ^ B) | C
36850fca6ea1SDimitry Andric   if (match(Op1, m_Xor(m_Value(A), m_Value(B))))
36860fca6ea1SDimitry Andric     if (match(Op0,
36870fca6ea1SDimitry Andric               m_c_Xor(m_c_Xor(m_Specific(B), m_Value(C)), m_Specific(A))) ||
36880fca6ea1SDimitry Andric         match(Op0, m_c_Xor(m_c_Xor(m_Specific(A), m_Value(C)), m_Specific(B))))
36890b57cec5SDimitry Andric       return BinaryOperator::CreateOr(Op1, C);
36900b57cec5SDimitry Andric 
36915f757f3fSDimitry Andric   if (Instruction *DeMorgan = matchDeMorgansLaws(I, *this))
36920b57cec5SDimitry Andric     return DeMorgan;
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric   // Canonicalize xor to the RHS.
36950b57cec5SDimitry Andric   bool SwappedForXor = false;
36960b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
36970b57cec5SDimitry Andric     std::swap(Op0, Op1);
36980b57cec5SDimitry Andric     SwappedForXor = true;
36990b57cec5SDimitry Andric   }
37000b57cec5SDimitry Andric 
37010b57cec5SDimitry Andric   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3702bdd1243dSDimitry Andric     // (A | ?) | (A ^ B) --> (A | ?) | B
3703bdd1243dSDimitry Andric     // (B | ?) | (A ^ B) --> (B | ?) | A
3704bdd1243dSDimitry Andric     if (match(Op0, m_c_Or(m_Specific(A), m_Value())))
3705bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(Op0, B);
3706bdd1243dSDimitry Andric     if (match(Op0, m_c_Or(m_Specific(B), m_Value())))
3707bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(Op0, A);
37080b57cec5SDimitry Andric 
3709bdd1243dSDimitry Andric     // (A & B) | (A ^ B) --> A | B
3710bdd1243dSDimitry Andric     // (B & A) | (A ^ B) --> A | B
37110fca6ea1SDimitry Andric     if (match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
37120b57cec5SDimitry Andric       return BinaryOperator::CreateOr(A, B);
37130b57cec5SDimitry Andric 
3714bdd1243dSDimitry Andric     // ~A | (A ^ B) --> ~(A & B)
3715bdd1243dSDimitry Andric     // ~B | (A ^ B) --> ~(A & B)
3716bdd1243dSDimitry Andric     // The swap above should always make Op0 the 'not'.
3717349cc55cSDimitry Andric     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3718349cc55cSDimitry Andric         (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
3719349cc55cSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
3720349cc55cSDimitry Andric 
3721bdd1243dSDimitry Andric     // Same as above, but peek through an 'and' to the common operand:
3722bdd1243dSDimitry Andric     // ~(A & ?) | (A ^ B) --> ~((A & ?) & B)
3723bdd1243dSDimitry Andric     // ~(B & ?) | (A ^ B) --> ~((B & ?) & A)
3724bdd1243dSDimitry Andric     Instruction *And;
3725bdd1243dSDimitry Andric     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3726bdd1243dSDimitry Andric         match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
3727bdd1243dSDimitry Andric                                       m_c_And(m_Specific(A), m_Value())))))
3728bdd1243dSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(And, B));
3729bdd1243dSDimitry Andric     if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
3730bdd1243dSDimitry Andric         match(Op0, m_Not(m_CombineAnd(m_Instruction(And),
3731bdd1243dSDimitry Andric                                       m_c_And(m_Specific(B), m_Value())))))
3732bdd1243dSDimitry Andric       return BinaryOperator::CreateNot(Builder.CreateAnd(And, A));
3733bdd1243dSDimitry Andric 
3734bdd1243dSDimitry Andric     // (~A | C) | (A ^ B) --> ~(A & B) | C
3735bdd1243dSDimitry Andric     // (~B | C) | (A ^ B) --> ~(A & B) | C
3736bdd1243dSDimitry Andric     if (Op0->hasOneUse() && Op1->hasOneUse() &&
3737bdd1243dSDimitry Andric         (match(Op0, m_c_Or(m_Not(m_Specific(A)), m_Value(C))) ||
3738bdd1243dSDimitry Andric          match(Op0, m_c_Or(m_Not(m_Specific(B)), m_Value(C))))) {
3739bdd1243dSDimitry Andric       Value *Nand = Builder.CreateNot(Builder.CreateAnd(A, B), "nand");
3740bdd1243dSDimitry Andric       return BinaryOperator::CreateOr(Nand, C);
3741bdd1243dSDimitry Andric     }
37420b57cec5SDimitry Andric   }
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric   if (SwappedForXor)
37450b57cec5SDimitry Andric     std::swap(Op0, Op1);
37460b57cec5SDimitry Andric 
37470b57cec5SDimitry Andric   {
37480b57cec5SDimitry Andric     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
37490b57cec5SDimitry Andric     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
37500b57cec5SDimitry Andric     if (LHS && RHS)
375181ad6265SDimitry Andric       if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ false))
37520b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric     // TODO: Make this recursive; it's a little tricky because an arbitrary
37550b57cec5SDimitry Andric     // number of 'or' instructions might have to be created.
37560b57cec5SDimitry Andric     Value *X, *Y;
375781ad6265SDimitry Andric     if (LHS && match(Op1, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
375881ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op1);
375981ad6265SDimitry Andric       // LHS | (X || Y) --> (LHS || X) || Y
37600b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
376181ad6265SDimitry Andric         if (Value *Res =
376281ad6265SDimitry Andric                 foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false, IsLogical))
376381ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
376481ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(Res, Y)
376581ad6265SDimitry Andric                                             : Builder.CreateOr(Res, Y));
376681ad6265SDimitry Andric       // LHS | (X || Y) --> X || (LHS | Y)
37670b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
376881ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false,
376981ad6265SDimitry Andric                                           /* IsLogical */ false))
377081ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
377181ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(X, Res)
377281ad6265SDimitry Andric                                             : Builder.CreateOr(X, Res));
37730b57cec5SDimitry Andric     }
377481ad6265SDimitry Andric     if (RHS && match(Op0, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
377581ad6265SDimitry Andric       bool IsLogical = isa<SelectInst>(Op0);
377681ad6265SDimitry Andric       // (X || Y) | RHS --> (X || RHS) || Y
37770b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(X))
377881ad6265SDimitry Andric         if (Value *Res =
377981ad6265SDimitry Andric                 foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false, IsLogical))
378081ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
378181ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(Res, Y)
378281ad6265SDimitry Andric                                             : Builder.CreateOr(Res, Y));
378381ad6265SDimitry Andric       // (X || Y) | RHS --> X || (Y | RHS)
37840b57cec5SDimitry Andric       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
378581ad6265SDimitry Andric         if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false,
378681ad6265SDimitry Andric                                           /* IsLogical */ false))
378781ad6265SDimitry Andric           return replaceInstUsesWith(I, IsLogical
378881ad6265SDimitry Andric                                             ? Builder.CreateLogicalOr(X, Res)
378981ad6265SDimitry Andric                                             : Builder.CreateOr(X, Res));
37900b57cec5SDimitry Andric     }
37910b57cec5SDimitry Andric   }
37920b57cec5SDimitry Andric 
37930b57cec5SDimitry Andric   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
37940b57cec5SDimitry Andric     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
379581ad6265SDimitry Andric       if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false))
37960b57cec5SDimitry Andric         return replaceInstUsesWith(I, Res);
37970b57cec5SDimitry Andric 
37980b57cec5SDimitry Andric   if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
37990b57cec5SDimitry Andric     return FoldedFCmps;
38000b57cec5SDimitry Andric 
38010b57cec5SDimitry Andric   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
38020b57cec5SDimitry Andric     return CastedOr;
38030b57cec5SDimitry Andric 
38044824e7fdSDimitry Andric   if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
38054824e7fdSDimitry Andric     return Sel;
38064824e7fdSDimitry Andric 
38070b57cec5SDimitry Andric   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
38084824e7fdSDimitry Andric   // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold
38094824e7fdSDimitry Andric   //       with binop identity constant. But creating a select with non-constant
38104824e7fdSDimitry Andric   //       arm may not be reversible due to poison semantics. Is that a good
38114824e7fdSDimitry Andric   //       canonicalization?
38125f757f3fSDimitry Andric   if (match(&I, m_c_Or(m_OneUse(m_SExt(m_Value(A))), m_Value(B))) &&
38130b57cec5SDimitry Andric       A->getType()->isIntOrIntVectorTy(1))
38145f757f3fSDimitry Andric     return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), B);
38150b57cec5SDimitry Andric 
38160b57cec5SDimitry Andric   // Note: If we've gotten to the point of visiting the outer OR, then the
38170b57cec5SDimitry Andric   // inner one couldn't be simplified.  If it was a constant, then it won't
38180b57cec5SDimitry Andric   // be simplified by a later pass either, so we try swapping the inner/outer
38190b57cec5SDimitry Andric   // ORs in the hopes that we'll be able to simplify it this way.
38200b57cec5SDimitry Andric   // (X|C) | V --> (X|V) | C
38210b57cec5SDimitry Andric   ConstantInt *CI;
3822e8d8bef9SDimitry Andric   if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
38230b57cec5SDimitry Andric       match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
38240b57cec5SDimitry Andric     Value *Inner = Builder.CreateOr(A, Op1);
38250b57cec5SDimitry Andric     Inner->takeName(Op0);
38260b57cec5SDimitry Andric     return BinaryOperator::CreateOr(Inner, CI);
38270b57cec5SDimitry Andric   }
38280b57cec5SDimitry Andric 
38290b57cec5SDimitry Andric   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
38300b57cec5SDimitry Andric   // Since this OR statement hasn't been optimized further yet, we hope
38310b57cec5SDimitry Andric   // that this transformation will allow the new ORs to be optimized.
38320b57cec5SDimitry Andric   {
38330b57cec5SDimitry Andric     Value *X = nullptr, *Y = nullptr;
38340b57cec5SDimitry Andric     if (Op0->hasOneUse() && Op1->hasOneUse() &&
38350b57cec5SDimitry Andric         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
38360b57cec5SDimitry Andric         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
38370b57cec5SDimitry Andric       Value *orTrue = Builder.CreateOr(A, C);
38380b57cec5SDimitry Andric       Value *orFalse = Builder.CreateOr(B, D);
38390b57cec5SDimitry Andric       return SelectInst::Create(X, orTrue, orFalse);
38400b57cec5SDimitry Andric     }
38410b57cec5SDimitry Andric   }
38420b57cec5SDimitry Andric 
38438bcb0991SDimitry Andric   // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X)  --> X s> Y ? -1 : X.
38448bcb0991SDimitry Andric   {
38458bcb0991SDimitry Andric     Value *X, *Y;
3846e8d8bef9SDimitry Andric     if (match(&I, m_c_Or(m_OneUse(m_AShr(
3847e8d8bef9SDimitry Andric                              m_NSWSub(m_Value(Y), m_Value(X)),
3848e8d8bef9SDimitry Andric                              m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
3849e8d8bef9SDimitry Andric                          m_Deferred(X)))) {
38508bcb0991SDimitry Andric       Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
3851e8d8bef9SDimitry Andric       Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
3852e8d8bef9SDimitry Andric       return SelectInst::Create(NewICmpInst, AllOnes, X);
38538bcb0991SDimitry Andric     }
38548bcb0991SDimitry Andric   }
38558bcb0991SDimitry Andric 
38565f757f3fSDimitry Andric   {
38575f757f3fSDimitry Andric     // ((A & B) ^ A) | ((A & B) ^ B) -> A ^ B
38585f757f3fSDimitry Andric     // (A ^ (A & B)) | (B ^ (A & B)) -> A ^ B
38595f757f3fSDimitry Andric     // ((A & B) ^ B) | ((A & B) ^ A) -> A ^ B
38605f757f3fSDimitry Andric     // (B ^ (A & B)) | (A ^ (A & B)) -> A ^ B
38615f757f3fSDimitry Andric     const auto TryXorOpt = [&](Value *Lhs, Value *Rhs) -> Instruction * {
38625f757f3fSDimitry Andric       if (match(Lhs, m_c_Xor(m_And(m_Value(A), m_Value(B)), m_Deferred(A))) &&
38635f757f3fSDimitry Andric           match(Rhs,
38640fca6ea1SDimitry Andric                 m_c_Xor(m_And(m_Specific(A), m_Specific(B)), m_Specific(B)))) {
38655f757f3fSDimitry Andric         return BinaryOperator::CreateXor(A, B);
38665f757f3fSDimitry Andric       }
38675f757f3fSDimitry Andric       return nullptr;
38685f757f3fSDimitry Andric     };
38695f757f3fSDimitry Andric 
38705f757f3fSDimitry Andric     if (Instruction *Result = TryXorOpt(Op0, Op1))
38715f757f3fSDimitry Andric       return Result;
38725f757f3fSDimitry Andric     if (Instruction *Result = TryXorOpt(Op1, Op0))
38735f757f3fSDimitry Andric       return Result;
38745f757f3fSDimitry Andric   }
38755f757f3fSDimitry Andric 
38768bcb0991SDimitry Andric   if (Instruction *V =
38778bcb0991SDimitry Andric           canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
38788bcb0991SDimitry Andric     return V;
38798bcb0991SDimitry Andric 
38805ffd83dbSDimitry Andric   CmpInst::Predicate Pred;
38815ffd83dbSDimitry Andric   Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
38825ffd83dbSDimitry Andric   // Check if the OR weakens the overflow condition for umul.with.overflow by
38835ffd83dbSDimitry Andric   // treating any non-zero result as overflow. In that case, we overflow if both
38845ffd83dbSDimitry Andric   // umul.with.overflow operands are != 0, as in that case the result can only
38855ffd83dbSDimitry Andric   // be 0, iff the multiplication overflows.
38865ffd83dbSDimitry Andric   if (match(&I,
38875ffd83dbSDimitry Andric             m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
38885ffd83dbSDimitry Andric                                 m_Value(Ov)),
38895ffd83dbSDimitry Andric                    m_CombineAnd(m_ICmp(Pred,
38905ffd83dbSDimitry Andric                                        m_CombineAnd(m_ExtractValue<0>(
38915ffd83dbSDimitry Andric                                                         m_Deferred(UMulWithOv)),
38925ffd83dbSDimitry Andric                                                     m_Value(Mul)),
38935ffd83dbSDimitry Andric                                        m_ZeroInt()),
38945ffd83dbSDimitry Andric                                 m_Value(MulIsNotZero)))) &&
38955ffd83dbSDimitry Andric       (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
38965ffd83dbSDimitry Andric       Pred == CmpInst::ICMP_NE) {
38975ffd83dbSDimitry Andric     Value *A, *B;
38985ffd83dbSDimitry Andric     if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
38995ffd83dbSDimitry Andric                               m_Value(A), m_Value(B)))) {
39005ffd83dbSDimitry Andric       Value *NotNullA = Builder.CreateIsNotNull(A);
39015ffd83dbSDimitry Andric       Value *NotNullB = Builder.CreateIsNotNull(B);
39025ffd83dbSDimitry Andric       return BinaryOperator::CreateAnd(NotNullA, NotNullB);
39035ffd83dbSDimitry Andric     }
39045ffd83dbSDimitry Andric   }
39055ffd83dbSDimitry Andric 
39065f757f3fSDimitry Andric   /// Res, Overflow = xxx_with_overflow X, C1
39075f757f3fSDimitry Andric   /// Try to canonicalize the pattern "Overflow | icmp pred Res, C2" into
39085f757f3fSDimitry Andric   /// "Overflow | icmp pred X, C2 +/- C1".
39095f757f3fSDimitry Andric   const WithOverflowInst *WO;
39105f757f3fSDimitry Andric   const Value *WOV;
39115f757f3fSDimitry Andric   const APInt *C1, *C2;
39125f757f3fSDimitry Andric   if (match(&I, m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_CombineAnd(
39135f757f3fSDimitry Andric                                         m_WithOverflowInst(WO), m_Value(WOV))),
39145f757f3fSDimitry Andric                                     m_Value(Ov)),
39155f757f3fSDimitry Andric                        m_OneUse(m_ICmp(Pred, m_ExtractValue<0>(m_Deferred(WOV)),
39165f757f3fSDimitry Andric                                        m_APInt(C2))))) &&
39175f757f3fSDimitry Andric       (WO->getBinaryOp() == Instruction::Add ||
39185f757f3fSDimitry Andric        WO->getBinaryOp() == Instruction::Sub) &&
39195f757f3fSDimitry Andric       (ICmpInst::isEquality(Pred) ||
39205f757f3fSDimitry Andric        WO->isSigned() == ICmpInst::isSigned(Pred)) &&
39215f757f3fSDimitry Andric       match(WO->getRHS(), m_APInt(C1))) {
39225f757f3fSDimitry Andric     bool Overflow;
39235f757f3fSDimitry Andric     APInt NewC = WO->getBinaryOp() == Instruction::Add
39245f757f3fSDimitry Andric                      ? (ICmpInst::isSigned(Pred) ? C2->ssub_ov(*C1, Overflow)
39255f757f3fSDimitry Andric                                                  : C2->usub_ov(*C1, Overflow))
39265f757f3fSDimitry Andric                      : (ICmpInst::isSigned(Pred) ? C2->sadd_ov(*C1, Overflow)
39275f757f3fSDimitry Andric                                                  : C2->uadd_ov(*C1, Overflow));
39285f757f3fSDimitry Andric     if (!Overflow || ICmpInst::isEquality(Pred)) {
39295f757f3fSDimitry Andric       Value *NewCmp = Builder.CreateICmp(
39305f757f3fSDimitry Andric           Pred, WO->getLHS(), ConstantInt::get(WO->getLHS()->getType(), NewC));
39315f757f3fSDimitry Andric       return BinaryOperator::CreateOr(Ov, NewCmp);
39325f757f3fSDimitry Andric     }
39335f757f3fSDimitry Andric   }
39345f757f3fSDimitry Andric 
3935e8d8bef9SDimitry Andric   // (~x) | y  -->  ~(x & (~y))  iff that gets rid of inversions
3936bdd1243dSDimitry Andric   if (sinkNotIntoOtherHandOfLogicalOp(I))
3937e8d8bef9SDimitry Andric     return &I;
3938e8d8bef9SDimitry Andric 
3939fe6060f1SDimitry Andric   // Improve "get low bit mask up to and including bit X" pattern:
3940fe6060f1SDimitry Andric   //   (1 << X) | ((1 << X) + -1)  -->  -1 l>> (bitwidth(x) - 1 - X)
3941fe6060f1SDimitry Andric   if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
3942fe6060f1SDimitry Andric                        m_Shl(m_One(), m_Deferred(X)))) &&
3943fe6060f1SDimitry Andric       match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
3944fe6060f1SDimitry Andric     Value *Sub = Builder.CreateSub(
3945fe6060f1SDimitry Andric         ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
3946fe6060f1SDimitry Andric     return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
3947fe6060f1SDimitry Andric   }
3948fe6060f1SDimitry Andric 
3949fe6060f1SDimitry Andric   // An or recurrence w/loop invariant step is equivelent to (or start, step)
3950fe6060f1SDimitry Andric   PHINode *PN = nullptr;
3951fe6060f1SDimitry Andric   Value *Start = nullptr, *Step = nullptr;
3952fe6060f1SDimitry Andric   if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
3953fe6060f1SDimitry Andric     return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
3954fe6060f1SDimitry Andric 
395581ad6265SDimitry Andric   // (A & B) | (C | D) or (C | D) | (A & B)
395681ad6265SDimitry Andric   // Can be combined if C or D is of type (A/B & X)
395781ad6265SDimitry Andric   if (match(&I, m_c_Or(m_OneUse(m_And(m_Value(A), m_Value(B))),
395881ad6265SDimitry Andric                        m_OneUse(m_Or(m_Value(C), m_Value(D)))))) {
395981ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
396081ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
396181ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
396281ad6265SDimitry Andric     // (A & B) | (C | ?) -> C | (? | (A & B))
396381ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
396481ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
396581ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
396681ad6265SDimitry Andric     // (C | ?) | (A & B) -> C | (? | (A & B))
396781ad6265SDimitry Andric     if (match(D, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
396881ad6265SDimitry Andric         match(D, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
396981ad6265SDimitry Andric       return BinaryOperator::CreateOr(
397081ad6265SDimitry Andric           C, Builder.CreateOr(D, Builder.CreateAnd(A, B)));
397181ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
397281ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
397381ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
397481ad6265SDimitry Andric     // (A & B) | (? | D) -> (? | (A & B)) | D
397581ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
397681ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
397781ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
397881ad6265SDimitry Andric     // (? | D) | (A & B) -> (? | (A & B)) | D
397981ad6265SDimitry Andric     if (match(C, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
398081ad6265SDimitry Andric         match(C, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
398181ad6265SDimitry Andric       return BinaryOperator::CreateOr(
398281ad6265SDimitry Andric           Builder.CreateOr(C, Builder.CreateAnd(A, B)), D);
398381ad6265SDimitry Andric   }
398481ad6265SDimitry Andric 
3985bdd1243dSDimitry Andric   if (Instruction *R = reassociateForUses(I, Builder))
3986bdd1243dSDimitry Andric     return R;
3987bdd1243dSDimitry Andric 
3988bdd1243dSDimitry Andric   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
3989bdd1243dSDimitry Andric     return Canonicalized;
3990bdd1243dSDimitry Andric 
3991bdd1243dSDimitry Andric   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
3992bdd1243dSDimitry Andric     return Folded;
3993bdd1243dSDimitry Andric 
399406c3fb27SDimitry Andric   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
399506c3fb27SDimitry Andric     return Res;
399606c3fb27SDimitry Andric 
39975f757f3fSDimitry Andric   // If we are setting the sign bit of a floating-point value, convert
39985f757f3fSDimitry Andric   // this to fneg(fabs), then cast back to integer.
39995f757f3fSDimitry Andric   //
40005f757f3fSDimitry Andric   // If the result isn't immediately cast back to a float, this will increase
40015f757f3fSDimitry Andric   // the number of instructions. This is still probably a better canonical form
40025f757f3fSDimitry Andric   // as it enables FP value tracking.
40035f757f3fSDimitry Andric   //
40045f757f3fSDimitry Andric   // Assumes any IEEE-represented type has the sign bit in the high bit.
40055f757f3fSDimitry Andric   //
40065f757f3fSDimitry Andric   // This is generous interpretation of noimplicitfloat, this is not a true
40075f757f3fSDimitry Andric   // floating-point operation.
40085f757f3fSDimitry Andric   Value *CastOp;
40090fca6ea1SDimitry Andric   if (match(Op0, m_ElementWiseBitCast(m_Value(CastOp))) &&
40100fca6ea1SDimitry Andric       match(Op1, m_SignMask()) &&
40115f757f3fSDimitry Andric       !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
40125f757f3fSDimitry Andric           Attribute::NoImplicitFloat)) {
40135f757f3fSDimitry Andric     Type *EltTy = CastOp->getType()->getScalarType();
40140fca6ea1SDimitry Andric     if (EltTy->isFloatingPointTy() && EltTy->isIEEE()) {
40155f757f3fSDimitry Andric       Value *FAbs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, CastOp);
40165f757f3fSDimitry Andric       Value *FNegFAbs = Builder.CreateFNeg(FAbs);
40175f757f3fSDimitry Andric       return new BitCastInst(FNegFAbs, I.getType());
40185f757f3fSDimitry Andric     }
40195f757f3fSDimitry Andric   }
40205f757f3fSDimitry Andric 
4021647cbc5dSDimitry Andric   // (X & C1) | C2 -> X & (C1 | C2) iff (X & C2) == C2
4022647cbc5dSDimitry Andric   if (match(Op0, m_OneUse(m_And(m_Value(X), m_APInt(C1)))) &&
4023647cbc5dSDimitry Andric       match(Op1, m_APInt(C2))) {
4024647cbc5dSDimitry Andric     KnownBits KnownX = computeKnownBits(X, /*Depth*/ 0, &I);
4025647cbc5dSDimitry Andric     if ((KnownX.One & *C2) == *C2)
4026647cbc5dSDimitry Andric       return BinaryOperator::CreateAnd(X, ConstantInt::get(Ty, *C1 | *C2));
4027647cbc5dSDimitry Andric   }
4028647cbc5dSDimitry Andric 
4029297eecfbSDimitry Andric   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
4030297eecfbSDimitry Andric     return Res;
4031297eecfbSDimitry Andric 
40320fca6ea1SDimitry Andric   if (Value *V =
40330fca6ea1SDimitry Andric           simplifyAndOrWithOpReplaced(Op0, Op1, Constant::getNullValue(Ty),
40340fca6ea1SDimitry Andric                                       /*SimplifyOnly*/ false, *this))
40350fca6ea1SDimitry Andric     return BinaryOperator::CreateOr(V, Op1);
40360fca6ea1SDimitry Andric   if (Value *V =
40370fca6ea1SDimitry Andric           simplifyAndOrWithOpReplaced(Op1, Op0, Constant::getNullValue(Ty),
40380fca6ea1SDimitry Andric                                       /*SimplifyOnly*/ false, *this))
40390fca6ea1SDimitry Andric     return BinaryOperator::CreateOr(Op0, V);
40400fca6ea1SDimitry Andric 
40410fca6ea1SDimitry Andric   if (cast<PossiblyDisjointInst>(I).isDisjoint())
40420fca6ea1SDimitry Andric     if (Value *V = SimplifyAddWithRemainder(I))
40430fca6ea1SDimitry Andric       return replaceInstUsesWith(I, V);
40440fca6ea1SDimitry Andric 
40450b57cec5SDimitry Andric   return nullptr;
40460b57cec5SDimitry Andric }
40470b57cec5SDimitry Andric 
40480b57cec5SDimitry Andric /// A ^ B can be specified using other logic ops in a variety of patterns. We
40490b57cec5SDimitry Andric /// can fold these early and efficiently by morphing an existing instruction.
40500b57cec5SDimitry Andric static Instruction *foldXorToXor(BinaryOperator &I,
40510b57cec5SDimitry Andric                                  InstCombiner::BuilderTy &Builder) {
40520b57cec5SDimitry Andric   assert(I.getOpcode() == Instruction::Xor);
40530b57cec5SDimitry Andric   Value *Op0 = I.getOperand(0);
40540b57cec5SDimitry Andric   Value *Op1 = I.getOperand(1);
40550b57cec5SDimitry Andric   Value *A, *B;
40560b57cec5SDimitry Andric 
40570b57cec5SDimitry Andric   // There are 4 commuted variants for each of the basic patterns.
40580b57cec5SDimitry Andric 
40590b57cec5SDimitry Andric   // (A & B) ^ (A | B) -> A ^ B
40600b57cec5SDimitry Andric   // (A & B) ^ (B | A) -> A ^ B
40610b57cec5SDimitry Andric   // (A | B) ^ (A & B) -> A ^ B
40620b57cec5SDimitry Andric   // (A | B) ^ (B & A) -> A ^ B
40630b57cec5SDimitry Andric   if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
40645ffd83dbSDimitry Andric                         m_c_Or(m_Deferred(A), m_Deferred(B)))))
40655ffd83dbSDimitry Andric     return BinaryOperator::CreateXor(A, B);
40660b57cec5SDimitry Andric 
40670b57cec5SDimitry Andric   // (A | ~B) ^ (~A | B) -> A ^ B
40680b57cec5SDimitry Andric   // (~B | A) ^ (~A | B) -> A ^ B
40690b57cec5SDimitry Andric   // (~A | B) ^ (A | ~B) -> A ^ B
40700b57cec5SDimitry Andric   // (B | ~A) ^ (A | ~B) -> A ^ B
40710b57cec5SDimitry Andric   if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
40725ffd83dbSDimitry Andric                       m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
40735ffd83dbSDimitry Andric     return BinaryOperator::CreateXor(A, B);
40740b57cec5SDimitry Andric 
40750b57cec5SDimitry Andric   // (A & ~B) ^ (~A & B) -> A ^ B
40760b57cec5SDimitry Andric   // (~B & A) ^ (~A & B) -> A ^ B
40770b57cec5SDimitry Andric   // (~A & B) ^ (A & ~B) -> A ^ B
40780b57cec5SDimitry Andric   // (B & ~A) ^ (A & ~B) -> A ^ B
40790b57cec5SDimitry Andric   if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
40805ffd83dbSDimitry Andric                       m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
40815ffd83dbSDimitry Andric     return BinaryOperator::CreateXor(A, B);
40820b57cec5SDimitry Andric 
40830b57cec5SDimitry Andric   // For the remaining cases we need to get rid of one of the operands.
40840b57cec5SDimitry Andric   if (!Op0->hasOneUse() && !Op1->hasOneUse())
40850b57cec5SDimitry Andric     return nullptr;
40860b57cec5SDimitry Andric 
40870b57cec5SDimitry Andric   // (A | B) ^ ~(A & B) -> ~(A ^ B)
40880b57cec5SDimitry Andric   // (A | B) ^ ~(B & A) -> ~(A ^ B)
40890b57cec5SDimitry Andric   // (A & B) ^ ~(A | B) -> ~(A ^ B)
40900b57cec5SDimitry Andric   // (A & B) ^ ~(B | A) -> ~(A ^ B)
40910b57cec5SDimitry Andric   // Complexity sorting ensures the not will be on the right side.
40920b57cec5SDimitry Andric   if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
40930b57cec5SDimitry Andric        match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
40940b57cec5SDimitry Andric       (match(Op0, m_And(m_Value(A), m_Value(B))) &&
40950b57cec5SDimitry Andric        match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
40960b57cec5SDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   return nullptr;
40990b57cec5SDimitry Andric }
41000b57cec5SDimitry Andric 
4101e8d8bef9SDimitry Andric Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
41028bcb0991SDimitry Andric                                         BinaryOperator &I) {
41038bcb0991SDimitry Andric   assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
41048bcb0991SDimitry Andric          I.getOperand(1) == RHS && "Should be 'xor' with these operands");
41058bcb0991SDimitry Andric 
410681ad6265SDimitry Andric   ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
410781ad6265SDimitry Andric   Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
410881ad6265SDimitry Andric   Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
410981ad6265SDimitry Andric 
411081ad6265SDimitry Andric   if (predicatesFoldable(PredL, PredR)) {
411181ad6265SDimitry Andric     if (LHS0 == RHS1 && LHS1 == RHS0) {
411281ad6265SDimitry Andric       std::swap(LHS0, LHS1);
411381ad6265SDimitry Andric       PredL = ICmpInst::getSwappedPredicate(PredL);
411481ad6265SDimitry Andric     }
411581ad6265SDimitry Andric     if (LHS0 == RHS0 && LHS1 == RHS1) {
41160b57cec5SDimitry Andric       // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
411781ad6265SDimitry Andric       unsigned Code = getICmpCode(PredL) ^ getICmpCode(PredR);
41180b57cec5SDimitry Andric       bool IsSigned = LHS->isSigned() || RHS->isSigned();
411981ad6265SDimitry Andric       return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
41200b57cec5SDimitry Andric     }
41210b57cec5SDimitry Andric   }
41220b57cec5SDimitry Andric 
41230b57cec5SDimitry Andric   // TODO: This can be generalized to compares of non-signbits using
41240b57cec5SDimitry Andric   // decomposeBitTestICmp(). It could be enhanced more by using (something like)
41250b57cec5SDimitry Andric   // foldLogOpOfMaskedICmps().
4126fcaf7f86SDimitry Andric   const APInt *LC, *RC;
4127fcaf7f86SDimitry Andric   if (match(LHS1, m_APInt(LC)) && match(RHS1, m_APInt(RC)) &&
41280b57cec5SDimitry Andric       LHS0->getType() == RHS0->getType() &&
4129cb14a3feSDimitry Andric       LHS0->getType()->isIntOrIntVectorTy()) {
4130fcaf7f86SDimitry Andric     // Convert xor of signbit tests to signbit test of xor'd values:
41310b57cec5SDimitry Andric     // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0
41320b57cec5SDimitry Andric     // (X <  0) ^ (Y <  0) --> (X ^ Y) < 0
41330b57cec5SDimitry Andric     // (X > -1) ^ (Y <  0) --> (X ^ Y) > -1
41340b57cec5SDimitry Andric     // (X <  0) ^ (Y > -1) --> (X ^ Y) > -1
4135fcaf7f86SDimitry Andric     bool TrueIfSignedL, TrueIfSignedR;
4136cb14a3feSDimitry Andric     if ((LHS->hasOneUse() || RHS->hasOneUse()) &&
4137cb14a3feSDimitry Andric         isSignBitCheck(PredL, *LC, TrueIfSignedL) &&
4138fcaf7f86SDimitry Andric         isSignBitCheck(PredR, *RC, TrueIfSignedR)) {
4139fcaf7f86SDimitry Andric       Value *XorLR = Builder.CreateXor(LHS0, RHS0);
4140fcaf7f86SDimitry Andric       return TrueIfSignedL == TrueIfSignedR ? Builder.CreateIsNeg(XorLR) :
4141fcaf7f86SDimitry Andric                                               Builder.CreateIsNotNeg(XorLR);
4142fcaf7f86SDimitry Andric     }
414381ad6265SDimitry Andric 
4144cb14a3feSDimitry Andric     // Fold (icmp pred1 X, C1) ^ (icmp pred2 X, C2)
4145cb14a3feSDimitry Andric     // into a single comparison using range-based reasoning.
4146cb14a3feSDimitry Andric     if (LHS0 == RHS0) {
4147cb14a3feSDimitry Andric       ConstantRange CR1 = ConstantRange::makeExactICmpRegion(PredL, *LC);
4148cb14a3feSDimitry Andric       ConstantRange CR2 = ConstantRange::makeExactICmpRegion(PredR, *RC);
4149cb14a3feSDimitry Andric       auto CRUnion = CR1.exactUnionWith(CR2);
4150cb14a3feSDimitry Andric       auto CRIntersect = CR1.exactIntersectWith(CR2);
4151cb14a3feSDimitry Andric       if (CRUnion && CRIntersect)
4152cb14a3feSDimitry Andric         if (auto CR = CRUnion->exactIntersectWith(CRIntersect->inverse())) {
4153cb14a3feSDimitry Andric           if (CR->isFullSet())
4154cb14a3feSDimitry Andric             return ConstantInt::getTrue(I.getType());
4155cb14a3feSDimitry Andric           if (CR->isEmptySet())
4156cb14a3feSDimitry Andric             return ConstantInt::getFalse(I.getType());
4157cb14a3feSDimitry Andric 
4158cb14a3feSDimitry Andric           CmpInst::Predicate NewPred;
4159cb14a3feSDimitry Andric           APInt NewC, Offset;
4160cb14a3feSDimitry Andric           CR->getEquivalentICmp(NewPred, NewC, Offset);
4161cb14a3feSDimitry Andric 
4162cb14a3feSDimitry Andric           if ((Offset.isZero() && (LHS->hasOneUse() || RHS->hasOneUse())) ||
4163cb14a3feSDimitry Andric               (LHS->hasOneUse() && RHS->hasOneUse())) {
4164cb14a3feSDimitry Andric             Value *NewV = LHS0;
4165cb14a3feSDimitry Andric             Type *Ty = LHS0->getType();
4166cb14a3feSDimitry Andric             if (!Offset.isZero())
4167cb14a3feSDimitry Andric               NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
4168cb14a3feSDimitry Andric             return Builder.CreateICmp(NewPred, NewV,
4169cb14a3feSDimitry Andric                                       ConstantInt::get(Ty, NewC));
4170cb14a3feSDimitry Andric           }
4171cb14a3feSDimitry Andric         }
4172cb14a3feSDimitry Andric     }
41730b57cec5SDimitry Andric   }
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric   // Instead of trying to imitate the folds for and/or, decompose this 'xor'
41760b57cec5SDimitry Andric   // into those logic ops. That is, try to turn this into an and-of-icmps
41770b57cec5SDimitry Andric   // because we have many folds for that pattern.
41780b57cec5SDimitry Andric   //
41790b57cec5SDimitry Andric   // This is based on a truth table definition of xor:
41800b57cec5SDimitry Andric   // X ^ Y --> (X | Y) & !(X & Y)
418181ad6265SDimitry Andric   if (Value *OrICmp = simplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
41820b57cec5SDimitry Andric     // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
41830b57cec5SDimitry Andric     // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
418481ad6265SDimitry Andric     if (Value *AndICmp = simplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
41850b57cec5SDimitry Andric       // TODO: Independently handle cases where the 'and' side is a constant.
41868bcb0991SDimitry Andric       ICmpInst *X = nullptr, *Y = nullptr;
41878bcb0991SDimitry Andric       if (OrICmp == LHS && AndICmp == RHS) {
41888bcb0991SDimitry Andric         // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS  --> X & !Y
41898bcb0991SDimitry Andric         X = LHS;
41908bcb0991SDimitry Andric         Y = RHS;
41910b57cec5SDimitry Andric       }
41928bcb0991SDimitry Andric       if (OrICmp == RHS && AndICmp == LHS) {
41938bcb0991SDimitry Andric         // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS  --> !Y & X
41948bcb0991SDimitry Andric         X = RHS;
41958bcb0991SDimitry Andric         Y = LHS;
41968bcb0991SDimitry Andric       }
41978bcb0991SDimitry Andric       if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
41988bcb0991SDimitry Andric         // Invert the predicate of 'Y', thus inverting its output.
41998bcb0991SDimitry Andric         Y->setPredicate(Y->getInversePredicate());
42008bcb0991SDimitry Andric         // So, are there other uses of Y?
42018bcb0991SDimitry Andric         if (!Y->hasOneUse()) {
42028bcb0991SDimitry Andric           // We need to adapt other uses of Y though. Get a value that matches
42038bcb0991SDimitry Andric           // the original value of Y before inversion. While this increases
42048bcb0991SDimitry Andric           // immediate instruction count, we have just ensured that all the
42058bcb0991SDimitry Andric           // users are freely-invertible, so that 'not' *will* get folded away.
42068bcb0991SDimitry Andric           BuilderTy::InsertPointGuard Guard(Builder);
42078bcb0991SDimitry Andric           // Set insertion point to right after the Y.
42088bcb0991SDimitry Andric           Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
42098bcb0991SDimitry Andric           Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
42108bcb0991SDimitry Andric           // Replace all uses of Y (excluding the one in NotY!) with NotY.
42115ffd83dbSDimitry Andric           Worklist.pushUsersToWorkList(*Y);
42128bcb0991SDimitry Andric           Y->replaceUsesWithIf(NotY,
42138bcb0991SDimitry Andric                                [NotY](Use &U) { return U.getUser() != NotY; });
42148bcb0991SDimitry Andric         }
42158bcb0991SDimitry Andric         // All done.
42160b57cec5SDimitry Andric         return Builder.CreateAnd(LHS, RHS);
42170b57cec5SDimitry Andric       }
42180b57cec5SDimitry Andric     }
42190b57cec5SDimitry Andric   }
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   return nullptr;
42220b57cec5SDimitry Andric }
42230b57cec5SDimitry Andric 
42240b57cec5SDimitry Andric /// If we have a masked merge, in the canonical form of:
42250b57cec5SDimitry Andric /// (assuming that A only has one use.)
42260b57cec5SDimitry Andric ///   |        A  |  |B|
42270b57cec5SDimitry Andric ///   ((x ^ y) & M) ^ y
42280b57cec5SDimitry Andric ///    |  D  |
42290b57cec5SDimitry Andric /// * If M is inverted:
42300b57cec5SDimitry Andric ///      |  D  |
42310b57cec5SDimitry Andric ///     ((x ^ y) & ~M) ^ y
42320b57cec5SDimitry Andric ///   We can canonicalize by swapping the final xor operand
42330b57cec5SDimitry Andric ///   to eliminate the 'not' of the mask.
42340b57cec5SDimitry Andric ///     ((x ^ y) & M) ^ x
42350b57cec5SDimitry Andric /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops
42360b57cec5SDimitry Andric ///   because that shortens the dependency chain and improves analysis:
42370b57cec5SDimitry Andric ///     (x & M) | (y & ~M)
42380b57cec5SDimitry Andric static Instruction *visitMaskedMerge(BinaryOperator &I,
42390b57cec5SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
42400b57cec5SDimitry Andric   Value *B, *X, *D;
42410b57cec5SDimitry Andric   Value *M;
42420b57cec5SDimitry Andric   if (!match(&I, m_c_Xor(m_Value(B),
42430b57cec5SDimitry Andric                          m_OneUse(m_c_And(
42440b57cec5SDimitry Andric                              m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
42450b57cec5SDimitry Andric                                           m_Value(D)),
42460b57cec5SDimitry Andric                              m_Value(M))))))
42470b57cec5SDimitry Andric     return nullptr;
42480b57cec5SDimitry Andric 
42490b57cec5SDimitry Andric   Value *NotM;
42500b57cec5SDimitry Andric   if (match(M, m_Not(m_Value(NotM)))) {
42510b57cec5SDimitry Andric     // De-invert the mask and swap the value in B part.
42520b57cec5SDimitry Andric     Value *NewA = Builder.CreateAnd(D, NotM);
42530b57cec5SDimitry Andric     return BinaryOperator::CreateXor(NewA, X);
42540b57cec5SDimitry Andric   }
42550b57cec5SDimitry Andric 
42560b57cec5SDimitry Andric   Constant *C;
42570b57cec5SDimitry Andric   if (D->hasOneUse() && match(M, m_Constant(C))) {
42585ffd83dbSDimitry Andric     // Propagating undef is unsafe. Clamp undef elements to -1.
42595ffd83dbSDimitry Andric     Type *EltTy = C->getType()->getScalarType();
42605ffd83dbSDimitry Andric     C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
42610b57cec5SDimitry Andric     // Unfold.
42620b57cec5SDimitry Andric     Value *LHS = Builder.CreateAnd(X, C);
42630b57cec5SDimitry Andric     Value *NotC = Builder.CreateNot(C);
42640b57cec5SDimitry Andric     Value *RHS = Builder.CreateAnd(B, NotC);
42650b57cec5SDimitry Andric     return BinaryOperator::CreateOr(LHS, RHS);
42660b57cec5SDimitry Andric   }
42670b57cec5SDimitry Andric 
42680b57cec5SDimitry Andric   return nullptr;
42690b57cec5SDimitry Andric }
42700b57cec5SDimitry Andric 
4271bdd1243dSDimitry Andric static Instruction *foldNotXor(BinaryOperator &I,
4272bdd1243dSDimitry Andric                                InstCombiner::BuilderTy &Builder) {
4273bdd1243dSDimitry Andric   Value *X, *Y;
4274bdd1243dSDimitry Andric   // FIXME: one-use check is not needed in general, but currently we are unable
4275bdd1243dSDimitry Andric   // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182)
4276bdd1243dSDimitry Andric   if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
4277bdd1243dSDimitry Andric     return nullptr;
4278bdd1243dSDimitry Andric 
4279bdd1243dSDimitry Andric   auto hasCommonOperand = [](Value *A, Value *B, Value *C, Value *D) {
4280bdd1243dSDimitry Andric     return A == C || A == D || B == C || B == D;
4281bdd1243dSDimitry Andric   };
4282bdd1243dSDimitry Andric 
4283bdd1243dSDimitry Andric   Value *A, *B, *C, *D;
4284bdd1243dSDimitry Andric   // Canonicalize ~((A & B) ^ (A | ?)) -> (A & B) | ~(A | ?)
4285bdd1243dSDimitry Andric   // 4 commuted variants
4286bdd1243dSDimitry Andric   if (match(X, m_And(m_Value(A), m_Value(B))) &&
4287bdd1243dSDimitry Andric       match(Y, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
4288bdd1243dSDimitry Andric     Value *NotY = Builder.CreateNot(Y);
4289bdd1243dSDimitry Andric     return BinaryOperator::CreateOr(X, NotY);
4290bdd1243dSDimitry Andric   };
4291bdd1243dSDimitry Andric 
4292bdd1243dSDimitry Andric   // Canonicalize ~((A | ?) ^ (A & B)) -> (A & B) | ~(A | ?)
4293bdd1243dSDimitry Andric   // 4 commuted variants
4294bdd1243dSDimitry Andric   if (match(Y, m_And(m_Value(A), m_Value(B))) &&
4295bdd1243dSDimitry Andric       match(X, m_Or(m_Value(C), m_Value(D))) && hasCommonOperand(A, B, C, D)) {
4296bdd1243dSDimitry Andric     Value *NotX = Builder.CreateNot(X);
4297bdd1243dSDimitry Andric     return BinaryOperator::CreateOr(Y, NotX);
4298bdd1243dSDimitry Andric   };
4299bdd1243dSDimitry Andric 
4300bdd1243dSDimitry Andric   return nullptr;
4301bdd1243dSDimitry Andric }
4302bdd1243dSDimitry Andric 
4303fe6060f1SDimitry Andric /// Canonicalize a shifty way to code absolute value to the more common pattern
4304fe6060f1SDimitry Andric /// that uses negation and select.
4305fe6060f1SDimitry Andric static Instruction *canonicalizeAbs(BinaryOperator &Xor,
4306fe6060f1SDimitry Andric                                     InstCombiner::BuilderTy &Builder) {
4307fe6060f1SDimitry Andric   assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
4308fe6060f1SDimitry Andric 
4309fe6060f1SDimitry Andric   // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1.
4310fe6060f1SDimitry Andric   // We're relying on the fact that we only do this transform when the shift has
4311fe6060f1SDimitry Andric   // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase
4312fe6060f1SDimitry Andric   // instructions).
4313fe6060f1SDimitry Andric   Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
4314fe6060f1SDimitry Andric   if (Op0->hasNUses(2))
4315fe6060f1SDimitry Andric     std::swap(Op0, Op1);
4316fe6060f1SDimitry Andric 
4317fe6060f1SDimitry Andric   Type *Ty = Xor.getType();
4318fe6060f1SDimitry Andric   Value *A;
4319fe6060f1SDimitry Andric   const APInt *ShAmt;
4320fe6060f1SDimitry Andric   if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
4321fe6060f1SDimitry Andric       Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
4322fe6060f1SDimitry Andric       match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
4323fe6060f1SDimitry Andric     // Op1 = ashr i32 A, 31   ; smear the sign bit
4324fe6060f1SDimitry Andric     // xor (add A, Op1), Op1  ; add -1 and flip bits if negative
4325fe6060f1SDimitry Andric     // --> (A < 0) ? -A : A
432681ad6265SDimitry Andric     Value *IsNeg = Builder.CreateIsNeg(A);
43270fca6ea1SDimitry Andric     // Copy the nsw flags from the add to the negate.
4328fe6060f1SDimitry Andric     auto *Add = cast<BinaryOperator>(Op0);
43290fca6ea1SDimitry Andric     Value *NegA = Add->hasNoUnsignedWrap()
43300fca6ea1SDimitry Andric                       ? Constant::getNullValue(A->getType())
43310fca6ea1SDimitry Andric                       : Builder.CreateNeg(A, "", Add->hasNoSignedWrap());
433281ad6265SDimitry Andric     return SelectInst::Create(IsNeg, NegA, A);
4333fe6060f1SDimitry Andric   }
4334fe6060f1SDimitry Andric   return nullptr;
4335fe6060f1SDimitry Andric }
4336fe6060f1SDimitry Andric 
433706c3fb27SDimitry Andric static bool canFreelyInvert(InstCombiner &IC, Value *Op,
433806c3fb27SDimitry Andric                             Instruction *IgnoredUser) {
433906c3fb27SDimitry Andric   auto *I = dyn_cast<Instruction>(Op);
434006c3fb27SDimitry Andric   return I && IC.isFreeToInvert(I, /*WillInvertAllUses=*/true) &&
43415f757f3fSDimitry Andric          IC.canFreelyInvertAllUsersOf(I, IgnoredUser);
434206c3fb27SDimitry Andric }
434306c3fb27SDimitry Andric 
434406c3fb27SDimitry Andric static Value *freelyInvert(InstCombinerImpl &IC, Value *Op,
434506c3fb27SDimitry Andric                            Instruction *IgnoredUser) {
434606c3fb27SDimitry Andric   auto *I = cast<Instruction>(Op);
43475f757f3fSDimitry Andric   IC.Builder.SetInsertPoint(*I->getInsertionPointAfterDef());
434806c3fb27SDimitry Andric   Value *NotOp = IC.Builder.CreateNot(Op, Op->getName() + ".not");
434906c3fb27SDimitry Andric   Op->replaceUsesWithIf(NotOp,
435006c3fb27SDimitry Andric                         [NotOp](Use &U) { return U.getUser() != NotOp; });
435106c3fb27SDimitry Andric   IC.freelyInvertAllUsersOf(NotOp, IgnoredUser);
435206c3fb27SDimitry Andric   return NotOp;
435306c3fb27SDimitry Andric }
435406c3fb27SDimitry Andric 
4355e8d8bef9SDimitry Andric // Transform
4356bdd1243dSDimitry Andric //   z = ~(x &/| y)
4357bdd1243dSDimitry Andric // into:
4358bdd1243dSDimitry Andric //   z = ((~x) |/& (~y))
4359bdd1243dSDimitry Andric // iff both x and y are free to invert and all uses of z can be freely updated.
4360bdd1243dSDimitry Andric bool InstCombinerImpl::sinkNotIntoLogicalOp(Instruction &I) {
4361bdd1243dSDimitry Andric   Value *Op0, *Op1;
4362bdd1243dSDimitry Andric   if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
4363bdd1243dSDimitry Andric     return false;
4364bdd1243dSDimitry Andric 
4365bdd1243dSDimitry Andric   // If this logic op has not been simplified yet, just bail out and let that
4366bdd1243dSDimitry Andric   // happen first. Otherwise, the code below may wrongly invert.
4367bdd1243dSDimitry Andric   if (Op0 == Op1)
4368bdd1243dSDimitry Andric     return false;
4369bdd1243dSDimitry Andric 
4370bdd1243dSDimitry Andric   Instruction::BinaryOps NewOpc =
4371bdd1243dSDimitry Andric       match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
4372bdd1243dSDimitry Andric   bool IsBinaryOp = isa<BinaryOperator>(I);
4373bdd1243dSDimitry Andric 
4374bdd1243dSDimitry Andric   // Can our users be adapted?
4375bdd1243dSDimitry Andric   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
4376bdd1243dSDimitry Andric     return false;
4377bdd1243dSDimitry Andric 
4378bdd1243dSDimitry Andric   // And can the operands be adapted?
437906c3fb27SDimitry Andric   if (!canFreelyInvert(*this, Op0, &I) || !canFreelyInvert(*this, Op1, &I))
4380bdd1243dSDimitry Andric     return false;
4381bdd1243dSDimitry Andric 
438206c3fb27SDimitry Andric   Op0 = freelyInvert(*this, Op0, &I);
438306c3fb27SDimitry Andric   Op1 = freelyInvert(*this, Op1, &I);
4384bdd1243dSDimitry Andric 
43855f757f3fSDimitry Andric   Builder.SetInsertPoint(*I.getInsertionPointAfterDef());
4386bdd1243dSDimitry Andric   Value *NewLogicOp;
4387bdd1243dSDimitry Andric   if (IsBinaryOp)
4388bdd1243dSDimitry Andric     NewLogicOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
4389bdd1243dSDimitry Andric   else
4390bdd1243dSDimitry Andric     NewLogicOp =
4391bdd1243dSDimitry Andric         Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
4392bdd1243dSDimitry Andric 
4393bdd1243dSDimitry Andric   replaceInstUsesWith(I, NewLogicOp);
4394bdd1243dSDimitry Andric   // We can not just create an outer `not`, it will most likely be immediately
4395bdd1243dSDimitry Andric   // folded back, reconstructing our initial pattern, and causing an
4396bdd1243dSDimitry Andric   // infinite combine loop, so immediately manually fold it away.
4397bdd1243dSDimitry Andric   freelyInvertAllUsersOf(NewLogicOp);
4398bdd1243dSDimitry Andric   return true;
4399bdd1243dSDimitry Andric }
4400bdd1243dSDimitry Andric 
4401bdd1243dSDimitry Andric // Transform
4402e8d8bef9SDimitry Andric //   z = (~x) &/| y
4403e8d8bef9SDimitry Andric // into:
4404e8d8bef9SDimitry Andric //   z = ~(x |/& (~y))
4405e8d8bef9SDimitry Andric // iff y is free to invert and all uses of z can be freely updated.
4406bdd1243dSDimitry Andric bool InstCombinerImpl::sinkNotIntoOtherHandOfLogicalOp(Instruction &I) {
4407bdd1243dSDimitry Andric   Value *Op0, *Op1;
4408bdd1243dSDimitry Andric   if (!match(&I, m_LogicalOp(m_Value(Op0), m_Value(Op1))))
4409e8d8bef9SDimitry Andric     return false;
4410bdd1243dSDimitry Andric   Instruction::BinaryOps NewOpc =
4411bdd1243dSDimitry Andric       match(&I, m_LogicalAnd()) ? Instruction::Or : Instruction::And;
4412bdd1243dSDimitry Andric   bool IsBinaryOp = isa<BinaryOperator>(I);
4413e8d8bef9SDimitry Andric 
4414bdd1243dSDimitry Andric   Value *NotOp0 = nullptr;
4415bdd1243dSDimitry Andric   Value *NotOp1 = nullptr;
4416bdd1243dSDimitry Andric   Value **OpToInvert = nullptr;
441706c3fb27SDimitry Andric   if (match(Op0, m_Not(m_Value(NotOp0))) && canFreelyInvert(*this, Op1, &I)) {
4418bdd1243dSDimitry Andric     Op0 = NotOp0;
4419bdd1243dSDimitry Andric     OpToInvert = &Op1;
4420bdd1243dSDimitry Andric   } else if (match(Op1, m_Not(m_Value(NotOp1))) &&
442106c3fb27SDimitry Andric              canFreelyInvert(*this, Op0, &I)) {
4422bdd1243dSDimitry Andric     Op1 = NotOp1;
4423bdd1243dSDimitry Andric     OpToInvert = &Op0;
4424bdd1243dSDimitry Andric   } else
4425e8d8bef9SDimitry Andric     return false;
4426e8d8bef9SDimitry Andric 
4427e8d8bef9SDimitry Andric   // And can our users be adapted?
4428e8d8bef9SDimitry Andric   if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
4429e8d8bef9SDimitry Andric     return false;
4430e8d8bef9SDimitry Andric 
443106c3fb27SDimitry Andric   *OpToInvert = freelyInvert(*this, *OpToInvert, &I);
4432bdd1243dSDimitry Andric 
44335f757f3fSDimitry Andric   Builder.SetInsertPoint(*I.getInsertionPointAfterDef());
4434bdd1243dSDimitry Andric   Value *NewBinOp;
4435bdd1243dSDimitry Andric   if (IsBinaryOp)
4436bdd1243dSDimitry Andric     NewBinOp = Builder.CreateBinOp(NewOpc, Op0, Op1, I.getName() + ".not");
4437bdd1243dSDimitry Andric   else
4438bdd1243dSDimitry Andric     NewBinOp = Builder.CreateLogicalOp(NewOpc, Op0, Op1, I.getName() + ".not");
4439e8d8bef9SDimitry Andric   replaceInstUsesWith(I, NewBinOp);
4440e8d8bef9SDimitry Andric   // We can not just create an outer `not`, it will most likely be immediately
4441e8d8bef9SDimitry Andric   // folded back, reconstructing our initial pattern, and causing an
4442e8d8bef9SDimitry Andric   // infinite combine loop, so immediately manually fold it away.
4443e8d8bef9SDimitry Andric   freelyInvertAllUsersOf(NewBinOp);
4444e8d8bef9SDimitry Andric   return true;
4445e8d8bef9SDimitry Andric }
4446e8d8bef9SDimitry Andric 
4447349cc55cSDimitry Andric Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
4448349cc55cSDimitry Andric   Value *NotOp;
4449349cc55cSDimitry Andric   if (!match(&I, m_Not(m_Value(NotOp))))
4450349cc55cSDimitry Andric     return nullptr;
44510b57cec5SDimitry Andric 
44520b57cec5SDimitry Andric   // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
44530b57cec5SDimitry Andric   // We must eliminate the and/or (one-use) for these transforms to not increase
44540b57cec5SDimitry Andric   // the instruction count.
4455349cc55cSDimitry Andric   //
44560b57cec5SDimitry Andric   // ~(~X & Y) --> (X | ~Y)
44570b57cec5SDimitry Andric   // ~(Y & ~X) --> (X | ~Y)
4458349cc55cSDimitry Andric   //
4459349cc55cSDimitry Andric   // Note: The logical matches do not check for the commuted patterns because
4460349cc55cSDimitry Andric   //       those are handled via SimplifySelectsFeedingBinaryOp().
4461349cc55cSDimitry Andric   Type *Ty = I.getType();
4462349cc55cSDimitry Andric   Value *X, *Y;
4463349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
44640b57cec5SDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
44650b57cec5SDimitry Andric     return BinaryOperator::CreateOr(X, NotY);
44660b57cec5SDimitry Andric   }
4467349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
4468349cc55cSDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4469349cc55cSDimitry Andric     return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
4470349cc55cSDimitry Andric   }
4471349cc55cSDimitry Andric 
44720b57cec5SDimitry Andric   // ~(~X | Y) --> (X & ~Y)
44730b57cec5SDimitry Andric   // ~(Y | ~X) --> (X & ~Y)
4474349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
44750b57cec5SDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
44760b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(X, NotY);
44770b57cec5SDimitry Andric   }
4478349cc55cSDimitry Andric   if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
4479349cc55cSDimitry Andric     Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
4480349cc55cSDimitry Andric     return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
4481349cc55cSDimitry Andric   }
44820b57cec5SDimitry Andric 
44830b57cec5SDimitry Andric   // Is this a 'not' (~) fed by a binary operator?
44840b57cec5SDimitry Andric   BinaryOperator *NotVal;
4485349cc55cSDimitry Andric   if (match(NotOp, m_BinOp(NotVal))) {
4486fe6060f1SDimitry Andric     // ~((-X) | Y) --> (X - 1) & (~Y)
4487fe6060f1SDimitry Andric     if (match(NotVal,
4488fe6060f1SDimitry Andric               m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
4489fe6060f1SDimitry Andric       Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
4490fe6060f1SDimitry Andric       Value *NotY = Builder.CreateNot(Y);
4491fe6060f1SDimitry Andric       return BinaryOperator::CreateAnd(DecX, NotY);
4492fe6060f1SDimitry Andric     }
4493fe6060f1SDimitry Andric 
44940b57cec5SDimitry Andric     // ~(~X >>s Y) --> (X >>s Y)
44950b57cec5SDimitry Andric     if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
44960b57cec5SDimitry Andric       return BinaryOperator::CreateAShr(X, Y);
44970b57cec5SDimitry Andric 
44985f757f3fSDimitry Andric     // Treat lshr with non-negative operand as ashr.
44995f757f3fSDimitry Andric     // ~(~X >>u Y) --> (X >>s Y) iff X is known negative
45005f757f3fSDimitry Andric     if (match(NotVal, m_LShr(m_Not(m_Value(X)), m_Value(Y))) &&
45015f757f3fSDimitry Andric         isKnownNegative(X, SQ.getWithInstruction(NotVal)))
45025f757f3fSDimitry Andric       return BinaryOperator::CreateAShr(X, Y);
45035f757f3fSDimitry Andric 
450406c3fb27SDimitry Andric     // Bit-hack form of a signbit test for iN type:
450506c3fb27SDimitry Andric     // ~(X >>s (N - 1)) --> sext i1 (X > -1) to iN
4506bdd1243dSDimitry Andric     unsigned FullShift = Ty->getScalarSizeInBits() - 1;
4507bdd1243dSDimitry Andric     if (match(NotVal, m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))))) {
4508bdd1243dSDimitry Andric       Value *IsNotNeg = Builder.CreateIsNotNeg(X, "isnotneg");
4509bdd1243dSDimitry Andric       return new SExtInst(IsNotNeg, Ty);
4510bdd1243dSDimitry Andric     }
4511bdd1243dSDimitry Andric 
45120b57cec5SDimitry Andric     // If we are inverting a right-shifted constant, we may be able to eliminate
45130b57cec5SDimitry Andric     // the 'not' by inverting the constant and using the opposite shift type.
45140b57cec5SDimitry Andric     // Canonicalization rules ensure that only a negative constant uses 'ashr',
45150b57cec5SDimitry Andric     // but we must check that in case that transform has not fired yet.
45160b57cec5SDimitry Andric 
45170b57cec5SDimitry Andric     // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
45180b57cec5SDimitry Andric     Constant *C;
45190b57cec5SDimitry Andric     if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
45200fca6ea1SDimitry Andric         match(C, m_Negative()))
45210b57cec5SDimitry Andric       return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
45220b57cec5SDimitry Andric 
45230b57cec5SDimitry Andric     // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
45240b57cec5SDimitry Andric     if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
45250fca6ea1SDimitry Andric         match(C, m_NonNegative()))
45260b57cec5SDimitry Andric       return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
45270b57cec5SDimitry Andric 
452823408297SDimitry Andric     // ~(X + C) --> ~C - X
45290fca6ea1SDimitry Andric     if (match(NotVal, m_Add(m_Value(X), m_ImmConstant(C))))
453023408297SDimitry Andric       return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
453123408297SDimitry Andric 
453223408297SDimitry Andric     // ~(X - Y) --> ~X + Y
453323408297SDimitry Andric     // FIXME: is it really beneficial to sink the `not` here?
453423408297SDimitry Andric     if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
453523408297SDimitry Andric       if (isa<Constant>(X) || NotVal->hasOneUse())
453623408297SDimitry Andric         return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
4537e8d8bef9SDimitry Andric 
4538e8d8bef9SDimitry Andric     // ~(~X + Y) --> X - Y
4539e8d8bef9SDimitry Andric     if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
4540e8d8bef9SDimitry Andric       return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
4541e8d8bef9SDimitry Andric                                                    NotVal);
45420b57cec5SDimitry Andric   }
45430b57cec5SDimitry Andric 
4544349cc55cSDimitry Andric   // not (cmp A, B) = !cmp A, B
4545349cc55cSDimitry Andric   CmpInst::Predicate Pred;
4546bdd1243dSDimitry Andric   if (match(NotOp, m_Cmp(Pred, m_Value(), m_Value())) &&
4547bdd1243dSDimitry Andric       (NotOp->hasOneUse() ||
4548bdd1243dSDimitry Andric        InstCombiner::canFreelyInvertAllUsersOf(cast<Instruction>(NotOp),
4549bdd1243dSDimitry Andric                                                /*IgnoredUser=*/nullptr))) {
4550349cc55cSDimitry Andric     cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
4551bdd1243dSDimitry Andric     freelyInvertAllUsersOf(NotOp);
4552bdd1243dSDimitry Andric     return &I;
4553349cc55cSDimitry Andric   }
4554349cc55cSDimitry Andric 
4555bdd1243dSDimitry Andric   // Move a 'not' ahead of casts of a bool to enable logic reduction:
4556bdd1243dSDimitry Andric   // not (bitcast (sext i1 X)) --> bitcast (sext (not i1 X))
4557bdd1243dSDimitry Andric   if (match(NotOp, m_OneUse(m_BitCast(m_OneUse(m_SExt(m_Value(X)))))) && X->getType()->isIntOrIntVectorTy(1)) {
4558bdd1243dSDimitry Andric     Type *SextTy = cast<BitCastOperator>(NotOp)->getSrcTy();
4559bdd1243dSDimitry Andric     Value *NotX = Builder.CreateNot(X);
4560bdd1243dSDimitry Andric     Value *Sext = Builder.CreateSExt(NotX, SextTy);
4561bdd1243dSDimitry Andric     return CastInst::CreateBitOrPointerCast(Sext, Ty);
4562bdd1243dSDimitry Andric   }
4563bdd1243dSDimitry Andric 
4564bdd1243dSDimitry Andric   if (auto *NotOpI = dyn_cast<Instruction>(NotOp))
4565bdd1243dSDimitry Andric     if (sinkNotIntoLogicalOp(*NotOpI))
4566bdd1243dSDimitry Andric       return &I;
4567bdd1243dSDimitry Andric 
4568349cc55cSDimitry Andric   // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max:
4569349cc55cSDimitry Andric   // ~min(~X, ~Y) --> max(X, Y)
4570349cc55cSDimitry Andric   // ~max(~X, Y) --> min(X, ~Y)
4571349cc55cSDimitry Andric   auto *II = dyn_cast<IntrinsicInst>(NotOp);
4572349cc55cSDimitry Andric   if (II && II->hasOneUse()) {
4573349cc55cSDimitry Andric     if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
4574349cc55cSDimitry Andric       Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
4575349cc55cSDimitry Andric       Value *NotY = Builder.CreateNot(Y);
4576349cc55cSDimitry Andric       Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
4577349cc55cSDimitry Andric       return replaceInstUsesWith(I, InvMaxMin);
4578349cc55cSDimitry Andric     }
4579bdd1243dSDimitry Andric 
4580bdd1243dSDimitry Andric     if (II->getIntrinsicID() == Intrinsic::is_fpclass) {
4581bdd1243dSDimitry Andric       ConstantInt *ClassMask = cast<ConstantInt>(II->getArgOperand(1));
4582bdd1243dSDimitry Andric       II->setArgOperand(
4583bdd1243dSDimitry Andric           1, ConstantInt::get(ClassMask->getType(),
4584bdd1243dSDimitry Andric                               ~ClassMask->getZExtValue() & fcAllFlags));
4585bdd1243dSDimitry Andric       return replaceInstUsesWith(I, II);
4586bdd1243dSDimitry Andric     }
4587349cc55cSDimitry Andric   }
4588349cc55cSDimitry Andric 
4589349cc55cSDimitry Andric   if (NotOp->hasOneUse()) {
4590349cc55cSDimitry Andric     // Pull 'not' into operands of select if both operands are one-use compares
4591349cc55cSDimitry Andric     // or one is one-use compare and the other one is a constant.
4592349cc55cSDimitry Andric     // Inverting the predicates eliminates the 'not' operation.
4593349cc55cSDimitry Andric     // Example:
4594349cc55cSDimitry Andric     //   not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) -->
4595349cc55cSDimitry Andric     //     select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?)
4596349cc55cSDimitry Andric     //   not (select ?, (cmp TPred, ?, ?), true -->
4597349cc55cSDimitry Andric     //     select ?, (cmp InvTPred, ?, ?), false
4598349cc55cSDimitry Andric     if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
4599349cc55cSDimitry Andric       Value *TV = Sel->getTrueValue();
4600349cc55cSDimitry Andric       Value *FV = Sel->getFalseValue();
4601349cc55cSDimitry Andric       auto *CmpT = dyn_cast<CmpInst>(TV);
4602349cc55cSDimitry Andric       auto *CmpF = dyn_cast<CmpInst>(FV);
4603349cc55cSDimitry Andric       bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
4604349cc55cSDimitry Andric       bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
4605349cc55cSDimitry Andric       if (InvertibleT && InvertibleF) {
4606349cc55cSDimitry Andric         if (CmpT)
4607349cc55cSDimitry Andric           CmpT->setPredicate(CmpT->getInversePredicate());
4608349cc55cSDimitry Andric         else
4609349cc55cSDimitry Andric           Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
4610349cc55cSDimitry Andric         if (CmpF)
4611349cc55cSDimitry Andric           CmpF->setPredicate(CmpF->getInversePredicate());
4612349cc55cSDimitry Andric         else
4613349cc55cSDimitry Andric           Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
4614349cc55cSDimitry Andric         return replaceInstUsesWith(I, Sel);
4615349cc55cSDimitry Andric       }
4616349cc55cSDimitry Andric     }
4617349cc55cSDimitry Andric   }
4618349cc55cSDimitry Andric 
4619bdd1243dSDimitry Andric   if (Instruction *NewXor = foldNotXor(I, Builder))
4620349cc55cSDimitry Andric     return NewXor;
4621349cc55cSDimitry Andric 
46225f757f3fSDimitry Andric   // TODO: Could handle multi-use better by checking if all uses of NotOp (other
46235f757f3fSDimitry Andric   // than I) can be inverted.
46245f757f3fSDimitry Andric   if (Value *R = getFreelyInverted(NotOp, NotOp->hasOneUse(), &Builder))
46255f757f3fSDimitry Andric     return replaceInstUsesWith(I, R);
46265f757f3fSDimitry Andric 
4627349cc55cSDimitry Andric   return nullptr;
4628349cc55cSDimitry Andric }
4629349cc55cSDimitry Andric 
4630349cc55cSDimitry Andric // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
4631349cc55cSDimitry Andric // here. We should standardize that construct where it is needed or choose some
4632349cc55cSDimitry Andric // other way to ensure that commutated variants of patterns are not missed.
4633349cc55cSDimitry Andric Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
463481ad6265SDimitry Andric   if (Value *V = simplifyXorInst(I.getOperand(0), I.getOperand(1),
4635349cc55cSDimitry Andric                                  SQ.getWithInstruction(&I)))
4636349cc55cSDimitry Andric     return replaceInstUsesWith(I, V);
4637349cc55cSDimitry Andric 
4638349cc55cSDimitry Andric   if (SimplifyAssociativeOrCommutative(I))
4639349cc55cSDimitry Andric     return &I;
4640349cc55cSDimitry Andric 
4641349cc55cSDimitry Andric   if (Instruction *X = foldVectorBinop(I))
4642349cc55cSDimitry Andric     return X;
4643349cc55cSDimitry Andric 
464404eeddc0SDimitry Andric   if (Instruction *Phi = foldBinopWithPhiOperands(I))
464504eeddc0SDimitry Andric     return Phi;
464604eeddc0SDimitry Andric 
4647349cc55cSDimitry Andric   if (Instruction *NewXor = foldXorToXor(I, Builder))
4648349cc55cSDimitry Andric     return NewXor;
4649349cc55cSDimitry Andric 
4650349cc55cSDimitry Andric   // (A&B)^(A&C) -> A&(B^C) etc
4651bdd1243dSDimitry Andric   if (Value *V = foldUsingDistributiveLaws(I))
4652349cc55cSDimitry Andric     return replaceInstUsesWith(I, V);
4653349cc55cSDimitry Andric 
4654349cc55cSDimitry Andric   // See if we can simplify any instructions used by the instruction whose sole
4655349cc55cSDimitry Andric   // purpose is to compute bits we don't care about.
4656349cc55cSDimitry Andric   if (SimplifyDemandedInstructionBits(I))
4657349cc55cSDimitry Andric     return &I;
4658349cc55cSDimitry Andric 
4659349cc55cSDimitry Andric   if (Instruction *R = foldNot(I))
4660349cc55cSDimitry Andric     return R;
4661349cc55cSDimitry Andric 
466206c3fb27SDimitry Andric   if (Instruction *R = foldBinOpShiftWithShift(I))
466306c3fb27SDimitry Andric     return R;
466406c3fb27SDimitry Andric 
4665349cc55cSDimitry Andric   // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M)
4666349cc55cSDimitry Andric   // This it a special case in haveNoCommonBitsSet, but the computeKnownBits
4667349cc55cSDimitry Andric   // calls in there are unnecessary as SimplifyDemandedInstructionBits should
4668349cc55cSDimitry Andric   // have already taken care of those cases.
4669349cc55cSDimitry Andric   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4670349cc55cSDimitry Andric   Value *M;
4671349cc55cSDimitry Andric   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
46720fca6ea1SDimitry Andric                         m_c_And(m_Deferred(M), m_Value())))) {
46730fca6ea1SDimitry Andric     if (isGuaranteedNotToBeUndef(M))
46745f757f3fSDimitry Andric       return BinaryOperator::CreateDisjointOr(Op0, Op1);
46750fca6ea1SDimitry Andric     else
46760fca6ea1SDimitry Andric       return BinaryOperator::CreateOr(Op0, Op1);
46770fca6ea1SDimitry Andric   }
4678349cc55cSDimitry Andric 
4679349cc55cSDimitry Andric   if (Instruction *Xor = visitMaskedMerge(I, Builder))
4680349cc55cSDimitry Andric     return Xor;
4681349cc55cSDimitry Andric 
4682349cc55cSDimitry Andric   Value *X, *Y;
46830b57cec5SDimitry Andric   Constant *C1;
46840b57cec5SDimitry Andric   if (match(Op1, m_Constant(C1))) {
46850b57cec5SDimitry Andric     Constant *C2;
468681ad6265SDimitry Andric 
468781ad6265SDimitry Andric     if (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C2)))) &&
468881ad6265SDimitry Andric         match(C1, m_ImmConstant())) {
468981ad6265SDimitry Andric       // (X | C2) ^ C1 --> (X & ~C2) ^ (C1^C2)
469081ad6265SDimitry Andric       C2 = Constant::replaceUndefsWith(
469181ad6265SDimitry Andric           C2, Constant::getAllOnesValue(C2->getType()->getScalarType()));
469281ad6265SDimitry Andric       Value *And = Builder.CreateAnd(
469381ad6265SDimitry Andric           X, Constant::mergeUndefsWith(ConstantExpr::getNot(C2), C1));
469481ad6265SDimitry Andric       return BinaryOperator::CreateXor(
469581ad6265SDimitry Andric           And, Constant::mergeUndefsWith(ConstantExpr::getXor(C1, C2), C1));
469681ad6265SDimitry Andric     }
469781ad6265SDimitry Andric 
469881ad6265SDimitry Andric     // Use DeMorgan and reassociation to eliminate a 'not' op.
46990b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
47000b57cec5SDimitry Andric       // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1
47010b57cec5SDimitry Andric       Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
47020b57cec5SDimitry Andric       return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
47030b57cec5SDimitry Andric     }
47040b57cec5SDimitry Andric     if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
47050b57cec5SDimitry Andric       // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1
47060b57cec5SDimitry Andric       Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
47070b57cec5SDimitry Andric       return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
47080b57cec5SDimitry Andric     }
4709349cc55cSDimitry Andric 
4710349cc55cSDimitry Andric     // Convert xor ([trunc] (ashr X, BW-1)), C =>
4711349cc55cSDimitry Andric     //   select(X >s -1, C, ~C)
4712349cc55cSDimitry Andric     // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the
4713349cc55cSDimitry Andric     // constant depending on whether this input is less than 0.
4714349cc55cSDimitry Andric     const APInt *CA;
4715349cc55cSDimitry Andric     if (match(Op0, m_OneUse(m_TruncOrSelf(
47160fca6ea1SDimitry Andric                        m_AShr(m_Value(X), m_APIntAllowPoison(CA))))) &&
4717349cc55cSDimitry Andric         *CA == X->getType()->getScalarSizeInBits() - 1 &&
4718349cc55cSDimitry Andric         !match(C1, m_AllOnes())) {
4719349cc55cSDimitry Andric       assert(!C1->isZeroValue() && "Unexpected xor with 0");
472081ad6265SDimitry Andric       Value *IsNotNeg = Builder.CreateIsNotNeg(X);
472181ad6265SDimitry Andric       return SelectInst::Create(IsNotNeg, Op1, Builder.CreateNot(Op1));
4722349cc55cSDimitry Andric     }
47230b57cec5SDimitry Andric   }
47240b57cec5SDimitry Andric 
4725349cc55cSDimitry Andric   Type *Ty = I.getType();
47260b57cec5SDimitry Andric   {
47270b57cec5SDimitry Andric     const APInt *RHSC;
47280b57cec5SDimitry Andric     if (match(Op1, m_APInt(RHSC))) {
47290b57cec5SDimitry Andric       Value *X;
47300b57cec5SDimitry Andric       const APInt *C;
4731e8d8bef9SDimitry Andric       // (C - X) ^ signmaskC --> (C + signmaskC) - X
4732e8d8bef9SDimitry Andric       if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
4733e8d8bef9SDimitry Andric         return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
47340b57cec5SDimitry Andric 
4735e8d8bef9SDimitry Andric       // (X + C) ^ signmaskC --> X + (C + signmaskC)
4736e8d8bef9SDimitry Andric       if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
4737e8d8bef9SDimitry Andric         return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
4738e8d8bef9SDimitry Andric 
4739e8d8bef9SDimitry Andric       // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0
47400b57cec5SDimitry Andric       if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
4741e8d8bef9SDimitry Andric           MaskedValueIsZero(X, *C, 0, &I))
4742e8d8bef9SDimitry Andric         return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
4743e8d8bef9SDimitry Andric 
4744bdd1243dSDimitry Andric       // When X is a power-of-two or zero and zero input is poison:
4745bdd1243dSDimitry Andric       // ctlz(i32 X) ^ 31 --> cttz(X)
4746bdd1243dSDimitry Andric       // cttz(i32 X) ^ 31 --> ctlz(X)
4747bdd1243dSDimitry Andric       auto *II = dyn_cast<IntrinsicInst>(Op0);
4748bdd1243dSDimitry Andric       if (II && II->hasOneUse() && *RHSC == Ty->getScalarSizeInBits() - 1) {
4749bdd1243dSDimitry Andric         Intrinsic::ID IID = II->getIntrinsicID();
4750bdd1243dSDimitry Andric         if ((IID == Intrinsic::ctlz || IID == Intrinsic::cttz) &&
4751bdd1243dSDimitry Andric             match(II->getArgOperand(1), m_One()) &&
4752bdd1243dSDimitry Andric             isKnownToBeAPowerOfTwo(II->getArgOperand(0), /*OrZero */ true)) {
4753bdd1243dSDimitry Andric           IID = (IID == Intrinsic::ctlz) ? Intrinsic::cttz : Intrinsic::ctlz;
4754bdd1243dSDimitry Andric           Function *F = Intrinsic::getDeclaration(II->getModule(), IID, Ty);
4755bdd1243dSDimitry Andric           return CallInst::Create(F, {II->getArgOperand(0), Builder.getTrue()});
4756bdd1243dSDimitry Andric         }
4757bdd1243dSDimitry Andric       }
4758bdd1243dSDimitry Andric 
4759e8d8bef9SDimitry Andric       // If RHSC is inverting the remaining bits of shifted X,
4760e8d8bef9SDimitry Andric       // canonicalize to a 'not' before the shift to help SCEV and codegen:
4761e8d8bef9SDimitry Andric       // (X << C) ^ RHSC --> ~X << C
4762e8d8bef9SDimitry Andric       if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
4763349cc55cSDimitry Andric           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
4764e8d8bef9SDimitry Andric         Value *NotX = Builder.CreateNot(X);
4765e8d8bef9SDimitry Andric         return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
47660b57cec5SDimitry Andric       }
4767e8d8bef9SDimitry Andric       // (X >>u C) ^ RHSC --> ~X >>u C
4768e8d8bef9SDimitry Andric       if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
4769349cc55cSDimitry Andric           *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
4770e8d8bef9SDimitry Andric         Value *NotX = Builder.CreateNot(X);
4771e8d8bef9SDimitry Andric         return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
4772e8d8bef9SDimitry Andric       }
4773e8d8bef9SDimitry Andric       // TODO: We could handle 'ashr' here as well. That would be matching
4774e8d8bef9SDimitry Andric       //       a 'not' op and moving it before the shift. Doing that requires
4775e8d8bef9SDimitry Andric       //       preventing the inverse fold in canShiftBinOpWithConstantRHS().
47760b57cec5SDimitry Andric     }
47775f757f3fSDimitry Andric 
47785f757f3fSDimitry Andric     // If we are XORing the sign bit of a floating-point value, convert
47795f757f3fSDimitry Andric     // this to fneg, then cast back to integer.
47805f757f3fSDimitry Andric     //
47815f757f3fSDimitry Andric     // This is generous interpretation of noimplicitfloat, this is not a true
47825f757f3fSDimitry Andric     // floating-point operation.
47835f757f3fSDimitry Andric     //
47845f757f3fSDimitry Andric     // Assumes any IEEE-represented type has the sign bit in the high bit.
47855f757f3fSDimitry Andric     // TODO: Unify with APInt matcher. This version allows undef unlike m_APInt
47865f757f3fSDimitry Andric     Value *CastOp;
47870fca6ea1SDimitry Andric     if (match(Op0, m_ElementWiseBitCast(m_Value(CastOp))) &&
47880fca6ea1SDimitry Andric         match(Op1, m_SignMask()) &&
47895f757f3fSDimitry Andric         !Builder.GetInsertBlock()->getParent()->hasFnAttribute(
47905f757f3fSDimitry Andric             Attribute::NoImplicitFloat)) {
47915f757f3fSDimitry Andric       Type *EltTy = CastOp->getType()->getScalarType();
47920fca6ea1SDimitry Andric       if (EltTy->isFloatingPointTy() && EltTy->isIEEE()) {
47935f757f3fSDimitry Andric         Value *FNeg = Builder.CreateFNeg(CastOp);
47945f757f3fSDimitry Andric         return new BitCastInst(FNeg, I.getType());
47955f757f3fSDimitry Andric       }
47965f757f3fSDimitry Andric     }
47970b57cec5SDimitry Andric   }
47980b57cec5SDimitry Andric 
4799e8d8bef9SDimitry Andric   // FIXME: This should not be limited to scalar (pull into APInt match above).
4800e8d8bef9SDimitry Andric   {
4801e8d8bef9SDimitry Andric     Value *X;
4802e8d8bef9SDimitry Andric     ConstantInt *C1, *C2, *C3;
48030b57cec5SDimitry Andric     // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
4804e8d8bef9SDimitry Andric     if (match(Op1, m_ConstantInt(C3)) &&
4805e8d8bef9SDimitry Andric         match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
4806e8d8bef9SDimitry Andric                           m_ConstantInt(C2))) &&
4807e8d8bef9SDimitry Andric         Op0->hasOneUse()) {
48080b57cec5SDimitry Andric       // fold (C1 >> C2) ^ C3
48090b57cec5SDimitry Andric       APInt FoldConst = C1->getValue().lshr(C2->getValue());
48100b57cec5SDimitry Andric       FoldConst ^= C3->getValue();
48110b57cec5SDimitry Andric       // Prepare the two operands.
481281ad6265SDimitry Andric       auto *Opnd0 = Builder.CreateLShr(X, C2);
481381ad6265SDimitry Andric       Opnd0->takeName(Op0);
4814e8d8bef9SDimitry Andric       return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
48150b57cec5SDimitry Andric     }
48160b57cec5SDimitry Andric   }
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric   if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
48190b57cec5SDimitry Andric     return FoldedLogic;
48200b57cec5SDimitry Andric 
48210b57cec5SDimitry Andric   // Y ^ (X | Y) --> X & ~Y
48220b57cec5SDimitry Andric   // Y ^ (Y | X) --> X & ~Y
48230b57cec5SDimitry Andric   if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
48240b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
48250b57cec5SDimitry Andric   // (X | Y) ^ Y --> X & ~Y
48260b57cec5SDimitry Andric   // (Y | X) ^ Y --> X & ~Y
48270b57cec5SDimitry Andric   if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
48280b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric   // Y ^ (X & Y) --> ~X & Y
48310b57cec5SDimitry Andric   // Y ^ (Y & X) --> ~X & Y
48320b57cec5SDimitry Andric   if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
48330b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
48340b57cec5SDimitry Andric   // (X & Y) ^ Y --> ~X & Y
48350b57cec5SDimitry Andric   // (Y & X) ^ Y --> ~X & Y
48360b57cec5SDimitry Andric   // Canonical form is (X & C) ^ C; don't touch that.
48370b57cec5SDimitry Andric   // TODO: A 'not' op is better for analysis and codegen, but demanded bits must
48380b57cec5SDimitry Andric   //       be fixed to prefer that (otherwise we get infinite looping).
48390b57cec5SDimitry Andric   if (!match(Op1, m_Constant()) &&
48400b57cec5SDimitry Andric       match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
48410b57cec5SDimitry Andric     return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
48420b57cec5SDimitry Andric 
48430b57cec5SDimitry Andric   Value *A, *B, *C;
48440b57cec5SDimitry Andric   // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants.
48450b57cec5SDimitry Andric   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
48460b57cec5SDimitry Andric                         m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
48470b57cec5SDimitry Andric       return BinaryOperator::CreateXor(
48480b57cec5SDimitry Andric           Builder.CreateAnd(Builder.CreateNot(A), C), B);
48490b57cec5SDimitry Andric 
48500b57cec5SDimitry Andric   // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants.
48510b57cec5SDimitry Andric   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
48520b57cec5SDimitry Andric                         m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
48530b57cec5SDimitry Andric       return BinaryOperator::CreateXor(
48540b57cec5SDimitry Andric           Builder.CreateAnd(Builder.CreateNot(B), C), A);
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric   // (A & B) ^ (A ^ B) -> (A | B)
48570b57cec5SDimitry Andric   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
48580b57cec5SDimitry Andric       match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
48590b57cec5SDimitry Andric     return BinaryOperator::CreateOr(A, B);
48600b57cec5SDimitry Andric   // (A ^ B) ^ (A & B) -> (A | B)
48610b57cec5SDimitry Andric   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
48620b57cec5SDimitry Andric       match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
48630b57cec5SDimitry Andric     return BinaryOperator::CreateOr(A, B);
48640b57cec5SDimitry Andric 
48650b57cec5SDimitry Andric   // (A & ~B) ^ ~A -> ~(A & B)
48660b57cec5SDimitry Andric   // (~B & A) ^ ~A -> ~(A & B)
48670b57cec5SDimitry Andric   if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
48680b57cec5SDimitry Andric       match(Op1, m_Not(m_Specific(A))))
48690b57cec5SDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
48700b57cec5SDimitry Andric 
4871e8d8bef9SDimitry Andric   // (~A & B) ^ A --> A | B -- There are 4 commuted variants.
4872e8d8bef9SDimitry Andric   if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
4873e8d8bef9SDimitry Andric     return BinaryOperator::CreateOr(A, B);
4874e8d8bef9SDimitry Andric 
48754824e7fdSDimitry Andric   // (~A | B) ^ A --> ~(A & B)
48764824e7fdSDimitry Andric   if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
48774824e7fdSDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
48784824e7fdSDimitry Andric 
48794824e7fdSDimitry Andric   // A ^ (~A | B) --> ~(A & B)
48804824e7fdSDimitry Andric   if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
48814824e7fdSDimitry Andric     return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
48824824e7fdSDimitry Andric 
4883e8d8bef9SDimitry Andric   // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants.
4884e8d8bef9SDimitry Andric   // TODO: Loosen one-use restriction if common operand is a constant.
4885e8d8bef9SDimitry Andric   Value *D;
4886e8d8bef9SDimitry Andric   if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
4887e8d8bef9SDimitry Andric       match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
4888e8d8bef9SDimitry Andric     if (B == C || B == D)
4889e8d8bef9SDimitry Andric       std::swap(A, B);
4890e8d8bef9SDimitry Andric     if (A == C)
4891e8d8bef9SDimitry Andric       std::swap(C, D);
4892e8d8bef9SDimitry Andric     if (A == D) {
4893e8d8bef9SDimitry Andric       Value *NotA = Builder.CreateNot(A);
4894e8d8bef9SDimitry Andric       return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
4895e8d8bef9SDimitry Andric     }
4896e8d8bef9SDimitry Andric   }
4897e8d8bef9SDimitry Andric 
489806c3fb27SDimitry Andric   // (A & B) ^ (A | C) --> A ? ~B : C -- There are 4 commuted variants.
489906c3fb27SDimitry Andric   if (I.getType()->isIntOrIntVectorTy(1) &&
490006c3fb27SDimitry Andric       match(Op0, m_OneUse(m_LogicalAnd(m_Value(A), m_Value(B)))) &&
490106c3fb27SDimitry Andric       match(Op1, m_OneUse(m_LogicalOr(m_Value(C), m_Value(D))))) {
490206c3fb27SDimitry Andric     bool NeedFreeze = isa<SelectInst>(Op0) && isa<SelectInst>(Op1) && B == D;
490306c3fb27SDimitry Andric     if (B == C || B == D)
490406c3fb27SDimitry Andric       std::swap(A, B);
490506c3fb27SDimitry Andric     if (A == C)
490606c3fb27SDimitry Andric       std::swap(C, D);
490706c3fb27SDimitry Andric     if (A == D) {
490806c3fb27SDimitry Andric       if (NeedFreeze)
490906c3fb27SDimitry Andric         A = Builder.CreateFreeze(A);
491006c3fb27SDimitry Andric       Value *NotB = Builder.CreateNot(B);
491106c3fb27SDimitry Andric       return SelectInst::Create(A, NotB, C);
491206c3fb27SDimitry Andric     }
491306c3fb27SDimitry Andric   }
491406c3fb27SDimitry Andric 
49150b57cec5SDimitry Andric   if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
49160b57cec5SDimitry Andric     if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
49178bcb0991SDimitry Andric       if (Value *V = foldXorOfICmps(LHS, RHS, I))
49180b57cec5SDimitry Andric         return replaceInstUsesWith(I, V);
49190b57cec5SDimitry Andric 
49200b57cec5SDimitry Andric   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
49210b57cec5SDimitry Andric     return CastedXor;
49220b57cec5SDimitry Andric 
4923fe6060f1SDimitry Andric   if (Instruction *Abs = canonicalizeAbs(I, Builder))
4924fe6060f1SDimitry Andric     return Abs;
4925fe6060f1SDimitry Andric 
4926e8d8bef9SDimitry Andric   // Otherwise, if all else failed, try to hoist the xor-by-constant:
4927e8d8bef9SDimitry Andric   //   (X ^ C) ^ Y --> (X ^ Y) ^ C
4928e8d8bef9SDimitry Andric   // Just like we do in other places, we completely avoid the fold
4929e8d8bef9SDimitry Andric   // for constantexprs, at least to avoid endless combine loop.
4930e8d8bef9SDimitry Andric   if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
4931e8d8bef9SDimitry Andric                                                     m_Unless(m_ConstantExpr())),
4932e8d8bef9SDimitry Andric                                        m_ImmConstant(C1))),
4933e8d8bef9SDimitry Andric                         m_Value(Y))))
4934e8d8bef9SDimitry Andric     return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
4935e8d8bef9SDimitry Andric 
4936bdd1243dSDimitry Andric   if (Instruction *R = reassociateForUses(I, Builder))
4937bdd1243dSDimitry Andric     return R;
4938bdd1243dSDimitry Andric 
4939bdd1243dSDimitry Andric   if (Instruction *Canonicalized = canonicalizeLogicFirst(I, Builder))
4940bdd1243dSDimitry Andric     return Canonicalized;
4941bdd1243dSDimitry Andric 
4942bdd1243dSDimitry Andric   if (Instruction *Folded = foldLogicOfIsFPClass(I, Op0, Op1))
4943bdd1243dSDimitry Andric     return Folded;
4944bdd1243dSDimitry Andric 
4945bdd1243dSDimitry Andric   if (Instruction *Folded = canonicalizeConditionalNegationViaMathToSelect(I))
4946bdd1243dSDimitry Andric     return Folded;
4947bdd1243dSDimitry Andric 
494806c3fb27SDimitry Andric   if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
494906c3fb27SDimitry Andric     return Res;
495006c3fb27SDimitry Andric 
4951297eecfbSDimitry Andric   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
4952297eecfbSDimitry Andric     return Res;
4953297eecfbSDimitry Andric 
49540b57cec5SDimitry Andric   return nullptr;
49550b57cec5SDimitry Andric }
4956