#include "InstCombineInternal.h"
#include "llvm/Analysis/CmpInstAnalysis.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS,
InstCombiner::BuilderTy &Builder) {
ICmpInst::Predicate NewPred;
if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred))
return TorF;
return Builder.CreateICmp(NewPred, LHS, RHS);
}
static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
InstCombiner::BuilderTy &Builder) {
FCmpInst::Predicate NewPred;
if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred))
return TorF;
return Builder.CreateFCmp(NewPred, LHS, RHS);
}
static Value *SimplifyBSwap(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying");
Value *OldLHS = I.getOperand(0);
Value *OldRHS = I.getOperand(1);
Value *NewLHS;
if (!match(OldLHS, m_BSwap(m_Value(NewLHS))))
return nullptr;
Value *NewRHS;
const APInt *C;
if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) {
if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse())
return nullptr;
} else if (match(OldRHS, m_APInt(C))) {
if (!OldLHS->hasOneUse())
return nullptr;
NewRHS = ConstantInt::get(I.getType(), C->byteSwap());
} else
return nullptr;
Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap,
I.getType());
return Builder.CreateCall(F, BinOp);
}
Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo,
const APInt &Hi, bool isSigned,
bool Inside) {
assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) &&
"Lo is not < Hi in range emission code!");
Type *Ty = V->getType();
ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
}
Value *VMinusLo =
Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo);
}
enum MaskedICmpType {
AMask_AllOnes = 1,
AMask_NotAllOnes = 2,
BMask_AllOnes = 4,
BMask_NotAllOnes = 8,
Mask_AllZeros = 16,
Mask_NotAllZeros = 32,
AMask_Mixed = 64,
AMask_NotMixed = 128,
BMask_Mixed = 256,
BMask_NotMixed = 512
};
static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
ICmpInst::Predicate Pred) {
const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr;
match(A, m_APInt(ConstA));
match(B, m_APInt(ConstB));
match(C, m_APInt(ConstC));
bool IsEq = (Pred == ICmpInst::ICMP_EQ);
bool IsAPow2 = ConstA && ConstA->isPowerOf2();
bool IsBPow2 = ConstB && ConstB->isPowerOf2();
unsigned MaskVal = 0;
if (ConstC && ConstC->isZero()) {
MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
: (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
if (IsAPow2)
MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
: (AMask_AllOnes | AMask_Mixed));
if (IsBPow2)
MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
: (BMask_AllOnes | BMask_Mixed));
return MaskVal;
}
if (A == C) {
MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
: (AMask_NotAllOnes | AMask_NotMixed));
if (IsAPow2)
MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
: (Mask_AllZeros | AMask_Mixed));
} else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) {
MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
}
if (B == C) {
MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
: (BMask_NotAllOnes | BMask_NotMixed));
if (IsBPow2)
MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
: (Mask_AllZeros | BMask_Mixed));
} else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) {
MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
}
return MaskVal;
}
static unsigned conjugateICmpMask(unsigned Mask) {
unsigned NewMask;
NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
AMask_Mixed | BMask_Mixed))
<< 1;
NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
AMask_NotMixed | BMask_NotMixed))
>> 1;
return NewMask;
}
static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred,
Value *&X, Value *&Y, Value *&Z) {
APInt Mask;
if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask))
return false;
Y = ConstantInt::get(X->getType(), Mask);
Z = ConstantInt::get(X->getType(), 0);
return true;
}
static
Optional<std::pair<unsigned, unsigned>>
getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
Value *&D, Value *&E, ICmpInst *LHS,
ICmpInst *RHS,
ICmpInst::Predicate &PredL,
ICmpInst::Predicate &PredR) {
if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() ||
!RHS->getOperand(0)->getType()->isIntOrIntVectorTy())
return None;
Value *L1 = LHS->getOperand(0);
Value *L2 = LHS->getOperand(1);
Value *L11, *L12, *L21, *L22;
if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) {
L21 = L22 = L1 = nullptr;
} else {
if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
L11 = L1;
L12 = Constant::getAllOnesValue(L1->getType());
}
if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
L21 = L2;
L22 = Constant::getAllOnesValue(L2->getType());
}
}
if (!ICmpInst::isEquality(PredL))
return None;
Value *R1 = RHS->getOperand(0);
Value *R2 = RHS->getOperand(1);
Value *R11, *R12;
bool Ok = false;
if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) {
if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
A = R11;
D = R12;
} else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
A = R12;
D = R11;
} else {
return None;
}
E = R2;
R1 = nullptr;
Ok = true;
} else {
if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
R11 = R1;
R12 = Constant::getAllOnesValue(R1->getType());
}
if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
A = R11;
D = R12;
E = R2;
Ok = true;
} else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
A = R12;
D = R11;
E = R2;
Ok = true;
}
}
if (!ICmpInst::isEquality(PredR))
return None;
if (!Ok) {
if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
R11 = R2;
R12 = Constant::getAllOnesValue(R2->getType());
}
if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
A = R11;
D = R12;
E = R1;
Ok = true;
} else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
A = R12;
D = R11;
E = R1;
Ok = true;
} else {
return None;
}
assert(Ok && "Failed to find AND on the right side of the RHS icmp.");
}
if (L11 == A) {
B = L12;
C = L2;
} else if (L12 == A) {
B = L11;
C = L2;
} else if (L21 == A) {
B = L22;
C = L1;
} else if (L22 == A) {
B = L21;
C = L1;
}
unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
unsigned RightType = getMaskedICmpType(A, D, E, PredR);
return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType));
}
static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
InstCombiner::BuilderTy &Builder) {
const APInt *BCst, *CCst, *DCst, *OrigECst;
if (!match(B, m_APInt(BCst)) || !match(C, m_APInt(CCst)) ||
!match(D, m_APInt(DCst)) || !match(E, m_APInt(OrigECst)))
return nullptr;
ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
APInt ECst = *OrigECst;
if (PredR != NewCC)
ECst ^= *DCst;
if (*BCst == 0 || *DCst == 0)
return nullptr;
if ((*BCst & *DCst) == 0)
return nullptr;
if ((((*BCst & *DCst) & ECst) == 0) &&
(*BCst & (*BCst ^ *DCst)).isPowerOf2()) {
APInt BorD = *BCst | *DCst;
APInt BandBxorDorE = (*BCst & (*BCst ^ *DCst)) | ECst;
Value *NewMask = ConstantInt::get(A->getType(), BorD);
Value *NewMaskedValue = ConstantInt::get(A->getType(), BandBxorDorE);
Value *NewAnd = Builder.CreateAnd(A, NewMask);
return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue);
}
auto IsSubSetOrEqual = [](const APInt *C1, const APInt *C2) {
return (*C1 & *C2) == *C1;
};
auto IsSuperSetOrEqual = [](const APInt *C1, const APInt *C2) {
return (*C1 & *C2) == *C2;
};
if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst))
return nullptr;
if (ECst.isZero()) {
if (IsSubSetOrEqual(BCst, DCst))
return ConstantInt::get(LHS->getType(), !IsAnd);
return nullptr;
}
if (IsSuperSetOrEqual(BCst, DCst))
return RHS;
assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code");
if ((*BCst & ECst) != 0)
return RHS;
return ConstantInt::get(LHS->getType(), !IsAnd);
}
static Value *foldLogOpOfMaskedICmpsAsymmetric(
ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C,
Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR,
unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) {
assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
"Expected equality predicates for masked type of icmps.");
if (!IsAnd) {
LHSMask = conjugateICmpMask(LHSMask);
RHSMask = conjugateICmpMask(RHSMask);
}
if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) {
if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
LHS, RHS, IsAnd, A, B, C, D, E,
PredL, PredR, Builder)) {
return V;
}
} else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) {
if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed(
RHS, LHS, IsAnd, A, D, E, B, C,
PredR, PredL, Builder)) {
return V;
}
}
return nullptr;
}
static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
bool IsLogical,
InstCombiner::BuilderTy &Builder) {
Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Optional<std::pair<unsigned, unsigned>> MaskPair =
getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
if (!MaskPair)
return nullptr;
assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
"Expected equality predicates for masked type of icmps.");
unsigned LHSMask = MaskPair->first;
unsigned RHSMask = MaskPair->second;
unsigned Mask = LHSMask & RHSMask;
if (Mask == 0) {
if (Value *V = foldLogOpOfMaskedICmpsAsymmetric(
LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask,
Builder))
return V;
return nullptr;
}
ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
if (!IsAnd) {
Mask = conjugateICmpMask(Mask);
}
if (Mask & Mask_AllZeros) {
if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
return nullptr; Value *NewOr = Builder.CreateOr(B, D);
Value *NewAnd = Builder.CreateAnd(A, NewOr);
Value *Zero = Constant::getNullValue(A->getType());
return Builder.CreateICmp(NewCC, NewAnd, Zero);
}
if (Mask & BMask_AllOnes) {
if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
return nullptr; Value *NewOr = Builder.CreateOr(B, D);
Value *NewAnd = Builder.CreateAnd(A, NewOr);
return Builder.CreateICmp(NewCC, NewAnd, NewOr);
}
if (Mask & AMask_AllOnes) {
if (IsLogical && !isGuaranteedNotToBeUndefOrPoison(D))
return nullptr; Value *NewAnd1 = Builder.CreateAnd(B, D);
Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1);
return Builder.CreateICmp(NewCC, NewAnd2, A);
}
const APInt *ConstB, *ConstD;
if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD)))
return nullptr;
if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
APInt NewMask = *ConstB & *ConstD;
if (NewMask == *ConstB)
return LHS;
else if (NewMask == *ConstD)
return RHS;
}
if (Mask & AMask_NotAllOnes) {
APInt NewMask = *ConstB | *ConstD;
if (NewMask == *ConstB)
return LHS;
else if (NewMask == *ConstD)
return RHS;
}
if (Mask & BMask_Mixed) {
const APInt *OldConstC, *OldConstE;
if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE)))
return nullptr;
const APInt ConstC = PredL != NewCC ? *ConstB ^ *OldConstC : *OldConstC;
const APInt ConstE = PredR != NewCC ? *ConstD ^ *OldConstE : *OldConstE;
if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue())
return ConstantInt::get(LHS->getType(), !IsAnd);
Value *NewOr1 = Builder.CreateOr(B, D);
Value *NewAnd = Builder.CreateAnd(A, NewOr1);
Constant *NewOr2 = ConstantInt::get(A->getType(), ConstC | ConstE);
return Builder.CreateICmp(NewCC, NewAnd, NewOr2);
}
return nullptr;
}
Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool Inverted) {
ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
if (!RangeStart)
return nullptr;
ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
Cmp0->getPredicate());
if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
(Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
return nullptr;
ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
Cmp1->getPredicate());
Value *Input = Cmp0->getOperand(0);
Value *RangeEnd;
if (Cmp1->getOperand(0) == Input) {
RangeEnd = Cmp1->getOperand(1);
} else if (Cmp1->getOperand(1) == Input) {
RangeEnd = Cmp1->getOperand(0);
Pred1 = ICmpInst::getSwappedPredicate(Pred1);
} else {
return nullptr;
}
ICmpInst::Predicate NewPred;
switch (Pred1) {
case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
default: return nullptr;
}
KnownBits Known = computeKnownBits(RangeEnd, 0, Cmp1);
if (!Known.isNonNegative())
return nullptr;
if (Inverted)
NewPred = ICmpInst::getInversePredicate(NewPred);
return Builder.CreateICmp(NewPred, Input, RangeEnd);
}
Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS,
ICmpInst *RHS,
Instruction *CxtI,
bool IsAnd,
bool IsLogical) {
CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ;
if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred)
return nullptr;
if (!match(LHS->getOperand(1), m_Zero()) ||
!match(RHS->getOperand(1), m_Zero()))
return nullptr;
Value *L1, *L2, *R1, *R2;
if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) &&
match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) {
if (L1 == R2 || L2 == R2)
std::swap(R1, R2);
if (L2 == R1)
std::swap(L1, L2);
if (L1 == R1 &&
isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) &&
isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) {
if (IsLogical)
R2 = Builder.CreateFreeze(R2);
Value *Mask = Builder.CreateOr(L2, R2);
Value *Masked = Builder.CreateAnd(L1, Mask);
auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
return Builder.CreateICmp(NewPred, Masked, Mask);
}
}
return nullptr;
}
static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1,
Instruction &CxtI,
InstCombiner::BuilderTy &Builder) {
assert(CxtI.getOpcode() == Instruction::And);
auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X,
APInt &SignBitMask) -> bool {
CmpInst::Predicate Pred;
const APInt *I01, *I1; if (!(match(ICmp,
m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) &&
Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1))
return false;
SignBitMask = *I01;
return true;
};
Value *X1;
APInt HighestBit;
ICmpInst *OtherICmp;
if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit))
OtherICmp = ICmp0;
else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit))
OtherICmp = ICmp1;
else
return nullptr;
assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)");
auto tryToDecompose = [](ICmpInst *ICmp, Value *&X,
APInt &UnsetBitsMask) -> bool {
CmpInst::Predicate Pred = ICmp->getPredicate();
if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1),
Pred, X, UnsetBitsMask,
false) &&
Pred == ICmpInst::ICMP_EQ)
return true;
const APInt *Mask;
if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) &&
Pred == ICmpInst::ICMP_EQ) {
UnsetBitsMask = *Mask;
return true;
}
return false;
};
Value *X0;
APInt UnsetBitsMask;
if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask))
return nullptr;
assert(!UnsetBitsMask.isZero() && "empty mask makes no sense.");
Value *X;
if (X1 == X0) {
X = X1;
} else if (match(X0, m_Trunc(m_Specific(X1)))) {
UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits());
X = X1;
} else
return nullptr;
APInt SignBitsMask = ~(HighestBit - 1U);
if (!UnsetBitsMask.intersects(SignBitsMask))
return nullptr;
if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) {
APInt OtherHighestBit = (~UnsetBitsMask) + 1U;
if (!OtherHighestBit.isPowerOf2())
return nullptr;
HighestBit = APIntOps::umin(HighestBit, OtherHighestBit);
}
return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit),
CxtI.getName() + ".simplified");
}
static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd,
InstCombiner::BuilderTy &Builder) {
CmpInst::Predicate Pred0, Pred1;
Value *X;
if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
m_SpecificInt(1))) ||
!match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())))
return nullptr;
Value *CtPop = Cmp0->getOperand(0);
if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE)
return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1));
if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ)
return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2));
return nullptr;
}
static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd,
InstCombiner::BuilderTy &Builder) {
if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE)
std::swap(Cmp0, Cmp1);
else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ)
std::swap(Cmp0, Cmp1);
CmpInst::Predicate Pred0, Pred1;
Value *X;
if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
m_SpecificInt(2))) &&
Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) {
Value *CtPop = Cmp1->getOperand(0);
return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1));
}
if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) &&
match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)),
m_SpecificInt(1))) &&
Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) {
Value *CtPop = Cmp1->getOperand(0);
return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1));
}
return nullptr;
}
static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp,
ICmpInst *UnsignedICmp, bool IsAnd,
const SimplifyQuery &Q,
InstCombiner::BuilderTy &Builder) {
Value *ZeroCmpOp;
ICmpInst::Predicate EqPred;
if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) ||
!ICmpInst::isEquality(EqPred))
return nullptr;
auto IsKnownNonZero = [&](Value *V) {
return isKnownNonZero(V, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
};
ICmpInst::Predicate UnsignedPred;
Value *A, *B;
if (match(UnsignedICmp,
m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) &&
match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) &&
(ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) {
auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) {
if (!IsKnownNonZero(NonZero))
std::swap(NonZero, Other);
return IsKnownNonZero(NonZero);
};
if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE &&
IsAnd && GetKnownNonZeroAndOther(B, A))
return Builder.CreateICmpULT(Builder.CreateNeg(B), A);
if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ &&
!IsAnd && GetKnownNonZeroAndOther(B, A))
return Builder.CreateICmpUGE(Builder.CreateNeg(B), A);
}
Value *Base, *Offset;
if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset))))
return nullptr;
if (!match(UnsignedICmp,
m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) ||
!ICmpInst::isUnsigned(UnsignedPred))
return nullptr;
if ((UnsignedPred == ICmpInst::ICMP_UGE ||
UnsignedPred == ICmpInst::ICMP_UGT) &&
EqPred == ICmpInst::ICMP_NE && IsAnd)
return Builder.CreateICmpUGT(Base, Offset);
if ((UnsignedPred == ICmpInst::ICMP_ULE ||
UnsignedPred == ICmpInst::ICMP_ULT) &&
EqPred == ICmpInst::ICMP_EQ && !IsAnd)
return Builder.CreateICmpULE(Base, Offset);
if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
IsAnd)
return Builder.CreateICmpULT(Base, Offset);
if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
!IsAnd)
return Builder.CreateICmpUGE(Base, Offset);
return nullptr;
}
struct IntPart {
Value *From;
unsigned StartBit;
unsigned NumBits;
};
static Optional<IntPart> matchIntPart(Value *V) {
Value *X;
if (!match(V, m_OneUse(m_Trunc(m_Value(X)))))
return None;
unsigned NumOriginalBits = X->getType()->getScalarSizeInBits();
unsigned NumExtractedBits = V->getType()->getScalarSizeInBits();
Value *Y;
const APInt *Shift;
if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) &&
Shift->ule(NumOriginalBits - NumExtractedBits))
return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}};
return {{X, 0, NumExtractedBits}};
}
static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) {
Value *V = P.From;
if (P.StartBit)
V = Builder.CreateLShr(V, P.StartBit);
Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits);
if (TruncTy != V->getType())
V = Builder.CreateTrunc(V, TruncTy);
return V;
}
Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool IsAnd) {
if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse())
return nullptr;
CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred)
return nullptr;
Optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0));
Optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1));
Optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0));
Optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1));
if (!L0 || !R0 || !L1 || !R1)
return nullptr;
if (L0->From != L1->From || R0->From != R1->From) {
if (L0->From != R1->From || R0->From != L1->From)
return nullptr;
std::swap(L1, R1);
}
if (L0->StartBit + L0->NumBits != L1->StartBit ||
R0->StartBit + R0->NumBits != R1->StartBit) {
if (L1->StartBit + L1->NumBits != L0->StartBit ||
R1->StartBit + R1->NumBits != R0->StartBit)
return nullptr;
std::swap(L0, L1);
std::swap(R0, R1);
}
IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits};
IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits};
Value *LValue = extractIntPart(L, Builder);
Value *RValue = extractIntPart(R, Builder);
return Builder.CreateICmp(Pred, LValue, RValue);
}
static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool IsAnd,
InstCombiner::BuilderTy &Builder,
const SimplifyQuery &Q) {
ICmpInst::Predicate Pred0;
Value *X;
Constant *C;
if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) ||
!isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X))
return nullptr;
if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) ||
(!IsAnd && Pred0 != ICmpInst::ICMP_NE))
return nullptr;
Value *Y;
ICmpInst::Predicate Pred1;
if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X))))
return nullptr;
Value *SubstituteCmp = simplifyICmpInst(Pred1, Y, C, Q);
if (!SubstituteCmp) {
if (!Cmp1->hasOneUse())
return nullptr;
SubstituteCmp = Builder.CreateICmp(Pred1, Y, C);
}
return Builder.CreateBinOp(IsAnd ? Instruction::And : Instruction::Or, Cmp0,
SubstituteCmp);
}
Value *InstCombinerImpl::foldAndOrOfICmpsUsingRanges(ICmpInst *ICmp1,
ICmpInst *ICmp2,
bool IsAnd) {
ICmpInst::Predicate Pred1, Pred2;
Value *V1, *V2;
const APInt *C1, *C2;
if (!match(ICmp1, m_ICmp(Pred1, m_Value(V1), m_APInt(C1))) ||
!match(ICmp2, m_ICmp(Pred2, m_Value(V2), m_APInt(C2))))
return nullptr;
const APInt *Offset1 = nullptr, *Offset2 = nullptr;
if (V1 != V2) {
Value *X;
if (match(V1, m_Add(m_Value(X), m_APInt(Offset1))))
V1 = X;
if (match(V2, m_Add(m_Value(X), m_APInt(Offset2))))
V2 = X;
}
if (V1 != V2)
return nullptr;
ConstantRange CR1 = ConstantRange::makeExactICmpRegion(
IsAnd ? ICmpInst::getInversePredicate(Pred1) : Pred1, *C1);
if (Offset1)
CR1 = CR1.subtract(*Offset1);
ConstantRange CR2 = ConstantRange::makeExactICmpRegion(
IsAnd ? ICmpInst::getInversePredicate(Pred2) : Pred2, *C2);
if (Offset2)
CR2 = CR2.subtract(*Offset2);
Type *Ty = V1->getType();
Value *NewV = V1;
Optional<ConstantRange> CR = CR1.exactUnionWith(CR2);
if (!CR) {
if (!(ICmp1->hasOneUse() && ICmp2->hasOneUse()) || CR1.isWrappedSet() ||
CR2.isWrappedSet())
return nullptr;
APInt LowerDiff = CR1.getLower() ^ CR2.getLower();
APInt UpperDiff = (CR1.getUpper() - 1) ^ (CR2.getUpper() - 1);
APInt CR1Size = CR1.getUpper() - CR1.getLower();
if (!LowerDiff.isPowerOf2() || LowerDiff != UpperDiff ||
CR1Size != CR2.getUpper() - CR2.getLower())
return nullptr;
CR = CR1.getLower().ult(CR2.getLower()) ? CR1 : CR2;
NewV = Builder.CreateAnd(NewV, ConstantInt::get(Ty, ~LowerDiff));
}
if (IsAnd)
CR = CR->inverse();
CmpInst::Predicate NewPred;
APInt NewC, Offset;
CR->getEquivalentICmp(NewPred, NewC, Offset);
if (Offset != 0)
NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset));
return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC));
}
Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS,
bool IsAnd, bool IsLogicalSelect) {
Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
if (LHS0 == RHS1 && RHS0 == LHS1) {
PredR = FCmpInst::getSwappedPredicate(PredR);
std::swap(RHS0, RHS1);
}
if (LHS0 == RHS0 && LHS1 == RHS1) {
unsigned FCmpCodeL = getFCmpCode(PredL);
unsigned FCmpCodeR = getFCmpCode(PredR);
unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR;
IRBuilder<>::FastMathFlagGuard FMFG(Builder);
FastMathFlags FMF = LHS->getFastMathFlags();
FMF &= RHS->getFastMathFlags();
Builder.setFastMathFlags(FMF);
return getFCmpValue(NewPred, LHS0, LHS1, Builder);
}
if (!IsLogicalSelect &&
((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
(PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO &&
!IsAnd))) {
if (LHS0->getType() != RHS0->getType())
return nullptr;
if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP()))
return Builder.CreateFCmp(PredL, LHS0, RHS0);
}
return nullptr;
}
static Instruction *reassociateFCmps(BinaryOperator &BO,
InstCombiner::BuilderTy &Builder) {
Instruction::BinaryOps Opcode = BO.getOpcode();
assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
"Expecting and/or op for fcmp transform");
Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X;
FCmpInst::Predicate Pred;
if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP())))
std::swap(Op0, Op1);
Value *BO10, *BO11;
FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD
: FCmpInst::FCMP_UNO;
if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred ||
!match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11))))
return nullptr;
Value *Y;
if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
Pred != NanPred || X->getType() != Y->getType())
std::swap(BO10, BO11);
if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) ||
Pred != NanPred || X->getType() != Y->getType())
return nullptr;
Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y);
if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) {
NewFCmpInst->copyIRFlags(Op0);
NewFCmpInst->andIRFlags(BO10);
}
return BinaryOperator::Create(Opcode, NewFCmp, BO11);
}
static Instruction *matchDeMorgansLaws(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
const Instruction::BinaryOps Opcode = I.getOpcode();
assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
"Trying to match De Morgan's Laws with something other than and/or");
const Instruction::BinaryOps FlippedOpcode =
(Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Value *A, *B;
if (match(Op0, m_OneUse(m_Not(m_Value(A)))) &&
match(Op1, m_OneUse(m_Not(m_Value(B)))) &&
!InstCombiner::isFreeToInvert(A, A->hasOneUse()) &&
!InstCombiner::isFreeToInvert(B, B->hasOneUse())) {
Value *AndOr =
Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan");
return BinaryOperator::CreateNot(AndOr);
}
Value *C;
if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) &&
match(Op1, m_Not(m_Value(C)))) {
Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C);
return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO));
}
return nullptr;
}
bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) {
Value *CastSrc = CI->getOperand(0);
if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
return false;
if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
if (isEliminableCastPair(PrecedingCI, CI))
return false;
return true;
}
static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
InstCombiner::BuilderTy &Builder) {
Constant *C = dyn_cast<Constant>(Logic.getOperand(1));
if (!C)
return nullptr;
auto LogicOpc = Logic.getOpcode();
Type *DestTy = Logic.getType();
Type *SrcTy = Cast->getSrcTy();
Value *X;
if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
if (ZextTruncC == C) {
Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
return new ZExtInst(NewOp, DestTy);
}
}
if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) {
Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy);
if (SextTruncC == C) {
Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC);
return new SExtInst(NewOp, DestTy);
}
}
return nullptr;
}
Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) {
auto LogicOpc = I.getOpcode();
assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
CastInst *Cast0 = dyn_cast<CastInst>(Op0);
if (!Cast0)
return nullptr;
Type *DestTy = I.getType();
Type *SrcTy = Cast0->getSrcTy();
if (!SrcTy->isIntOrIntVectorTy())
return nullptr;
if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
return Ret;
CastInst *Cast1 = dyn_cast<CastInst>(Op1);
if (!Cast1)
return nullptr;
auto CastOpcode = Cast0->getOpcode();
if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
return nullptr;
Value *Cast0Src = Cast0->getOperand(0);
Value *Cast1Src = Cast1->getOperand(0);
if ((Cast0->hasOneUse() || Cast1->hasOneUse()) &&
shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
I.getName());
return CastInst::Create(CastOpcode, NewOp, DestTy);
}
if (LogicOpc == Instruction::Xor)
return nullptr;
ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
if (ICmp0 && ICmp1) {
if (Value *Res =
foldAndOrOfICmps(ICmp0, ICmp1, I, LogicOpc == Instruction::And))
return CastInst::Create(CastOpcode, Res, DestTy);
return nullptr;
}
FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
if (FCmp0 && FCmp1)
if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And))
return CastInst::Create(CastOpcode, R, DestTy);
return nullptr;
}
static Instruction *foldAndToXor(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert(I.getOpcode() == Instruction::And);
Value *Op0 = I.getOperand(0);
Value *Op1 = I.getOperand(1);
Value *A, *B;
if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)),
m_Not(m_c_And(m_Deferred(A), m_Deferred(B))))))
return BinaryOperator::CreateXor(A, B);
if (Op0->hasOneUse() || Op1->hasOneUse())
if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))),
m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
return nullptr;
}
static Instruction *foldOrToXor(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert(I.getOpcode() == Instruction::Or);
Value *Op0 = I.getOperand(0);
Value *Op1 = I.getOperand(1);
Value *A, *B;
if (Op0->hasOneUse() || Op1->hasOneUse())
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
if (Op0->hasOneUse() || Op1->hasOneUse())
if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
return BinaryOperator::CreateXor(A, B);
return nullptr;
}
static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) {
APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth);
return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold));
}
Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) {
Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1);
Constant *C;
if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) &&
!match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) &&
!match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) &&
!match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) &&
!match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1)))))
return nullptr;
Value *X;
if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3))
return nullptr;
Type *Ty = And.getType();
if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType()))
return nullptr;
Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode();
if (Opc == Instruction::LShr || Opc == Instruction::Shl)
if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits()))
return nullptr;
Value *NewC = ConstantExpr::getTrunc(C, X->getType());
Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X)
: Builder.CreateBinOp(Opc, X, NewC);
return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty);
}
static Instruction *foldComplexAndOrPatterns(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
const Instruction::BinaryOps Opcode = I.getOpcode();
assert(Opcode == Instruction::And || Opcode == Instruction::Or);
const Instruction::BinaryOps FlippedOpcode =
(Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Value *A, *B, *C, *X, *Y, *Dummy;
const auto matchNotOrAnd =
[Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C,
Value *&X, bool CountUses = false) -> bool {
if (CountUses && !Op->hasOneUse())
return false;
if (match(Op, m_c_BinOp(FlippedOpcode,
m_CombineAnd(m_Value(X),
m_Not(m_c_BinOp(Opcode, m_A, m_B))),
m_C)))
return !CountUses || X->hasOneUse();
return false;
};
if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) {
if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy,
true)) {
Value *Xor = Builder.CreateXor(B, C);
return (Opcode == Instruction::Or)
? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A))
: BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A));
}
if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy,
true)) {
Value *Xor = Builder.CreateXor(A, C);
return (Opcode == Instruction::Or)
? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B))
: BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B));
}
if (match(Op1, m_OneUse(m_Not(m_OneUse(
m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
return BinaryOperator::CreateNot(Builder.CreateBinOp(
Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A));
if (match(Op1, m_OneUse(m_Not(m_OneUse(
m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)))))))
return BinaryOperator::CreateNot(Builder.CreateBinOp(
Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B));
if (Opcode == Instruction::Or && Op0->hasOneUse() &&
match(Op1, m_OneUse(m_Not(m_CombineAnd(
m_Value(Y),
m_c_BinOp(Opcode, m_Specific(C),
m_c_Xor(m_Specific(A), m_Specific(B)))))))) {
Value *Or = cast<BinaryOperator>(X)->getOperand(0);
return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y));
}
}
if (match(Op0,
m_OneUse(m_c_BinOp(FlippedOpcode,
m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)),
m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) ||
match(Op0, m_OneUse(m_c_BinOp(
FlippedOpcode,
m_c_BinOp(FlippedOpcode, m_Value(C),
m_CombineAnd(m_Value(X), m_Not(m_Value(A)))),
m_Value(B))))) {
if (match(Op1, m_OneUse(m_Not(m_c_BinOp(
Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)),
m_Specific(C))))) ||
match(Op1, m_OneUse(m_Not(m_c_BinOp(
Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)),
m_Specific(A))))) ||
match(Op1, m_OneUse(m_Not(m_c_BinOp(
Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)),
m_Specific(B)))))) {
Value *Xor = Builder.CreateXor(B, C);
return (Opcode == Instruction::Or)
? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A))
: BinaryOperator::CreateOr(Xor, X);
}
if (match(Op1, m_OneUse(m_Not(m_OneUse(
m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)))))))
return BinaryOperator::Create(
FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)),
X);
if (match(Op1, m_OneUse(m_Not(m_OneUse(
m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)))))))
return BinaryOperator::Create(
FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)),
X);
}
return nullptr;
}
Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
Type *Ty = I.getType();
if (Value *V = simplifyAndInst(I.getOperand(0), I.getOperand(1),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
if (SimplifyDemandedInstructionBits(I))
return &I;
if (Instruction *Xor = foldAndToXor(I, Builder))
return Xor;
if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
return X;
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
if (Value *V = SimplifyBSwap(I, Builder))
return replaceInstUsesWith(I, V);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Value *X, *Y;
if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) &&
match(Op1, m_One())) {
Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0));
return new ZExtInst(IsZero, Ty);
}
Value *Neg;
if (match(&I,
m_c_And(m_CombineAnd(m_Value(Neg),
m_OneUse(m_Neg(m_And(m_Value(), m_One())))),
m_Value(Y)))) {
Value *Cmp = Builder.CreateIsNull(Neg);
return SelectInst::Create(Cmp, ConstantInt::getNullValue(Ty), Y);
}
const APInt *C;
if (match(Op1, m_APInt(C))) {
const APInt *XorC;
if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) {
Constant *NewC = ConstantInt::get(Ty, *C & *XorC);
Value *And = Builder.CreateAnd(X, Op1);
And->takeName(Op0);
return BinaryOperator::CreateXor(And, NewC);
}
const APInt *OrC;
if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) {
APInt Together = *C & *OrC;
Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C));
And->takeName(Op0);
return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together));
}
unsigned Width = Ty->getScalarSizeInBits();
const APInt *ShiftC;
if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC))))) &&
ShiftC->ult(Width)) {
if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) {
Value *Sext = Builder.CreateSExt(X, Ty);
Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width));
return BinaryOperator::CreateLShr(Sext, ShAmtC);
}
}
if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) &&
C->isMask(Width - ShiftC->getZExtValue()))
return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC));
const APInt *AddC;
if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) {
unsigned Ctlz = C->countLeadingZeros();
APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz));
if ((*AddC & LowMask).isZero())
return BinaryOperator::CreateAnd(X, Op1);
if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) {
assert((*C & *AddC) != 0 && "Expected common bit");
Value *NewAnd = Builder.CreateAnd(X, Op1);
return BinaryOperator::CreateXor(NewAnd, Op1);
}
}
auto isNarrowableBinOpcode = [](BinaryOperator *B) {
switch (B->getOpcode()) {
case Instruction::Xor:
case Instruction::Or:
case Instruction::Mul:
case Instruction::Add:
case Instruction::Sub:
return true;
default:
return false;
}
};
BinaryOperator *BO;
if (match(Op0, m_OneUse(m_BinOp(BO))) && isNarrowableBinOpcode(BO)) {
Instruction::BinaryOps BOpcode = BO->getOpcode();
Value *X;
const APInt *C1;
if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) &&
C->isIntN(X->getType()->getScalarSizeInBits())) {
unsigned XWidth = X->getType()->getScalarSizeInBits();
Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth));
Value *BinOp = isa<ZExtInst>(BO->getOperand(0))
? Builder.CreateBinOp(BOpcode, X, TruncC1)
: Builder.CreateBinOp(BOpcode, TruncC1, X);
Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth));
Value *And = Builder.CreateAnd(BinOp, TruncC);
return new ZExtInst(And, Ty);
}
if (isa<Instruction>(BO->getOperand(0)) &&
match(BO->getOperand(0), m_OneUse(m_ZExt(m_Value(X)))) &&
C->isMask(X->getType()->getScalarSizeInBits())) {
Y = BO->getOperand(1);
Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
Value *NewBO =
Builder.CreateBinOp(BOpcode, X, TrY, BO->getName() + ".narrow");
return new ZExtInst(NewBO, Ty);
}
if (isa<Instruction>(BO->getOperand(1)) &&
match(BO->getOperand(1), m_OneUse(m_ZExt(m_Value(X)))) &&
C->isMask(X->getType()->getScalarSizeInBits())) {
Y = BO->getOperand(0);
Value *TrY = Builder.CreateTrunc(Y, X->getType(), Y->getName() + ".tr");
Value *NewBO =
Builder.CreateBinOp(BOpcode, TrY, X, BO->getName() + ".narrow");
return new ZExtInst(NewBO, Ty);
}
}
if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) ||
match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
APInt NotAndMask(~(*C));
BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode();
if (MaskedValueIsZero(X, NotAndMask, 0, &I)) {
Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked");
return BinaryOperator::Create(BinOp, X, NewRHS);
}
if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) {
Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked");
return BinaryOperator::Create(BinOp, NewLHS, Y);
}
}
if (C->isPowerOf2() &&
match(Op0, m_OneUse(m_LogicalShift(m_Power2(ShiftC), m_Value(X))))) {
int Log2ShiftC = ShiftC->exactLogBase2();
int Log2C = C->exactLogBase2();
bool IsShiftLeft =
cast<BinaryOperator>(Op0)->getOpcode() == Instruction::Shl;
int BitNum = IsShiftLeft ? Log2C - Log2ShiftC : Log2ShiftC - Log2C;
assert(BitNum >= 0 && "Expected demanded bits to handle impossible mask");
Value *Cmp = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, BitNum));
return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C),
ConstantInt::getNullValue(Ty));
}
Constant *C1, *C2;
const APInt *C3 = C;
Value *X;
if (C3->isPowerOf2()) {
Constant *Log2C3 = ConstantInt::get(Ty, C3->countTrailingZeros());
if (match(Op0, m_OneUse(m_LShr(m_Shl(m_ImmConstant(C1), m_Value(X)),
m_ImmConstant(C2)))) &&
match(C1, m_Power2())) {
Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
Constant *LshrC = ConstantExpr::getAdd(C2, Log2C3);
KnownBits KnownLShrc = computeKnownBits(LshrC, 0, nullptr);
if (KnownLShrc.getMaxValue().ult(Width)) {
Constant *CmpC = ConstantExpr::getSub(LshrC, Log2C1);
Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
ConstantInt::getNullValue(Ty));
}
}
if (match(Op0, m_OneUse(m_Shl(m_LShr(m_ImmConstant(C1), m_Value(X)),
m_ImmConstant(C2)))) &&
match(C1, m_Power2())) {
Constant *Log2C1 = ConstantExpr::getExactLogBase2(C1);
Constant *Cmp =
ConstantExpr::getCompare(ICmpInst::ICMP_ULT, Log2C3, C2);
if (Cmp->isZeroValue()) {
Constant *ShlC = ConstantExpr::getAdd(C2, Log2C1);
Constant *CmpC = ConstantExpr::getSub(ShlC, Log2C3);
Value *Cmp = Builder.CreateICmpEQ(X, CmpC);
return SelectInst::Create(Cmp, ConstantInt::get(Ty, *C3),
ConstantInt::getNullValue(Ty));
}
}
}
}
if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))),
m_SignMask())) &&
match(Y, m_SpecificInt_ICMP(
ICmpInst::Predicate::ICMP_EQ,
APInt(Ty->getScalarSizeInBits(),
Ty->getScalarSizeInBits() -
X->getType()->getScalarSizeInBits())))) {
auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext");
auto *SanitizedSignMask = cast<Constant>(Op1);
SanitizedSignMask = Constant::replaceUndefsWith(
SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType()));
SanitizedSignMask =
Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y));
return BinaryOperator::CreateAnd(SExt, SanitizedSignMask);
}
if (Instruction *Z = narrowMaskedBinOp(I))
return Z;
if (I.getType()->isIntOrIntVectorTy(1)) {
if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
if (auto *I =
foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, true))
return I;
}
if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
if (auto *I =
foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, true))
return I;
}
}
if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
return FoldedLogic;
if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
return DeMorgan;
{
Value *A, *B, *C;
if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B)))))
return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B));
if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B)))))
return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B));
if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B)))))
return BinaryOperator::CreateAnd(Op0, B);
if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B)))))
return BinaryOperator::CreateAnd(Op1, B);
if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C));
if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse()))
return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C));
if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(A, B);
if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
}
{
ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
if (LHS && RHS)
if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, true))
return replaceInstUsesWith(I, Res);
if (LHS && match(Op1, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
bool IsLogical = isa<SelectInst>(Op1);
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res =
foldAndOrOfICmps(LHS, Cmp, I, true, IsLogical))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalAnd(Res, Y)
: Builder.CreateAnd(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, true,
false))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalAnd(X, Res)
: Builder.CreateAnd(X, Res));
}
if (RHS && match(Op0, m_OneUse(m_LogicalAnd(m_Value(X), m_Value(Y))))) {
bool IsLogical = isa<SelectInst>(Op0);
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res =
foldAndOrOfICmps(Cmp, RHS, I, true, IsLogical))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalAnd(Res, Y)
: Builder.CreateAnd(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, true,
false))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalAnd(X, Res)
: Builder.CreateAnd(X, Res));
}
}
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
if (Value *Res = foldLogicOfFCmps(LHS, RHS, true))
return replaceInstUsesWith(I, Res);
if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
return FoldedFCmps;
if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
return CastedAnd;
if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
return Sel;
Value *A;
if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
A->getType()->isIntOrIntVectorTy(1))
return SelectInst::Create(A, Op1, Constant::getNullValue(Ty));
if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
A->getType()->isIntOrIntVectorTy(1))
return SelectInst::Create(A, Op0, Constant::getNullValue(Ty));
unsigned FullShift = Ty->getScalarSizeInBits() - 1;
if (match(&I, m_c_And(m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))),
m_Value(Y)))) {
Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
return SelectInst::Create(IsNeg, Y, ConstantInt::getNullValue(Ty));
}
if (match(&I, m_c_And(m_OneUse(m_Not(
m_AShr(m_Value(X), m_SpecificInt(FullShift)))),
m_Value(Y)))) {
Value *IsNeg = Builder.CreateIsNeg(X, "isneg");
return SelectInst::Create(IsNeg, ConstantInt::getNullValue(Ty), Y);
}
if (sinkNotIntoOtherHandOfAndOrOr(I))
return &I;
PHINode *PN = nullptr;
Value *Start = nullptr, *Step = nullptr;
if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step));
return nullptr;
}
Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I,
bool MatchBSwaps,
bool MatchBitReversals) {
SmallVector<Instruction *, 4> Insts;
if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals,
Insts))
return nullptr;
Instruction *LastInst = Insts.pop_back_val();
LastInst->removeFromParent();
for (auto *Inst : Insts)
Worklist.push(Inst);
return LastInst;
}
static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) {
unsigned Width = Or.getType()->getScalarSizeInBits();
BinaryOperator *Or0, *Or1;
if (!match(Or.getOperand(0), m_BinOp(Or0)) ||
!match(Or.getOperand(1), m_BinOp(Or1)))
return nullptr;
Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1;
if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) ||
!match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) ||
Or0->getOpcode() == Or1->getOpcode())
return nullptr;
if (Or0->getOpcode() == BinaryOperator::LShr) {
std::swap(Or0, Or1);
std::swap(ShVal0, ShVal1);
std::swap(ShAmt0, ShAmt1);
}
assert(Or0->getOpcode() == BinaryOperator::Shl &&
Or1->getOpcode() == BinaryOperator::LShr &&
"Illegal or(shift,shift) pair");
auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * {
const APInt *LI, *RI;
if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI)))
if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width)
return ConstantInt::get(L->getType(), *LI);
Constant *LC, *RC;
if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) &&
match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) &&
match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width)))
return ConstantExpr::mergeUndefsWith(LC, RC);
if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) {
KnownBits KnownL = IC.computeKnownBits(L, 0, &Or);
return KnownL.getMaxValue().ult(Width) ? L : nullptr;
}
if (ShVal0 != ShVal1)
return nullptr;
if (!isPowerOf2_32(Width))
return nullptr;
Value *X;
unsigned Mask = Width - 1;
if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) &&
match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))
return X;
if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))),
m_SpecificInt(Mask))))
return L;
if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) &&
match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))))
return L;
return nullptr;
};
Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width);
bool IsFshl = true; if (!ShAmt) {
ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width);
IsFshl = false; }
if (!ShAmt)
return nullptr;
Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType());
return CallInst::Create(F, {ShVal0, ShVal1, ShAmt});
}
static Instruction *matchOrConcat(Instruction &Or,
InstCombiner::BuilderTy &Builder) {
assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'");
Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1);
Type *Ty = Or.getType();
unsigned Width = Ty->getScalarSizeInBits();
if ((Width & 1) != 0)
return nullptr;
unsigned HalfWidth = Width / 2;
if (!isa<ZExtInst>(Op0))
std::swap(Op0, Op1);
Value *LowerSrc, *ShlVal, *UpperSrc;
const APInt *C;
if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) ||
!match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) ||
!match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc)))))
return nullptr;
if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() ||
LowerSrc->getType()->getScalarSizeInBits() != HalfWidth)
return nullptr;
auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) {
Value *NewLower = Builder.CreateZExt(Lo, Ty);
Value *NewUpper = Builder.CreateZExt(Hi, Ty);
NewUpper = Builder.CreateShl(NewUpper, HalfWidth);
Value *BinOp = Builder.CreateOr(NewLower, NewUpper);
Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty);
return Builder.CreateCall(F, BinOp);
};
Value *LowerBSwap, *UpperBSwap;
if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) &&
match(UpperSrc, m_BSwap(m_Value(UpperBSwap))))
return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap);
Value *LowerBRev, *UpperBRev;
if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) &&
match(UpperSrc, m_BitReverse(m_Value(UpperBRev))))
return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev);
return nullptr;
}
static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements();
for (unsigned i = 0; i != NumElts; ++i) {
Constant *EltC1 = C1->getAggregateElement(i);
Constant *EltC2 = C2->getAggregateElement(i);
if (!EltC1 || !EltC2)
return false;
if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
(match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
return false;
}
return true;
}
Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B) {
Type *Ty = A->getType();
if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy())
return nullptr;
if (match(B, m_Not(m_Specific(A)))) {
if (Ty->isIntOrIntVectorTy(1))
return A;
A = peekThroughBitcast(A);
if (A->getType()->isIntOrIntVectorTy()) {
unsigned NumSignBits = ComputeNumSignBits(A);
if (NumSignBits == A->getType()->getScalarSizeInBits() &&
NumSignBits <= Ty->getScalarSizeInBits())
return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType()));
}
return nullptr;
}
Constant *AConst, *BConst;
if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst)))
if (AConst == ConstantExpr::getNot(BConst) &&
ComputeNumSignBits(A) == Ty->getScalarSizeInBits())
return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty));
Value *Cond;
Value *NotB;
if (match(A, m_SExt(m_Value(Cond))) &&
Cond->getType()->isIntOrIntVectorTy(1)) {
if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
return Cond;
if (match(B, m_OneUse(m_Not(m_Value(NotB))))) {
NotB = peekThroughBitcast(NotB, true);
if (match(NotB, m_SExt(m_Specific(Cond))))
return Cond;
}
}
if (!Ty->isVectorTy())
return nullptr;
if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) &&
match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) &&
Cond->getType()->isIntOrIntVectorTy(1) &&
areInverseVectorBitmasks(AConst, BConst)) {
AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty));
return Builder.CreateXor(Cond, AConst);
}
return nullptr;
}
Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B,
Value *D) {
Type *OrigType = A->getType();
A = peekThroughBitcast(A, true);
B = peekThroughBitcast(B, true);
if (Value *Cond = getSelectCondition(A, B)) {
Type *SelTy = A->getType();
if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) {
unsigned Elts = VecTy->getElementCount().getKnownMinValue();
unsigned SelEltSize = SelTy->getPrimitiveSizeInBits().getKnownMinSize();
Type *EltTy = Builder.getIntNTy(SelEltSize / Elts);
SelTy = VectorType::get(EltTy, VecTy->getElementCount());
}
Value *BitcastC = Builder.CreateBitCast(C, SelTy);
Value *BitcastD = Builder.CreateBitCast(D, SelTy);
Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
return Builder.CreateBitCast(Select, OrigType);
}
return nullptr;
}
Value *foldAndOrOfICmpEqZeroAndICmp(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
IRBuilderBase &Builder) {
ICmpInst::Predicate LPred =
IsAnd ? LHS->getInversePredicate() : LHS->getPredicate();
ICmpInst::Predicate RPred =
IsAnd ? RHS->getInversePredicate() : RHS->getPredicate();
Value *LHS0 = LHS->getOperand(0);
if (LPred != ICmpInst::ICMP_EQ || !match(LHS->getOperand(1), m_Zero()) ||
!LHS0->getType()->isIntOrIntVectorTy() ||
!(LHS->hasOneUse() || RHS->hasOneUse()))
return nullptr;
Value *Other;
if (RPred == ICmpInst::ICMP_ULT && RHS->getOperand(1) == LHS0)
Other = RHS->getOperand(0);
else if (RPred == ICmpInst::ICMP_UGT && RHS->getOperand(0) == LHS0)
Other = RHS->getOperand(1);
else
return nullptr;
return Builder.CreateICmp(
IsAnd ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE,
Builder.CreateAdd(LHS0, Constant::getAllOnesValue(LHS0->getType())),
Other);
}
Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
Instruction &I, bool IsAnd,
bool IsLogical) {
const SimplifyQuery Q = SQ.getWithInstruction(&I);
if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &I, IsAnd, IsLogical))
return V;
ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1);
const APInt *LHSC = nullptr, *RHSC = nullptr;
match(LHS1, m_APInt(LHSC));
match(RHS1, m_APInt(RHSC));
if (predicatesFoldable(PredL, PredR)) {
if (LHS0 == RHS1 && LHS1 == RHS0) {
PredL = ICmpInst::getSwappedPredicate(PredL);
std::swap(LHS0, LHS1);
}
if (LHS0 == RHS0 && LHS1 == RHS1) {
unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR)
: getICmpCode(PredL) | getICmpCode(PredR);
bool IsSigned = LHS->isSigned() || RHS->isSigned();
return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
}
}
if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, IsLogical, Builder))
return V;
if (!IsLogical) {
if (Value *V = foldAndOrOfICmpEqZeroAndICmp(LHS, RHS, IsAnd, Builder))
return V;
if (Value *V = foldAndOrOfICmpEqZeroAndICmp(RHS, LHS, IsAnd, Builder))
return V;
}
if (!IsLogical) {
if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, IsAnd, Builder, Q))
return V;
if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, IsAnd, Builder, Q))
return V;
}
if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder))
return V;
if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder))
return V;
if (!IsLogical) {
if (Value *V = simplifyRangeCheck(LHS, RHS, !IsAnd))
return V;
if (Value *V = simplifyRangeCheck(RHS, LHS, !IsAnd))
return V;
}
if (IsAnd && !IsLogical)
if (Value *V = foldSignedTruncationCheck(LHS, RHS, I, Builder))
return V;
if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder))
return V;
if (!IsLogical) {
if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder))
return X;
if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder))
return X;
}
if (Value *X = foldEqOfParts(LHS, RHS, IsAnd))
return X;
if (!IsLogical && PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) &&
LHS0->getType() == RHS0->getType()) {
Value *NewOr = Builder.CreateOr(LHS0, RHS0);
return Builder.CreateICmp(PredL, NewOr,
Constant::getNullValue(NewOr->getType()));
}
if (!LHSC || !RHSC)
return nullptr;
if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) &&
PredL == PredR && LHS->hasOneUse() && RHS->hasOneUse()) {
Value *V;
const APInt *AndC, *SmallC = nullptr, *BigC = nullptr;
if (match(RHS0, m_Trunc(m_Value(V))) &&
match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
SmallC = RHSC;
BigC = LHSC;
} else if (match(LHS0, m_Trunc(m_Value(V))) &&
match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) {
SmallC = LHSC;
BigC = RHSC;
}
if (SmallC && BigC) {
unsigned BigBitSize = BigC->getBitWidth();
unsigned SmallBitSize = SmallC->getBitWidth();
APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) {
Value *NewAnd = Builder.CreateAnd(V, Low | *AndC);
APInt N = SmallC->zext(BigBitSize) | *BigC;
Value *NewVal = ConstantInt::get(NewAnd->getType(), N);
return Builder.CreateICmp(PredL, NewAnd, NewVal);
}
}
}
bool TrueIfSignedL, TrueIfSignedR;
if (isSignBitCheck(PredL, *LHSC, TrueIfSignedL) &&
isSignBitCheck(PredR, *RHSC, TrueIfSignedR) &&
(RHS->hasOneUse() || LHS->hasOneUse())) {
Value *X, *Y;
if (IsAnd) {
if ((TrueIfSignedL && !TrueIfSignedR &&
match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
match(RHS0, m_c_And(m_Specific(X), m_Specific(Y)))) ||
(!TrueIfSignedL && TrueIfSignedR &&
match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y))))) {
Value *NewXor = Builder.CreateXor(X, Y);
return Builder.CreateIsNeg(NewXor);
}
} else {
if ((TrueIfSignedL && !TrueIfSignedR &&
match(LHS0, m_And(m_Value(X), m_Value(Y))) &&
match(RHS0, m_c_Or(m_Specific(X), m_Specific(Y)))) ||
(!TrueIfSignedL && TrueIfSignedR &&
match(LHS0, m_Or(m_Value(X), m_Value(Y))) &&
match(RHS0, m_c_And(m_Specific(X), m_Specific(Y))))) {
Value *NewXor = Builder.CreateXor(X, Y);
return Builder.CreateIsNotNeg(NewXor);
}
}
}
return foldAndOrOfICmpsUsingRanges(LHS, RHS, IsAnd);
}
Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) {
if (Value *V = simplifyOrInst(I.getOperand(0), I.getOperand(1),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
if (SimplifyDemandedInstructionBits(I))
return &I;
if (Instruction *Xor = foldOrToXor(I, Builder))
return Xor;
if (Instruction *X = foldComplexAndOrPatterns(I, Builder))
return X;
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
if (Value *V = SimplifyBSwap(I, Builder))
return replaceInstUsesWith(I, V);
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Type *Ty = I.getType();
if (Ty->isIntOrIntVectorTy(1)) {
if (auto *SI0 = dyn_cast<SelectInst>(Op0)) {
if (auto *I =
foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, false))
return I;
}
if (auto *SI1 = dyn_cast<SelectInst>(Op1)) {
if (auto *I =
foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, false))
return I;
}
}
if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
return FoldedLogic;
if (Instruction *BitOp = matchBSwapOrBitReverse(I, true,
true))
return BitOp;
if (Instruction *Funnel = matchFunnelShift(I, *this))
return Funnel;
if (Instruction *Concat = matchOrConcat(I, Builder))
return replaceInstUsesWith(I, Concat);
Value *X, *Y;
const APInt *CV;
if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) &&
!CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) {
Value *Or = Builder.CreateOr(X, Y);
return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV));
}
if (match(&I,
m_c_Or(m_OneUse(m_Mul(m_Value(X), m_Value(Y))), m_Deferred(X))) &&
haveNoCommonBitsSet(Op0, Op1, DL)) {
Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1));
return BinaryOperator::CreateMul(X, IncrementY);
}
Value *A, *B, *C, *D;
if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
match(Op1, m_And(m_Value(B), m_Value(D)))) {
const APInt *C0, *C1;
if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) {
Value *X;
if (*C0 == ~*C1) {
if (match(A, m_c_Or(m_Value(X), m_Specific(B))))
return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B);
if (match(B, m_c_Or(m_Specific(A), m_Value(X))))
return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A);
if (match(A, m_c_Xor(m_Value(X), m_Specific(B))))
return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B);
if (match(B, m_c_Xor(m_Specific(A), m_Value(X))))
return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A);
}
if ((*C0 & *C1).isZero()) {
if (match(A, m_c_Or(m_Value(X), m_Specific(B))) &&
MaskedValueIsZero(X, ~*C0, 0, &I)) {
Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
return BinaryOperator::CreateAnd(A, C01);
}
if (match(B, m_c_Or(m_Value(X), m_Specific(A))) &&
MaskedValueIsZero(X, ~*C1, 0, &I)) {
Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
return BinaryOperator::CreateAnd(B, C01);
}
const APInt *C2, *C3;
if (match(A, m_Or(m_Value(X), m_APInt(C2))) &&
match(B, m_Or(m_Specific(X), m_APInt(C3))) &&
(*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) {
Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield");
Constant *C01 = ConstantInt::get(Ty, *C0 | *C1);
return BinaryOperator::CreateAnd(Or, C01);
}
}
}
if (Op0->hasOneUse() || Op1->hasOneUse()) {
if (Value *V = matchSelectFromAndOr(A, C, B, D))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(A, C, D, B))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(C, A, B, D))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(C, A, D, B))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(B, D, A, C))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(B, D, C, A))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(D, B, A, C))
return replaceInstUsesWith(I, V);
if (Value *V = matchSelectFromAndOr(D, B, C, A))
return replaceInstUsesWith(I, V);
}
}
if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
return BinaryOperator::CreateOr(Op0, C);
if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
return BinaryOperator::CreateOr(Op1, C);
if (match(Op0, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op1)), m_Value(C))))
return BinaryOperator::CreateOr(C, Op1);
if (match(Op1, m_c_Xor(m_c_And(m_Value(A), m_Specific(Op0)), m_Value(C))))
return BinaryOperator::CreateOr(Op0, C);
if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C));
if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
return DeMorgan;
bool SwappedForXor = false;
if (match(Op0, m_Xor(m_Value(), m_Value()))) {
std::swap(Op0, Op1);
SwappedForXor = true;
}
if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
if (Op0 == A || Op0 == B)
return BinaryOperator::CreateOr(A, B);
if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
match(Op0, m_And(m_Specific(B), m_Specific(A))))
return BinaryOperator::CreateOr(A, B);
if ((Op0->hasOneUse() || Op1->hasOneUse()) &&
(match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B)))))
return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
Value *Not = Builder.CreateNot(B, B->getName() + ".not");
return BinaryOperator::CreateOr(Not, Op0);
}
if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
Value *Not = Builder.CreateNot(A, A->getName() + ".not");
return BinaryOperator::CreateOr(Not, Op0);
}
}
if (match(Op1, m_Not(m_Value(A))))
if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
B->getOpcode() == Instruction::Xor)) {
Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
B->getOperand(0);
Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not");
return BinaryOperator::CreateOr(Not, Op0);
}
if (SwappedForXor)
std::swap(Op0, Op1);
{
ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
if (LHS && RHS)
if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, false))
return replaceInstUsesWith(I, Res);
Value *X, *Y;
if (LHS && match(Op1, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
bool IsLogical = isa<SelectInst>(Op1);
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res =
foldAndOrOfICmps(LHS, Cmp, I, false, IsLogical))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalOr(Res, Y)
: Builder.CreateOr(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, false,
false))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalOr(X, Res)
: Builder.CreateOr(X, Res));
}
if (RHS && match(Op0, m_OneUse(m_LogicalOr(m_Value(X), m_Value(Y))))) {
bool IsLogical = isa<SelectInst>(Op0);
if (auto *Cmp = dyn_cast<ICmpInst>(X))
if (Value *Res =
foldAndOrOfICmps(Cmp, RHS, I, false, IsLogical))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalOr(Res, Y)
: Builder.CreateOr(Res, Y));
if (auto *Cmp = dyn_cast<ICmpInst>(Y))
if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, false,
false))
return replaceInstUsesWith(I, IsLogical
? Builder.CreateLogicalOr(X, Res)
: Builder.CreateOr(X, Res));
}
}
if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
if (Value *Res = foldLogicOfFCmps(LHS, RHS, false))
return replaceInstUsesWith(I, Res);
if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder))
return FoldedFCmps;
if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
return CastedOr;
if (Instruction *Sel = foldBinopOfSextBoolToSelect(I))
return Sel;
if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
A->getType()->isIntOrIntVectorTy(1))
return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op1);
if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
A->getType()->isIntOrIntVectorTy(1))
return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op0);
ConstantInt *CI;
if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) &&
match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) {
Value *Inner = Builder.CreateOr(A, Op1);
Inner->takeName(Op0);
return BinaryOperator::CreateOr(Inner, CI);
}
{
Value *X = nullptr, *Y = nullptr;
if (Op0->hasOneUse() && Op1->hasOneUse() &&
match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
Value *orTrue = Builder.CreateOr(A, C);
Value *orFalse = Builder.CreateOr(B, D);
return SelectInst::Create(X, orTrue, orFalse);
}
}
{
Value *X, *Y;
if (match(&I, m_c_Or(m_OneUse(m_AShr(
m_NSWSub(m_Value(Y), m_Value(X)),
m_SpecificInt(Ty->getScalarSizeInBits() - 1))),
m_Deferred(X)))) {
Value *NewICmpInst = Builder.CreateICmpSGT(X, Y);
Value *AllOnes = ConstantInt::getAllOnesValue(Ty);
return SelectInst::Create(NewICmpInst, AllOnes, X);
}
}
if (Instruction *V =
canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
return V;
CmpInst::Predicate Pred;
Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv;
if (match(&I,
m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)),
m_Value(Ov)),
m_CombineAnd(m_ICmp(Pred,
m_CombineAnd(m_ExtractValue<0>(
m_Deferred(UMulWithOv)),
m_Value(Mul)),
m_ZeroInt()),
m_Value(MulIsNotZero)))) &&
(Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) &&
Pred == CmpInst::ICMP_NE) {
Value *A, *B;
if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>(
m_Value(A), m_Value(B)))) {
Value *NotNullA = Builder.CreateIsNotNull(A);
Value *NotNullB = Builder.CreateIsNotNull(B);
return BinaryOperator::CreateAnd(NotNullA, NotNullB);
}
}
if (sinkNotIntoOtherHandOfAndOrOr(I))
return &I;
if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()),
m_Shl(m_One(), m_Deferred(X)))) &&
match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) {
Value *Sub = Builder.CreateSub(
ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X);
return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub);
}
PHINode *PN = nullptr;
Value *Start = nullptr, *Step = nullptr;
if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN))
return replaceInstUsesWith(I, Builder.CreateOr(Start, Step));
if (match(&I, m_c_Or(m_OneUse(m_And(m_Value(A), m_Value(B))),
m_OneUse(m_Or(m_Value(C), m_Value(D)))))) {
if (match(D, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
match(D, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
return BinaryOperator::CreateOr(
C, Builder.CreateOr(D, Builder.CreateAnd(A, B)));
if (match(C, m_OneUse(m_c_And(m_Specific(A), m_Value()))) ||
match(C, m_OneUse(m_c_And(m_Specific(B), m_Value()))))
return BinaryOperator::CreateOr(
Builder.CreateOr(C, Builder.CreateAnd(A, B)), D);
}
return nullptr;
}
static Instruction *foldXorToXor(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
assert(I.getOpcode() == Instruction::Xor);
Value *Op0 = I.getOperand(0);
Value *Op1 = I.getOperand(1);
Value *A, *B;
if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)),
m_c_Or(m_Deferred(A), m_Deferred(B)))))
return BinaryOperator::CreateXor(A, B);
if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))),
m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B)))))
return BinaryOperator::CreateXor(A, B);
if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))),
m_c_And(m_Not(m_Deferred(A)), m_Deferred(B)))))
return BinaryOperator::CreateXor(A, B);
if (!Op0->hasOneUse() && !Op1->hasOneUse())
return nullptr;
if ((match(Op0, m_Or(m_Value(A), m_Value(B))) &&
match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) ||
(match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))))
return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
return nullptr;
}
Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS,
BinaryOperator &I) {
assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS &&
I.getOperand(1) == RHS && "Should be 'xor' with these operands");
ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
if (predicatesFoldable(PredL, PredR)) {
if (LHS0 == RHS1 && LHS1 == RHS0) {
std::swap(LHS0, LHS1);
PredL = ICmpInst::getSwappedPredicate(PredL);
}
if (LHS0 == RHS0 && LHS1 == RHS1) {
unsigned Code = getICmpCode(PredL) ^ getICmpCode(PredR);
bool IsSigned = LHS->isSigned() || RHS->isSigned();
return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder);
}
}
const APInt *LC, *RC;
if (match(LHS1, m_APInt(LC)) && match(RHS1, m_APInt(RC)) &&
LHS0->getType() == RHS0->getType() &&
LHS0->getType()->isIntOrIntVectorTy() &&
(LHS->hasOneUse() || RHS->hasOneUse())) {
bool TrueIfSignedL, TrueIfSignedR;
if (isSignBitCheck(PredL, *LC, TrueIfSignedL) &&
isSignBitCheck(PredR, *RC, TrueIfSignedR)) {
Value *XorLR = Builder.CreateXor(LHS0, RHS0);
return TrueIfSignedL == TrueIfSignedR ? Builder.CreateIsNeg(XorLR) :
Builder.CreateIsNotNeg(XorLR);
}
const APInt *C1, *C2;
if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_APInt(C1)) &&
PredR == CmpInst::ICMP_SLT && match(RHS1, m_APInt(C2))) ||
(PredL == CmpInst::ICMP_SLT && match(LHS1, m_APInt(C2)) &&
PredR == CmpInst::ICMP_SGT && match(RHS1, m_APInt(C1))))
if (LHS0 == RHS0 && *C1 + 2 == *C2 &&
(C1->isNegative() || C2->isNonNegative()))
return Builder.CreateICmpNE(LHS0,
ConstantInt::get(LHS0->getType(), *C1 + 1));
}
if (Value *OrICmp = simplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
if (Value *AndICmp = simplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
ICmpInst *X = nullptr, *Y = nullptr;
if (OrICmp == LHS && AndICmp == RHS) {
X = LHS;
Y = RHS;
}
if (OrICmp == RHS && AndICmp == LHS) {
X = RHS;
Y = LHS;
}
if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) {
Y->setPredicate(Y->getInversePredicate());
if (!Y->hasOneUse()) {
BuilderTy::InsertPointGuard Guard(Builder);
Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator()));
Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Worklist.pushUsersToWorkList(*Y);
Y->replaceUsesWithIf(NotY,
[NotY](Use &U) { return U.getUser() != NotY; });
}
return Builder.CreateAnd(LHS, RHS);
}
}
}
return nullptr;
}
static Instruction *visitMaskedMerge(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *B, *X, *D;
Value *M;
if (!match(&I, m_c_Xor(m_Value(B),
m_OneUse(m_c_And(
m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)),
m_Value(D)),
m_Value(M))))))
return nullptr;
Value *NotM;
if (match(M, m_Not(m_Value(NotM)))) {
Value *NewA = Builder.CreateAnd(D, NotM);
return BinaryOperator::CreateXor(NewA, X);
}
Constant *C;
if (D->hasOneUse() && match(M, m_Constant(C))) {
Type *EltTy = C->getType()->getScalarType();
C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
Value *LHS = Builder.CreateAnd(X, C);
Value *NotC = Builder.CreateNot(C);
Value *RHS = Builder.CreateAnd(B, NotC);
return BinaryOperator::CreateOr(LHS, RHS);
}
return nullptr;
}
static Instruction *sinkNotIntoXor(BinaryOperator &I,
InstCombiner::BuilderTy &Builder) {
Value *X, *Y;
if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y))))))
return nullptr;
if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) {
} else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) {
std::swap(X, Y);
} else
return nullptr;
Value *NotX = Builder.CreateNot(X, X->getName() + ".not");
return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan");
}
static Instruction *canonicalizeAbs(BinaryOperator &Xor,
InstCombiner::BuilderTy &Builder) {
assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction.");
Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1);
if (Op0->hasNUses(2))
std::swap(Op0, Op1);
Type *Ty = Xor.getType();
Value *A;
const APInt *ShAmt;
if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) {
Value *IsNeg = Builder.CreateIsNeg(A);
auto *Add = cast<BinaryOperator>(Op0);
Value *NegA = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(),
Add->hasNoSignedWrap());
return SelectInst::Create(IsNeg, NegA, A);
}
return nullptr;
}
bool InstCombinerImpl::sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I) {
Instruction::BinaryOps NewOpc;
switch (I.getOpcode()) {
case Instruction::And:
NewOpc = Instruction::Or;
break;
case Instruction::Or:
NewOpc = Instruction::And;
break;
default:
return false;
};
Value *X, *Y;
if (!match(&I, m_c_BinOp(m_Not(m_Value(X)), m_Value(Y))))
return false;
if (!InstCombiner::isFreeToInvert(Y, Y->hasOneUse()))
return false;
if (!InstCombiner::canFreelyInvertAllUsersOf(&I, nullptr))
return false;
Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
Value *NewBinOp =
BinaryOperator::Create(NewOpc, X, NotY, I.getName() + ".not");
Builder.Insert(NewBinOp);
replaceInstUsesWith(I, NewBinOp);
freelyInvertAllUsersOf(NewBinOp);
return true;
}
Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
Value *NotOp;
if (!match(&I, m_Not(m_Value(NotOp))))
return nullptr;
Type *Ty = I.getType();
Value *X, *Y;
if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) {
Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
return BinaryOperator::CreateOr(X, NotY);
}
if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) {
Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY);
}
if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) {
Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
return BinaryOperator::CreateAnd(X, NotY);
}
if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) {
Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not");
return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty));
}
BinaryOperator *NotVal;
if (match(NotOp, m_BinOp(NotVal))) {
if (NotVal->getOpcode() == Instruction::And ||
NotVal->getOpcode() == Instruction::Or) {
if (isFreeToInvert(NotVal->getOperand(0),
NotVal->getOperand(0)->hasOneUse()) &&
isFreeToInvert(NotVal->getOperand(1),
NotVal->getOperand(1)->hasOneUse())) {
Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs");
Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs");
if (NotVal->getOpcode() == Instruction::And)
return BinaryOperator::CreateOr(NotX, NotY);
return BinaryOperator::CreateAnd(NotX, NotY);
}
}
if (match(NotVal,
m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) {
Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty));
Value *NotY = Builder.CreateNot(Y);
return BinaryOperator::CreateAnd(DecX, NotY);
}
if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
return BinaryOperator::CreateAShr(X, Y);
Constant *C;
if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) &&
match(C, m_Negative())) {
Type *EltTy = Ty->getScalarType();
C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy));
return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y);
}
if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) &&
match(C, m_NonNegative())) {
Type *EltTy = Ty->getScalarType();
C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy));
return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y);
}
if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C))))
return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X);
if (match(NotVal, m_Sub(m_Value(X), m_Value(Y))))
if (isa<Constant>(X) || NotVal->hasOneUse())
return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y);
if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y))))
return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y,
NotVal);
}
CmpInst::Predicate Pred;
if (match(NotOp, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred));
return replaceInstUsesWith(I, NotOp);
}
auto *II = dyn_cast<IntrinsicInst>(NotOp);
if (II && II->hasOneUse()) {
if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) &&
isFreeToInvert(X, X->hasOneUse()) &&
isFreeToInvert(Y, Y->hasOneUse())) {
Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
Value *NotX = Builder.CreateNot(X);
Value *NotY = Builder.CreateNot(Y);
Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY);
return replaceInstUsesWith(I, InvMaxMin);
}
if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) {
Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
Value *NotY = Builder.CreateNot(Y);
Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY);
return replaceInstUsesWith(I, InvMaxMin);
}
}
if (NotOp->hasOneUse()) {
if (auto *Sel = dyn_cast<SelectInst>(NotOp)) {
Value *TV = Sel->getTrueValue();
Value *FV = Sel->getFalseValue();
auto *CmpT = dyn_cast<CmpInst>(TV);
auto *CmpF = dyn_cast<CmpInst>(FV);
bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV);
bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV);
if (InvertibleT && InvertibleF) {
if (CmpT)
CmpT->setPredicate(CmpT->getInversePredicate());
else
Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV)));
if (CmpF)
CmpF->setPredicate(CmpF->getInversePredicate());
else
Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV)));
return replaceInstUsesWith(I, Sel);
}
}
}
if (Instruction *NewXor = sinkNotIntoXor(I, Builder))
return NewXor;
return nullptr;
}
Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
if (Value *V = simplifyXorInst(I.getOperand(0), I.getOperand(1),
SQ.getWithInstruction(&I)))
return replaceInstUsesWith(I, V);
if (SimplifyAssociativeOrCommutative(I))
return &I;
if (Instruction *X = foldVectorBinop(I))
return X;
if (Instruction *Phi = foldBinopWithPhiOperands(I))
return Phi;
if (Instruction *NewXor = foldXorToXor(I, Builder))
return NewXor;
if (Value *V = SimplifyUsingDistributiveLaws(I))
return replaceInstUsesWith(I, V);
if (SimplifyDemandedInstructionBits(I))
return &I;
if (Value *V = SimplifyBSwap(I, Builder))
return replaceInstUsesWith(I, V);
if (Instruction *R = foldNot(I))
return R;
Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Value *M;
if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()),
m_c_And(m_Deferred(M), m_Value()))))
return BinaryOperator::CreateOr(Op0, Op1);
if (Instruction *Xor = visitMaskedMerge(I, Builder))
return Xor;
Value *X, *Y;
Constant *C1;
if (match(Op1, m_Constant(C1))) {
Constant *C2;
if (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C2)))) &&
match(C1, m_ImmConstant())) {
C2 = Constant::replaceUndefsWith(
C2, Constant::getAllOnesValue(C2->getType()->getScalarType()));
Value *And = Builder.CreateAnd(
X, Constant::mergeUndefsWith(ConstantExpr::getNot(C2), C1));
return BinaryOperator::CreateXor(
And, Constant::mergeUndefsWith(ConstantExpr::getXor(C1, C2), C1));
}
if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) {
Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2));
return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1));
}
if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) {
Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2));
return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1));
}
const APInt *CA;
if (match(Op0, m_OneUse(m_TruncOrSelf(
m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) &&
*CA == X->getType()->getScalarSizeInBits() - 1 &&
!match(C1, m_AllOnes())) {
assert(!C1->isZeroValue() && "Unexpected xor with 0");
Value *IsNotNeg = Builder.CreateIsNotNeg(X);
return SelectInst::Create(IsNotNeg, Op1, Builder.CreateNot(Op1));
}
}
Type *Ty = I.getType();
{
const APInt *RHSC;
if (match(Op1, m_APInt(RHSC))) {
Value *X;
const APInt *C;
if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X))))
return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X);
if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C))))
return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC));
if (match(Op0, m_Or(m_Value(X), m_APInt(C))) &&
MaskedValueIsZero(X, *C, 0, &I))
return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC));
if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) &&
*RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) {
Value *NotX = Builder.CreateNot(X);
return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C));
}
if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) &&
*RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) {
Value *NotX = Builder.CreateNot(X);
return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C));
}
}
}
{
Value *X;
ConstantInt *C1, *C2, *C3;
if (match(Op1, m_ConstantInt(C3)) &&
match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)),
m_ConstantInt(C2))) &&
Op0->hasOneUse()) {
APInt FoldConst = C1->getValue().lshr(C2->getValue());
FoldConst ^= C3->getValue();
auto *Opnd0 = Builder.CreateLShr(X, C2);
Opnd0->takeName(Op0);
return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst));
}
}
if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I))
return FoldedLogic;
if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0)))))
return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0));
if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1)))))
return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1));
if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0)))))
return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X));
if (!match(Op1, m_Constant()) &&
match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1)))))
return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X));
Value *A, *B, *C;
if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
m_OneUse(m_c_Or(m_Deferred(A), m_Value(C))))))
return BinaryOperator::CreateXor(
Builder.CreateAnd(Builder.CreateNot(A), C), B);
if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))),
m_OneUse(m_c_Or(m_Deferred(B), m_Value(C))))))
return BinaryOperator::CreateXor(
Builder.CreateAnd(Builder.CreateNot(B), C), A);
if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateOr(A, B);
if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
return BinaryOperator::CreateOr(A, B);
if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
match(Op1, m_Not(m_Specific(A))))
return BinaryOperator::CreateNot(Builder.CreateAnd(A, B));
if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A))))
return BinaryOperator::CreateOr(A, B);
if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B)))))
return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B));
if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B)))))
return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B));
Value *D;
if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) &&
match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) {
if (B == C || B == D)
std::swap(A, B);
if (A == C)
std::swap(C, D);
if (A == D) {
Value *NotA = Builder.CreateNot(A);
return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA);
}
}
if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
if (Value *V = foldXorOfICmps(LHS, RHS, I))
return replaceInstUsesWith(I, V);
if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
return CastedXor;
if (Instruction *Abs = canonicalizeAbs(I, Builder))
return Abs;
if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X),
m_Unless(m_ConstantExpr())),
m_ImmConstant(C1))),
m_Value(Y))))
return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1);
return nullptr;
}