#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/CaptureTracking.h"
#include "llvm/Analysis/CmpInstAnalysis.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/InstSimplifyFolder.h"
#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/OverflowInstAnalysis.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/KnownBits.h"
#include <algorithm>
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "instsimplify"
enum { RecursionLimit = 3 };
STATISTIC(NumExpand, "Number of expansions");
STATISTIC(NumReassoc, "Number of reassociations");
static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
unsigned);
static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
const SimplifyQuery &, unsigned);
static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
unsigned);
static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
const SimplifyQuery &, unsigned);
static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
unsigned);
static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
const SimplifyQuery &Q, unsigned MaxRecurse);
static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
unsigned);
static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
unsigned);
static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>, bool,
const SimplifyQuery &, unsigned);
static Value *simplifySelectInst(Value *, Value *, Value *,
const SimplifyQuery &, unsigned);
static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
Value *FalseVal) {
BinaryOperator::BinaryOps BinOpCode;
if (auto *BO = dyn_cast<BinaryOperator>(Cond))
BinOpCode = BO->getOpcode();
else
return nullptr;
CmpInst::Predicate ExpectedPred, Pred1, Pred2;
if (BinOpCode == BinaryOperator::Or) {
ExpectedPred = ICmpInst::ICMP_NE;
} else if (BinOpCode == BinaryOperator::And) {
ExpectedPred = ICmpInst::ICMP_EQ;
} else
return nullptr;
Value *X, *Y;
if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
m_Specific(FalseVal)),
m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
Pred1 != Pred2 || Pred1 != ExpectedPred)
return nullptr;
if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
return nullptr;
}
static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
Value *RHS) {
CmpInst *Cmp = dyn_cast<CmpInst>(V);
if (!Cmp)
return false;
CmpInst::Predicate CPred = Cmp->getPredicate();
Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
if (CPred == Pred && CLHS == LHS && CRHS == RHS)
return true;
return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
CRHS == LHS;
}
static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, Value *Cond,
const SimplifyQuery &Q, unsigned MaxRecurse,
Constant *TrueOrFalse) {
Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
if (SimplifiedCmp == Cond) {
return TrueOrFalse;
} else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
return TrueOrFalse;
}
return SimplifiedCmp;
}
static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, Value *Cond,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
getTrue(Cond->getType()));
}
static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, Value *Cond,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
getFalse(Cond->getType()));
}
static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
Value *Cond,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
return V;
if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
return V;
if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
if (Value *V = simplifyXorInst(
Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
return V;
return nullptr;
}
static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I)
return true;
if (!I->getParent() || !P->getParent() || !I->getFunction())
return false;
if (DT)
return DT->dominates(I, P);
if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
!isa<CallBrInst>(I))
return true;
return false;
}
static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
const SimplifyQuery &Q, unsigned MaxRecurse) {
auto *B = dyn_cast<BinaryOperator>(V);
if (!B || B->getOpcode() != OpcodeToExpand)
return nullptr;
Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
Value *L =
simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
if (!L)
return nullptr;
Value *R =
simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
if (!R)
return nullptr;
if ((L == B0 && R == B1) ||
(Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
++NumExpand;
return B;
}
Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
if (!S)
return nullptr;
++NumExpand;
return S;
}
static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
Value *R,
Instruction::BinaryOps OpcodeToExpand,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (!MaxRecurse--)
return nullptr;
if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
return V;
if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
return V;
return nullptr;
}
static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
Value *LHS, Value *RHS,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
if (!MaxRecurse--)
return nullptr;
BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
if (Op0 && Op0->getOpcode() == Opcode) {
Value *A = Op0->getOperand(0);
Value *B = Op0->getOperand(1);
Value *C = RHS;
if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
if (V == B)
return LHS;
if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
++NumReassoc;
return W;
}
}
}
if (Op1 && Op1->getOpcode() == Opcode) {
Value *A = LHS;
Value *B = Op1->getOperand(0);
Value *C = Op1->getOperand(1);
if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
if (V == B)
return RHS;
if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
++NumReassoc;
return W;
}
}
}
if (!Instruction::isCommutative(Opcode))
return nullptr;
if (Op0 && Op0->getOpcode() == Opcode) {
Value *A = Op0->getOperand(0);
Value *B = Op0->getOperand(1);
Value *C = RHS;
if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
if (V == A)
return LHS;
if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
++NumReassoc;
return W;
}
}
}
if (Op1 && Op1->getOpcode() == Opcode) {
Value *A = LHS;
Value *B = Op1->getOperand(0);
Value *C = Op1->getOperand(1);
if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
if (V == C)
return RHS;
if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
++NumReassoc;
return W;
}
}
}
return nullptr;
}
static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
Value *RHS, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (!MaxRecurse--)
return nullptr;
SelectInst *SI;
if (isa<SelectInst>(LHS)) {
SI = cast<SelectInst>(LHS);
} else {
assert(isa<SelectInst>(RHS) && "No select instruction operand!");
SI = cast<SelectInst>(RHS);
}
Value *TV;
Value *FV;
if (SI == LHS) {
TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
} else {
TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
}
if (TV == FV)
return TV;
if (TV && Q.isUndefValue(TV))
return FV;
if (FV && Q.isUndefValue(FV))
return TV;
if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
return SI;
if ((FV && !TV) || (TV && !FV)) {
Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
if (Simplified->getOperand(0) == UnsimplifiedLHS &&
Simplified->getOperand(1) == UnsimplifiedRHS)
return Simplified;
if (Simplified->isCommutative() &&
Simplified->getOperand(1) == UnsimplifiedLHS &&
Simplified->getOperand(0) == UnsimplifiedRHS)
return Simplified;
}
}
return nullptr;
}
static Value *threadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (!MaxRecurse--)
return nullptr;
if (!isa<SelectInst>(LHS)) {
std::swap(LHS, RHS);
Pred = CmpInst::getSwappedPredicate(Pred);
}
assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
SelectInst *SI = cast<SelectInst>(LHS);
Value *Cond = SI->getCondition();
Value *TV = SI->getTrueValue();
Value *FV = SI->getFalseValue();
Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
if (!TCmp)
return nullptr;
Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
if (!FCmp)
return nullptr;
if (TCmp == FCmp)
return TCmp;
if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
return nullptr;
}
static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
Value *RHS, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (!MaxRecurse--)
return nullptr;
PHINode *PI;
if (isa<PHINode>(LHS)) {
PI = cast<PHINode>(LHS);
if (!valueDominatesPHI(RHS, PI, Q.DT))
return nullptr;
} else {
assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
PI = cast<PHINode>(RHS);
if (!valueDominatesPHI(LHS, PI, Q.DT))
return nullptr;
}
Value *CommonValue = nullptr;
for (Value *Incoming : PI->incoming_values()) {
if (Incoming == PI)
continue;
Value *V = PI == LHS ? simplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse)
: simplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
if (!V || (CommonValue && V != CommonValue))
return nullptr;
CommonValue = V;
}
return CommonValue;
}
static Value *threadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (!MaxRecurse--)
return nullptr;
if (!isa<PHINode>(LHS)) {
std::swap(LHS, RHS);
Pred = CmpInst::getSwappedPredicate(Pred);
}
assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
PHINode *PI = cast<PHINode>(LHS);
if (!valueDominatesPHI(RHS, PI, Q.DT))
return nullptr;
Value *CommonValue = nullptr;
for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
Value *Incoming = PI->getIncomingValue(u);
Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
if (Incoming == PI)
continue;
Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
MaxRecurse);
if (!V || (CommonValue && V != CommonValue))
return nullptr;
CommonValue = V;
}
return CommonValue;
}
static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
Value *&Op0, Value *&Op1,
const SimplifyQuery &Q) {
if (auto *CLHS = dyn_cast<Constant>(Op0)) {
if (auto *CRHS = dyn_cast<Constant>(Op1)) {
switch (Opcode) {
default:
break;
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
if (Q.CxtI != nullptr)
return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CxtI);
}
return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
}
if (Instruction::isCommutative(Opcode))
std::swap(Op0, Op1);
}
return nullptr;
}
static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op1))
return Op1;
if (Q.isUndefValue(Op1))
return Op1;
if (match(Op1, m_Zero()))
return Op0;
if (isKnownNegation(Op0, Op1))
return Constant::getNullValue(Op0->getType());
Value *Y = nullptr;
if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
return Y;
Type *Ty = Op0->getType();
if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
return Constant::getAllOnesValue(Ty);
if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
match(Op0, m_Xor(m_Value(Y), m_SignMask())))
return Y;
if (IsNUW && match(Op1, m_AllOnes()))
return Op1;
if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
return V;
if (Value *V =
simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
return V;
return nullptr;
}
Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
const SimplifyQuery &Query) {
return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
}
static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
bool AllowNonInbounds = false) {
assert(V->getType()->isPtrOrPtrVectorTy());
APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
}
static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
Value *RHS) {
APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
if (LHS != RHS)
return nullptr;
Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
return Res;
}
static Value *simplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
return PoisonValue::get(Op0->getType());
if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
return UndefValue::get(Op0->getType());
if (match(Op1, m_Zero()))
return Op0;
if (Op0 == Op1)
return Constant::getNullValue(Op0->getType());
if (match(Op0, m_Zero())) {
if (isNUW)
return Constant::getNullValue(Op0->getType());
KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (Known.Zero.isMaxSignedValue()) {
if (isNSW)
return Constant::getNullValue(Op0->getType());
return Op1;
}
}
Value *X = nullptr, *Y = nullptr, *Z = Op1;
if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
++NumReassoc;
return W;
}
if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
++NumReassoc;
return W;
}
}
X = Op0;
if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
++NumReassoc;
return W;
}
if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
++NumReassoc;
return W;
}
}
Z = Op0;
if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
++NumReassoc;
return W;
}
if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
match(Op1, m_Trunc(m_Value(Y))))
if (X->getType() == Y->getType())
if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
Q, MaxRecurse - 1))
return W;
if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
if (Constant *Result = computePointerDifference(Q.DL, X, Y))
return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
return V;
return nullptr;
}
Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
const SimplifyQuery &Q) {
return ::simplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
}
static Value *simplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op1))
return Op1;
if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
return Constant::getNullValue(Op0->getType());
if (match(Op1, m_One()))
return Op0;
Value *X = nullptr;
if (Q.IIQ.UseInstrInfo &&
(match(Op0,
m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) return X;
if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
return V;
if (Value *V =
simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
Instruction::Add, Q, MaxRecurse))
return V;
if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
if (Value *V =
threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
return V;
if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
if (Value *V =
threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
return V;
return nullptr;
}
Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifyMulInst(Op0, Op1, Q, RecursionLimit);
}
static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
Value *Op1, const SimplifyQuery &Q) {
bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
Type *Ty = Op0->getType();
if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
return PoisonValue::get(Ty);
if (match(Op1, m_Zero()))
return PoisonValue::get(Ty);
auto *Op1C = dyn_cast<Constant>(Op1);
auto *VTy = dyn_cast<FixedVectorType>(Ty);
if (Op1C && VTy) {
unsigned NumElts = VTy->getNumElements();
for (unsigned i = 0; i != NumElts; ++i) {
Constant *Elt = Op1C->getAggregateElement(i);
if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
return PoisonValue::get(Ty);
}
}
if (isa<PoisonValue>(Op0))
return Op0;
if (Q.isUndefValue(Op0))
return Constant::getNullValue(Ty);
if (match(Op0, m_Zero()))
return Constant::getNullValue(Op0->getType());
if (Op0 == Op1)
return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
Value *X;
if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
(match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
return IsDiv ? Op0 : Constant::getNullValue(Ty);
if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
auto *Mul = cast<OverflowingBinaryOperator>(Op0);
if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
(!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
(IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
(!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
return IsDiv ? X : Constant::getNullValue(Op0->getType());
}
}
return nullptr;
}
static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
const SimplifyQuery &Q, unsigned MaxRecurse) {
Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
Constant *C = dyn_cast_or_null<Constant>(V);
return (C && C->isAllOnesValue());
}
static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
unsigned MaxRecurse, bool IsSigned) {
if (!MaxRecurse--)
return false;
if (IsSigned) {
Type *Ty = X->getType();
const APInt *C;
if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
return true;
}
if (match(Y, m_APInt(C))) {
if (C->isMinSignedValue())
return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
return true;
}
return false;
}
const APInt *C;
if (match(Y, m_APInt(C)) &&
computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
return true;
return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
}
static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
return C;
if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q))
return V;
bool IsSigned = Opcode == Instruction::SDiv;
if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
(!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
return Constant::getNullValue(Op0->getType());
ConstantInt *C1, *C2;
if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) &&
match(Op1, m_ConstantInt(C2))) {
bool Overflow;
(void)C1->getValue().umul_ov(C2->getValue(), Overflow);
if (Overflow)
return Constant::getNullValue(Op0->getType());
}
if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
return Constant::getNullValue(Op0->getType());
return nullptr;
}
static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
return C;
if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q))
return V;
if ((Opcode == Instruction::SRem &&
match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
(Opcode == Instruction::URem &&
match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
return Op0;
if (Q.IIQ.UseInstrInfo &&
((Opcode == Instruction::SRem &&
match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
(Opcode == Instruction::URem &&
match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
return Constant::getNullValue(Op0->getType());
if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
return Op0;
return nullptr;
}
static Value *simplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (isKnownNegation(Op0, Op1, true))
return Constant::getAllOnesValue(Op0->getType());
return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
}
Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifySDivInst(Op0, Op1, Q, RecursionLimit);
}
static Value *simplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
}
Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifyUDivInst(Op0, Op1, Q, RecursionLimit);
}
static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
Value *X;
if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
return ConstantInt::getNullValue(Op0->getType());
if (isKnownNegation(Op0, Op1))
return ConstantInt::getNullValue(Op0->getType());
return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
}
Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
}
static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
}
Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
}
static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
Constant *C = dyn_cast<Constant>(Amount);
if (!C)
return false;
if (Q.isUndefValue(C))
return true;
if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
if (CI->getValue().uge(CI->getType()->getScalarSizeInBits()))
return true;
if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
for (unsigned I = 0,
E = cast<FixedVectorType>(C->getType())->getNumElements();
I != E; ++I)
if (!isPoisonShift(C->getAggregateElement(I), Q))
return false;
return true;
}
return false;
}
static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
Value *Op1, bool IsNSW, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op0))
return Op0;
if (match(Op0, m_Zero()))
return Constant::getNullValue(Op0->getType());
Value *X;
if (match(Op1, m_Zero()) ||
(match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
return Op0;
if (isPoisonShift(Op1, Q))
return PoisonValue::get(Op0->getType());
if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
return V;
KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
return PoisonValue::get(Op0->getType());
unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
return Op0;
if (IsNSW) {
assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
if (KnownVal.Zero.isSignBitSet())
KnownShl.Zero.setSignBit();
if (KnownVal.One.isSignBitSet())
KnownShl.One.setSignBit();
if (KnownShl.hasConflict())
return PoisonValue::get(Op0->getType());
}
return nullptr;
}
static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
Value *Op1, bool isExact,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Value *V =
simplifyShift(Opcode, Op0, Op1, false, Q, MaxRecurse))
return V;
if (Op0 == Op1)
return Constant::getNullValue(Op0->getType());
if (Q.isUndefValue(Op0))
return isExact ? Op0 : Constant::getNullValue(Op0->getType());
if (isExact) {
KnownBits Op0Known =
computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (Op0Known.One[0])
return Op0;
}
return nullptr;
}
static Value *simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Value *V =
simplifyShift(Instruction::Shl, Op0, Op1, isNSW, Q, MaxRecurse))
return V;
if (Q.isUndefValue(Op0))
return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Value *X;
if (Q.IIQ.UseInstrInfo &&
match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
return X;
if (isNUW && match(Op0, m_Negative()))
return Op0;
return nullptr;
}
Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
const SimplifyQuery &Q) {
return ::simplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
}
static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
MaxRecurse))
return V;
Value *X;
if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
return X;
Value *Y;
const APInt *ShRAmt, *ShLAmt;
if (match(Op1, m_APInt(ShRAmt)) &&
match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
*ShRAmt == *ShLAmt) {
const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
const unsigned EffWidthY = YKnown.countMaxActiveBits();
if (ShRAmt->uge(EffWidthY))
return X;
}
return nullptr;
}
Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
const SimplifyQuery &Q) {
return ::simplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
}
static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
MaxRecurse))
return V;
if (match(Op0, m_AllOnes()) ||
match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
return Constant::getAllOnesValue(Op0->getType());
Value *X;
if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
return X;
unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (NumSignBits == Op0->getType()->getScalarSizeInBits())
return Op0;
return nullptr;
}
Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
const SimplifyQuery &Q) {
return ::simplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
}
static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
ICmpInst *UnsignedICmp, bool IsAnd,
const SimplifyQuery &Q) {
Value *X, *Y;
ICmpInst::Predicate EqPred;
if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
!ICmpInst::isEquality(EqPred))
return nullptr;
ICmpInst::Predicate UnsignedPred;
Value *A, *B;
if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
if (match(UnsignedICmp,
m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
ICmpInst::isUnsigned(UnsignedPred)) {
if ((UnsignedPred == ICmpInst::ICMP_UGE ||
UnsignedPred == ICmpInst::ICMP_ULE) &&
EqPred == ICmpInst::ICMP_NE && !IsAnd)
return ConstantInt::getTrue(UnsignedICmp->getType());
if ((UnsignedPred == ICmpInst::ICMP_ULT ||
UnsignedPred == ICmpInst::ICMP_UGT) &&
EqPred == ICmpInst::ICMP_EQ && IsAnd)
return ConstantInt::getFalse(UnsignedICmp->getType());
if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
UnsignedPred == ICmpInst::ICMP_UGT))
return IsAnd ? UnsignedICmp : ZeroICmp;
if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
UnsignedPred == ICmpInst::ICMP_UGE))
return IsAnd ? ZeroICmp : UnsignedICmp;
}
if (match(UnsignedICmp,
m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
EqPred == ICmpInst::ICMP_NE &&
isKnownNonZero(B, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return UnsignedICmp;
if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
EqPred == ICmpInst::ICMP_EQ &&
isKnownNonZero(B, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return UnsignedICmp;
}
}
if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
ICmpInst::isUnsigned(UnsignedPred))
;
else if (match(UnsignedICmp,
m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
ICmpInst::isUnsigned(UnsignedPred))
UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
else
return nullptr;
if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
isKnownNonZero(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return IsAnd ? ZeroICmp : UnsignedICmp;
if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
isKnownNonZero(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return IsAnd ? UnsignedICmp : ZeroICmp;
if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
return IsAnd ? UnsignedICmp : ZeroICmp;
if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
return IsAnd ? ZeroICmp : UnsignedICmp;
if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
IsAnd)
return getFalse(UnsignedICmp->getType());
if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
!IsAnd)
return getTrue(UnsignedICmp->getType());
return nullptr;
}
static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
ICmpInst::Predicate Pred0, Pred1;
Value *A, *B;
if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
!match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
return nullptr;
if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
(Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
(Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
(Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
return getFalse(Op0->getType());
return nullptr;
}
static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
ICmpInst::Predicate Pred0, Pred1;
Value *A, *B;
if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
!match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
return nullptr;
if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
(Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
(Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
(Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
return getTrue(Op0->getType());
return nullptr;
}
static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool IsAnd) {
if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
return nullptr;
const APInt *C0, *C1;
if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
!match(Cmp1->getOperand(1), m_APInt(C1)))
return nullptr;
auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
return getFalse(Cmp0->getType());
if (!IsAnd && Range0.unionWith(Range1).isFullSet())
return getTrue(Cmp0->getType());
if (Range0.contains(Range1))
return IsAnd ? Cmp1 : Cmp0;
if (Range1.contains(Range0))
return IsAnd ? Cmp0 : Cmp1;
return nullptr;
}
static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool IsAnd) {
ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
if (!match(Cmp0->getOperand(1), m_Zero()) ||
!match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
return nullptr;
if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
return nullptr;
Value *X = Cmp0->getOperand(0);
Value *Y = Cmp1->getOperand(0);
if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
return Cmp1;
if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
return Cmp0;
return nullptr;
}
static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
const InstrInfoQuery &IIQ) {
ICmpInst::Predicate Pred0, Pred1;
const APInt *C0, *C1;
Value *V;
if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
return nullptr;
if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
return nullptr;
auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
if (AddInst->getOperand(1) != Op1->getOperand(1))
return nullptr;
Type *ITy = Op0->getType();
bool isNSW = IIQ.hasNoSignedWrap(AddInst);
bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
const APInt Delta = *C1 - *C0;
if (C0->isStrictlyPositive()) {
if (Delta == 2) {
if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
return getFalse(ITy);
if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
return getFalse(ITy);
}
if (Delta == 1) {
if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
return getFalse(ITy);
if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
return getFalse(ITy);
}
}
if (C0->getBoolValue() && isNUW) {
if (Delta == 2)
if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
return getFalse(ITy);
if (Delta == 1)
if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
return getFalse(ITy);
}
return nullptr;
}
static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool IsAnd) {
if (Cmp1->isEquality())
std::swap(Cmp0, Cmp1);
if (!Cmp0->isEquality())
return nullptr;
ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
Value *X = Cmp0->getOperand(0);
ICmpInst::Predicate Pred1;
bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
return nullptr;
if (ICmpInst::isEquality(Pred1))
return nullptr;
APInt MinMaxC;
const APInt *C;
if (match(Cmp0->getOperand(1), m_APInt(C)))
MinMaxC = HasNotOp ? ~*C : *C;
else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
MinMaxC = APInt::getZero(8);
else
return nullptr;
if (!IsAnd) {
Pred0 = ICmpInst::getInversePredicate(Pred0);
Pred1 = ICmpInst::getInversePredicate(Pred1);
}
if (ICmpInst::isSigned(Pred1)) {
Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
}
if (MinMaxC.isMaxValue())
if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
return Cmp1;
if (MinMaxC.isMinValue())
if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
return Cmp1;
return nullptr;
}
static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
bool IsAnd) {
ICmpInst::Predicate Pred0, Pred1;
Value *X;
const APInt *C;
if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
m_APInt(C))) ||
!match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
return nullptr;
if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
return Cmp1;
if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
return Cmp1;
return nullptr;
}
static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
const SimplifyQuery &Q) {
if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, true, Q))
return X;
if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, true, Q))
return X;
if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
return X;
if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
return X;
if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
return X;
if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
return X;
if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
return X;
if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
return X;
if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
return X;
if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
return X;
if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
return X;
return nullptr;
}
static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
const InstrInfoQuery &IIQ) {
ICmpInst::Predicate Pred0, Pred1;
const APInt *C0, *C1;
Value *V;
if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
return nullptr;
if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
return nullptr;
auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
if (AddInst->getOperand(1) != Op1->getOperand(1))
return nullptr;
Type *ITy = Op0->getType();
bool isNSW = IIQ.hasNoSignedWrap(AddInst);
bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
const APInt Delta = *C1 - *C0;
if (C0->isStrictlyPositive()) {
if (Delta == 2) {
if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
return getTrue(ITy);
if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
return getTrue(ITy);
}
if (Delta == 1) {
if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
return getTrue(ITy);
if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
return getTrue(ITy);
}
}
if (C0->getBoolValue() && isNUW) {
if (Delta == 2)
if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
return getTrue(ITy);
if (Delta == 1)
if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
return getTrue(ITy);
}
return nullptr;
}
static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
const SimplifyQuery &Q) {
if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, false, Q))
return X;
if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, false, Q))
return X;
if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
return X;
if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
return X;
if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
return X;
if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
return X;
if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
return X;
if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
return X;
if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
return X;
if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
return X;
if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
return X;
return nullptr;
}
static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, FCmpInst *LHS,
FCmpInst *RHS, bool IsAnd) {
Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
if (LHS0->getType() != RHS0->getType())
return nullptr;
FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
(PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
(isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
return RHS;
if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
(isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
return LHS;
}
return nullptr;
}
static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
Value *Op1, bool IsAnd) {
auto *Cast0 = dyn_cast<CastInst>(Op0);
auto *Cast1 = dyn_cast<CastInst>(Op1);
if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
Cast0->getSrcTy() == Cast1->getSrcTy()) {
Op0 = Cast0->getOperand(0);
Op1 = Cast1->getOperand(0);
}
Value *V = nullptr;
auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
if (ICmp0 && ICmp1)
V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
: simplifyOrOfICmps(ICmp0, ICmp1, Q);
auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
if (FCmp0 && FCmp1)
V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
if (!V)
return nullptr;
if (!Cast0)
return V;
if (auto *C = dyn_cast<Constant>(V))
return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
return nullptr;
}
static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
Instruction::BinaryOps Opcode) {
assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
Value *X;
Constant *C1, *C2;
if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
(match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
if (ConstantExpr::getNot(C1) == C2) {
Type *Ty = Op0->getType();
return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
: ConstantInt::getAllOnesValue(Ty);
}
}
return nullptr;
}
static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op1))
return Op1;
if (Q.isUndefValue(Op1))
return Constant::getNullValue(Op0->getType());
if (Op0 == Op1)
return Op0;
if (match(Op1, m_Zero()))
return Constant::getNullValue(Op0->getType());
if (match(Op1, m_AllOnes()))
return Op0;
if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
return Constant::getNullValue(Op0->getType());
if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
return Op1;
if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
return Op0;
Value *X, *Y;
if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
return X;
if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
return X;
if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
return V;
const APInt *Mask;
const APInt *ShAmt;
if (match(Op1, m_APInt(Mask))) {
if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
(~(*Mask)).lshr(*ShAmt).isZero())
return Op0;
if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
(~(*Mask)).shl(*ShAmt).isZero())
return Op0;
}
if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
return Op1;
if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
return Op0;
if (match(Op0, m_Neg(m_Specific(Op1))) ||
match(Op1, m_Neg(m_Specific(Op0)))) {
if (isKnownToBeAPowerOfTwo(Op0, Q.DL, true, 0, Q.AC, Q.CxtI,
Q.DT))
return Op0;
if (isKnownToBeAPowerOfTwo(Op1, Q.DL, true, 0, Q.AC, Q.CxtI,
Q.DT))
return Op1;
}
if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
isKnownToBeAPowerOfTwo(Op1, Q.DL, true, 0, Q.AC, Q.CxtI, Q.DT))
return Constant::getNullValue(Op1->getType());
if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
isKnownToBeAPowerOfTwo(Op0, Q.DL, true, 0, Q.AC, Q.CxtI, Q.DT))
return Constant::getNullValue(Op0->getType());
if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
return V;
if (Value *V =
simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
Instruction::Or, Q, MaxRecurse))
return V;
if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
Instruction::Xor, Q, MaxRecurse))
return V;
if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
if (Op0->getType()->isIntOrIntVectorTy(1)) {
if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
return Op1;
else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
return Op0;
}
if (Value *V =
threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
return V;
}
if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
if (Value *V =
threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
return V;
Value *XShifted;
if (match(Op1, m_APInt(Mask)) &&
match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
m_Value(XShifted)),
m_Value(Y)))) {
const unsigned Width = Op0->getType()->getScalarSizeInBits();
const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
const unsigned EffWidthY = YKnown.countMaxActiveBits();
if (EffWidthY <= ShftCnt) {
const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
const unsigned EffWidthX = XKnown.countMaxActiveBits();
const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
return Y;
if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
return XShifted;
}
}
BinaryOperator *Or;
if (match(Op0, m_c_Xor(m_Value(X),
m_CombineAnd(m_BinOp(Or),
m_c_Or(m_Deferred(X), m_Value(Y))))) &&
match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
return Constant::getNullValue(Op0->getType());
if (Op0->getType()->isIntOrIntVectorTy(1)) {
if (isImpliedCondition(Op0, Op1, Q.DL).value_or(false))
return Op0;
if (isImpliedCondition(Op1, Op0, Q.DL).value_or(false))
return Op1;
}
return nullptr;
}
Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
}
static Value *simplifyOrLogic(Value *X, Value *Y) {
assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
Type *Ty = X->getType();
if (match(Y, m_Not(m_Specific(X))))
return ConstantInt::getAllOnesValue(Ty);
if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
return ConstantInt::getAllOnesValue(Ty);
if (match(Y, m_c_And(m_Specific(X), m_Value())))
return X;
Value *A, *B;
if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
return Y;
if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
return ConstantInt::getAllOnesValue(Ty);
if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
return Y;
if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
match(Y, m_c_And(m_Specific(A), m_Specific(B))))
return X;
if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
return ConstantInt::getAllOnesValue(Ty);
Value *NotA;
if (match(X,
m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
m_Value(B))) &&
match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
return NotA;
Value *NotAB;
if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
m_Value(NotAB))) &&
match(Y, m_c_And(m_Specific(A), m_Specific(B))))
return NotAB;
if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
m_Value(NotAB))) &&
match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
return NotAB;
return nullptr;
}
static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op1))
return Op1;
if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
return Constant::getAllOnesValue(Op0->getType());
if (Op0 == Op1 || match(Op1, m_Zero()))
return Op0;
if (Value *R = simplifyOrLogic(Op0, Op1))
return R;
if (Value *R = simplifyOrLogic(Op1, Op0))
return R;
if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
return V;
Value *X, *Y;
if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
(match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
const APInt *C;
if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
C->ule(X->getType()->getScalarSizeInBits())) {
return ConstantInt::getAllOnesValue(X->getType());
}
}
if (match(Op0,
m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
return Op0;
if (match(Op1,
m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
return Op1;
if (match(Op0,
m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
return Op0;
if (match(Op1,
m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
return Op1;
if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
return V;
if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
return Op1;
if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
return Op0;
if (Value *V =
simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
return V;
if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
Instruction::And, Q, MaxRecurse))
return V;
if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
if (Op0->getType()->isIntOrIntVectorTy(1)) {
if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
return Op1;
else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
return Op0;
}
if (Value *V =
threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
return V;
}
Value *A, *B;
const APInt *C1, *C2;
if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
if (*C1 == ~*C2) {
Value *N;
if (C2->isMask() && match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return A;
}
if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return B;
}
}
}
if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
return V;
if (Op0->getType()->isIntOrIntVectorTy(1)) {
if (isImpliedCondition(Op0, Op1, Q.DL).value_or(false))
return Op1;
if (isImpliedCondition(Op1, Op0, Q.DL).value_or(false))
return Op0;
}
return nullptr;
}
Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
}
static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
return C;
if (isa<PoisonValue>(Op1))
return Op1;
if (Q.isUndefValue(Op1))
return Op1;
if (match(Op1, m_Zero()))
return Op0;
if (Op0 == Op1)
return Constant::getNullValue(Op0->getType());
if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
return Constant::getAllOnesValue(Op0->getType());
auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
Value *A, *B;
if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
return A;
Value *NotA;
if (match(X,
m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
m_Value(B))) &&
match(Y, m_c_And(m_Specific(A), m_Specific(B))))
return NotA;
return nullptr;
};
if (Value *R = foldAndOrNot(Op0, Op1))
return R;
if (Value *R = foldAndOrNot(Op1, Op0))
return R;
if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
return V;
if (Value *V =
simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
return V;
return nullptr;
}
Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
}
static Type *getCompareTy(Value *Op) {
return CmpInst::makeCmpResultType(Op->getType());
}
static Value *extractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
Value *LHS, Value *RHS) {
SelectInst *SI = dyn_cast<SelectInst>(V);
if (!SI)
return nullptr;
CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
if (!Cmp)
return nullptr;
Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
return Cmp;
if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
LHS == CmpRHS && RHS == CmpLHS)
return Cmp;
return nullptr;
}
static bool isAllocDisjoint(const Value *V) {
if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
!GV->isThreadLocal();
if (const Argument *A = dyn_cast<Argument>(V))
return A->hasByValAttr();
return false;
}
static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
auto isByValArg = [](const Value *V) {
const Argument *A = dyn_cast<Argument>(V);
return A && A->hasByValAttr();
};
if (isByValArg(V1))
return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
if (isByValArg(V2))
return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
return isa<AllocaInst>(V1) &&
(isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
}
static Constant *computePointerICmp(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const SimplifyQuery &Q) {
const DataLayout &DL = Q.DL;
const TargetLibraryInfo *TLI = Q.TLI;
const DominatorTree *DT = Q.DT;
const Instruction *CxtI = Q.CxtI;
const InstrInfoQuery &IIQ = Q.IIQ;
LHS = LHS->stripPointerCasts();
RHS = RHS->stripPointerCasts();
if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
IIQ.UseInstrInfo))
return ConstantInt::get(getCompareTy(LHS), !CmpInst::isTrueWhenEqual(Pred));
switch (Pred) {
default:
return nullptr;
case CmpInst::ICMP_EQ:
case CmpInst::ICMP_NE:
break;
case CmpInst::ICMP_UGT:
case CmpInst::ICMP_UGE:
case CmpInst::ICMP_ULT:
case CmpInst::ICMP_ULE:
Pred = ICmpInst::getSignedPredicate(Pred);
break;
}
bool AllowNonInbounds = ICmpInst::isEquality(Pred);
APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
if (LHS == RHS)
return ConstantInt::get(getCompareTy(LHS),
ICmpInst::compare(LHSOffset, RHSOffset, Pred));
if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
if (haveNonOverlappingStorage(LHS, RHS)) {
uint64_t LHSSize, RHSSize;
ObjectSizeOpts Opts;
Opts.EvalMode = ObjectSizeOpts::Mode::Min;
auto *F = [](Value *V) -> Function * {
if (auto *I = dyn_cast<Instruction>(V))
return I->getFunction();
if (auto *A = dyn_cast<Argument>(V))
return A->getParent();
return nullptr;
}(LHS);
Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
!LHSOffset.isNegative() && !RHSOffset.isNegative() &&
LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
return ConstantInt::get(getCompareTy(LHS),
!CmpInst::isTrueWhenEqual(Pred));
}
}
SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
getUnderlyingObjects(LHS, LHSUObjs);
getUnderlyingObjects(RHS, RHSUObjs);
auto IsNAC = [](ArrayRef<const Value *> Objects) {
return all_of(Objects, isNoAliasCall);
};
auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
return all_of(Objects, ::isAllocDisjoint);
};
if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
(IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
return ConstantInt::get(getCompareTy(LHS),
!CmpInst::isTrueWhenEqual(Pred));
Value *MI = nullptr;
if (isAllocLikeFn(LHS, TLI) &&
llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
MI = LHS;
else if (isAllocLikeFn(RHS, TLI) &&
llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
MI = RHS;
if (MI && !PointerMayBeCaptured(MI, true, true))
return ConstantInt::get(getCompareTy(LHS),
CmpInst::isFalseWhenEqual(Pred));
}
return nullptr;
}
static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const SimplifyQuery &Q) {
Type *ITy = getCompareTy(LHS); Type *OpTy = LHS->getType(); if (!OpTy->isIntOrIntVectorTy(1))
return nullptr;
auto ExtractNotLHS = [](Value *V) -> Value * {
Value *X;
if (match(V, m_Not(m_Value(X))))
return X;
return nullptr;
};
if (match(RHS, m_Zero())) {
switch (Pred) {
case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT: case CmpInst::ICMP_SLT: return LHS;
case CmpInst::ICMP_EQ: case CmpInst::ICMP_ULE: case CmpInst::ICMP_SGE: if (Value *X = ExtractNotLHS(LHS))
return X;
break;
case CmpInst::ICMP_ULT: case CmpInst::ICMP_SGT: return getFalse(ITy);
case CmpInst::ICMP_UGE: case CmpInst::ICMP_SLE: return getTrue(ITy);
default:
break;
}
} else if (match(RHS, m_One())) {
switch (Pred) {
case CmpInst::ICMP_EQ: case CmpInst::ICMP_UGE: case CmpInst::ICMP_SLE: return LHS;
case CmpInst::ICMP_NE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_SGT: if (Value *X = ExtractNotLHS(LHS))
return X;
break;
case CmpInst::ICMP_UGT: case CmpInst::ICMP_SLT: return getFalse(ITy);
case CmpInst::ICMP_ULE: case CmpInst::ICMP_SGE: return getTrue(ITy);
default:
break;
}
}
switch (Pred) {
default:
break;
case ICmpInst::ICMP_UGE:
if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
return getTrue(ITy);
break;
case ICmpInst::ICMP_SGE:
if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
return getTrue(ITy);
break;
case ICmpInst::ICMP_ULE:
if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
return getTrue(ITy);
break;
}
return nullptr;
}
static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const SimplifyQuery &Q) {
if (!match(RHS, m_Zero()))
return nullptr;
Type *ITy = getCompareTy(LHS); switch (Pred) {
default:
llvm_unreachable("Unknown ICmp predicate!");
case ICmpInst::ICMP_ULT:
return getFalse(ITy);
case ICmpInst::ICMP_UGE:
return getTrue(ITy);
case ICmpInst::ICMP_EQ:
case ICmpInst::ICMP_ULE:
if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
return getFalse(ITy);
break;
case ICmpInst::ICMP_NE:
case ICmpInst::ICMP_UGT:
if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
return getTrue(ITy);
break;
case ICmpInst::ICMP_SLT: {
KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (LHSKnown.isNegative())
return getTrue(ITy);
if (LHSKnown.isNonNegative())
return getFalse(ITy);
break;
}
case ICmpInst::ICMP_SLE: {
KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (LHSKnown.isNegative())
return getTrue(ITy);
if (LHSKnown.isNonNegative() &&
isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return getFalse(ITy);
break;
}
case ICmpInst::ICMP_SGE: {
KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (LHSKnown.isNegative())
return getFalse(ITy);
if (LHSKnown.isNonNegative())
return getTrue(ITy);
break;
}
case ICmpInst::ICMP_SGT: {
KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (LHSKnown.isNegative())
return getFalse(ITy);
if (LHSKnown.isNonNegative() &&
isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return getTrue(ITy);
break;
}
}
return nullptr;
}
static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const InstrInfoQuery &IIQ) {
Type *ITy = getCompareTy(RHS);
Value *X;
if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
return ConstantInt::getFalse(ITy);
if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
return ConstantInt::getTrue(ITy);
}
const APInt *C;
if (!match(RHS, m_APIntAllowUndef(C)))
return nullptr;
ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
if (RHS_CR.isEmptySet())
return ConstantInt::getFalse(ITy);
if (RHS_CR.isFullSet())
return ConstantInt::getTrue(ITy);
ConstantRange LHS_CR =
computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
if (!LHS_CR.isFullSet()) {
if (RHS_CR.contains(LHS_CR))
return ConstantInt::getTrue(ITy);
if (RHS_CR.inverse().contains(LHS_CR))
return ConstantInt::getFalse(ITy);
}
const APInt *MulC;
if (ICmpInst::isEquality(Pred) &&
((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
*MulC != 0 && C->urem(*MulC) != 0) ||
(match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
*MulC != 0 && C->srem(*MulC) != 0)))
return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
return nullptr;
}
static Value *simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,
BinaryOperator *LBO, Value *RHS,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
Type *ITy = getCompareTy(RHS);
Value *Y = nullptr;
if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
if (Pred == ICmpInst::ICMP_ULT)
return getFalse(ITy);
if (Pred == ICmpInst::ICMP_UGE)
return getTrue(ITy);
if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (RHSKnown.isNonNegative() && YKnown.isNegative())
return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
if (RHSKnown.isNegative() || YKnown.isNonNegative())
return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
}
}
if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
if (Pred == ICmpInst::ICMP_UGT)
return getFalse(ITy);
if (Pred == ICmpInst::ICMP_ULE)
return getTrue(ITy);
}
if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
switch (Pred) {
default:
break;
case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE: {
KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (!Known.isNonNegative())
break;
LLVM_FALLTHROUGH;
}
case ICmpInst::ICMP_EQ:
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE:
return getFalse(ITy);
case ICmpInst::ICMP_SLT:
case ICmpInst::ICMP_SLE: {
KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
if (!Known.isNonNegative())
break;
LLVM_FALLTHROUGH;
}
case ICmpInst::ICMP_NE:
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_ULE:
return getTrue(ITy);
}
}
if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
if (Pred == ICmpInst::ICMP_ULE)
return getTrue(ITy);
if (Pred == ICmpInst::ICMP_UGT)
return getFalse(ITy);
}
if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
if (Pred == ICmpInst::ICMP_UGT)
return getFalse(ITy);
if (Pred == ICmpInst::ICMP_ULE)
return getTrue(ITy);
}
const APInt *C;
if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
(match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
switch (Pred) {
default:
break;
case ICmpInst::ICMP_EQ:
case ICmpInst::ICMP_UGE:
return getFalse(ITy);
case ICmpInst::ICMP_NE:
case ICmpInst::ICMP_ULT:
return getTrue(ITy);
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_ULE:
llvm_unreachable("Unexpected UGT/ULE, should have been handled");
}
}
}
const APInt *C1, *C2;
if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
C1->ule(*C2)) ||
(match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
(match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
(APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
if (Pred == ICmpInst::ICMP_UGT)
return getFalse(ITy);
if (Pred == ICmpInst::ICMP_ULE)
return getTrue(ITy);
}
return nullptr;
}
static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
Value *RHS) {
if (Pred != CmpInst::ICMP_SLT)
return false;
if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
std::swap(LHS, RHS);
if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
return false;
Value *X;
const APInt *C1, *C2;
if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
!match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
return false;
return (C1->slt(*C2) && C1->isNonNegative()) ||
(C2->slt(*C1) && C1->isNonPositive());
}
static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const SimplifyQuery &Q,
unsigned MaxRecurse) {
BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
if (MaxRecurse && (LBO || RBO)) {
Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
if (LBO && LBO->getOpcode() == Instruction::Add) {
A = LBO->getOperand(0);
B = LBO->getOperand(1);
NoLHSWrapProblem =
ICmpInst::isEquality(Pred) ||
(CmpInst::isUnsigned(Pred) &&
Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
(CmpInst::isSigned(Pred) &&
Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
}
if (RBO && RBO->getOpcode() == Instruction::Add) {
C = RBO->getOperand(0);
D = RBO->getOperand(1);
NoRHSWrapProblem =
ICmpInst::isEquality(Pred) ||
(CmpInst::isUnsigned(Pred) &&
Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
(CmpInst::isSigned(Pred) &&
Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
}
if ((A == RHS || B == RHS) && NoLHSWrapProblem)
if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
Constant::getNullValue(RHS->getType()), Q,
MaxRecurse - 1))
return V;
if ((C == LHS || D == LHS) && NoRHSWrapProblem)
if (Value *V =
simplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
C == LHS ? D : C, Q, MaxRecurse - 1))
return V;
bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
trySimplifyICmpWithAdds(Pred, LHS, RHS);
if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
Value *Y, *Z;
if (A == C) {
Y = B;
Z = D;
} else if (A == D) {
Y = B;
Z = C;
} else if (B == C) {
Y = A;
Z = D;
} else {
assert(B == D);
Y = A;
Z = C;
}
if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
return V;
}
}
if (LBO)
if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
return V;
if (RBO)
if (Value *V = simplifyICmpWithBinOpOnLHS(
ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
return V;
if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
const APInt *C;
if (match(RHS, m_APInt(C))) {
if (C->isStrictlyPositive()) {
if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
return ConstantInt::getTrue(getCompareTy(RHS));
if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
return ConstantInt::getFalse(getCompareTy(RHS));
}
if (C->isNonNegative()) {
if (Pred == ICmpInst::ICMP_SLE)
return ConstantInt::getTrue(getCompareTy(RHS));
if (Pred == ICmpInst::ICMP_SGT)
return ConstantInt::getFalse(getCompareTy(RHS));
}
}
}
const APInt *C;
if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
if (Pred == ICmpInst::ICMP_EQ)
return ConstantInt::getFalse(getCompareTy(RHS));
if (Pred == ICmpInst::ICMP_NE)
return ConstantInt::getTrue(getCompareTy(RHS));
}
}
if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
if (Pred == ICmpInst::ICMP_UGT)
return ConstantInt::getFalse(getCompareTy(RHS));
if (Pred == ICmpInst::ICMP_ULE)
return ConstantInt::getTrue(getCompareTy(RHS));
}
if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
LBO->getOperand(1) == RBO->getOperand(1)) {
switch (LBO->getOpcode()) {
default:
break;
case Instruction::UDiv:
case Instruction::LShr:
if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
!Q.IIQ.isExact(RBO))
break;
if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
RBO->getOperand(0), Q, MaxRecurse - 1))
return V;
break;
case Instruction::SDiv:
if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
!Q.IIQ.isExact(RBO))
break;
if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
RBO->getOperand(0), Q, MaxRecurse - 1))
return V;
break;
case Instruction::AShr:
if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
break;
if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
RBO->getOperand(0), Q, MaxRecurse - 1))
return V;
break;
case Instruction::Shl: {
bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
if (!NUW && !NSW)
break;
if (!NSW && ICmpInst::isSigned(Pred))
break;
if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
RBO->getOperand(0), Q, MaxRecurse - 1))
return V;
break;
}
}
}
return nullptr;
}
static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
Value *RHS, const SimplifyQuery &Q,
unsigned MaxRecurse) {
Type *ITy = getCompareTy(LHS); Value *A, *B;
CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
CmpInst::Predicate EqP;
if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
if (A != RHS)
std::swap(A, B); EqP = CmpInst::ICMP_SGE; P = Pred;
} else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
(A == LHS || B == LHS)) {
if (A != LHS)
std::swap(A, B); EqP = CmpInst::ICMP_SGE; P = CmpInst::getSwappedPredicate(Pred);
} else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
(A == RHS || B == RHS)) {
if (A != RHS)
std::swap(A, B); EqP = CmpInst::ICMP_SLE; P = CmpInst::getSwappedPredicate(Pred);
} else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
(A == LHS || B == LHS)) {
if (A != LHS)
std::swap(A, B); EqP = CmpInst::ICMP_SLE; P = Pred;
}
if (P != CmpInst::BAD_ICMP_PREDICATE) {
switch (P) {
default:
break;
case CmpInst::ICMP_EQ:
case CmpInst::ICMP_SLE:
if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
return V;
if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
return V;
if (MaxRecurse)
if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
return V;
break;
case CmpInst::ICMP_NE:
case CmpInst::ICMP_SGT: {
CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
return V;
if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
return V;
if (MaxRecurse)
if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
return V;
break;
}
case CmpInst::ICMP_SGE:
return getTrue(ITy);
case CmpInst::ICMP_SLT:
return getFalse(ITy);
}
}
P = CmpInst::BAD_ICMP_PREDICATE;
if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
if (A != RHS)
std::swap(A, B); EqP = CmpInst::ICMP_UGE; P = Pred;
} else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
(A == LHS || B == LHS)) {
if (A != LHS)
std::swap(A, B); EqP = CmpInst::ICMP_UGE; P = CmpInst::getSwappedPredicate(Pred);
} else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
(A == RHS || B == RHS)) {
if (A != RHS)
std::swap(A, B); EqP = CmpInst::ICMP_ULE; P = CmpInst::getSwappedPredicate(Pred);
} else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
(A == LHS || B == LHS)) {
if (A != LHS)
std::swap(A, B); EqP = CmpInst::ICMP_ULE; P = Pred;
}
if (P != CmpInst::BAD_ICMP_PREDICATE) {
switch (P) {
default:
break;
case CmpInst::ICMP_EQ:
case CmpInst::ICMP_ULE:
if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
return V;
if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
return V;
if (MaxRecurse)
if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
return V;
break;
case CmpInst::ICMP_NE:
case CmpInst::ICMP_UGT: {
CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
return V;
if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
return V;
if (MaxRecurse)
if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
return V;
break;
}
case CmpInst::ICMP_UGE:
return getTrue(ITy);
case CmpInst::ICMP_ULT:
return getFalse(ITy);
}
}
if (match(LHS, m_UMin(m_Value(), m_Value())) ||
match(LHS, m_SMin(m_Value(), m_Value()))) {
std::swap(LHS, RHS);
Pred = ICmpInst::getSwappedPredicate(Pred);
}
Value *C, *D;
if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
(A == C || A == D || B == C || B == D)) {
if (Pred == CmpInst::ICMP_SGE)
return getTrue(ITy);
if (Pred == CmpInst::ICMP_SLT)
return getFalse(ITy);
} else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
(A == C || A == D || B == C || B == D)) {
if (Pred == CmpInst::ICMP_UGE)
return getTrue(ITy);
if (Pred == CmpInst::ICMP_ULT)
return getFalse(ITy);
}
return nullptr;
}
static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
Value *LHS, Value *RHS,
const SimplifyQuery &Q) {
if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
return nullptr;
for (Value *AssumeBaseOp : {LHS, RHS}) {
for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
if (!AssumeVH)
continue;
CallInst *Assume = cast<CallInst>(AssumeVH);
if (Optional<bool> Imp = isImpliedCondition(Assume->getArgOperand(0),
Predicate, LHS, RHS, Q.DL))
if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
return ConstantInt::get(getCompareTy(LHS), *Imp);
}
}
return nullptr;
}
static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
const SimplifyQuery &Q, unsigned MaxRecurse) {
CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
if (Constant *CRHS = dyn_cast<Constant>(RHS))
return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
std::swap(LHS, RHS);
Pred = CmpInst::getSwappedPredicate(Pred);
}
assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
Type *ITy = getCompareTy(LHS);
if (isa<PoisonValue>(RHS))
return PoisonValue::get(ITy);
if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
return UndefValue::get(ITy);
if (LHS == RHS || Q.isUndefValue(RHS))
return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
return V;
if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
return V;
if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
return V;
if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
auto RHS_Instr = cast<Instruction>(RHS);
auto LHS_Instr = cast<Instruction>(LHS);
if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
auto RHS_CR = getConstantRangeFromMetadata(
*RHS_Instr->getMetadata(LLVMContext::MD_range));
auto LHS_CR = getConstantRangeFromMetadata(
*LHS_Instr->getMetadata(LLVMContext::MD_range));
if (LHS_CR.icmp(Pred, RHS_CR))
return ConstantInt::getTrue(RHS->getContext());
if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
return ConstantInt::getFalse(RHS->getContext());
}
}
if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
Instruction *LI = cast<CastInst>(LHS);
Value *SrcOp = LI->getOperand(0);
Type *SrcTy = SrcOp->getType();
Type *DstTy = LI->getType();
if (MaxRecurse && isa<PtrToIntInst>(LI) &&
Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
if (Value *V = simplifyICmpInst(Pred, SrcOp,
ConstantExpr::getIntToPtr(RHSC, SrcTy),
Q, MaxRecurse - 1))
return V;
} else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
if (RI->getOperand(0)->getType() == SrcTy)
if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
MaxRecurse - 1))
return V;
}
}
if (isa<ZExtInst>(LHS)) {
if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
if (Value *V =
simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), SrcOp,
RI->getOperand(0), Q, MaxRecurse - 1))
return V;
}
else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
if (SrcOp == RI->getOperand(0)) {
if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
return ConstantInt::getTrue(ITy);
if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
return ConstantInt::getFalse(ITy);
}
}
else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
if (RExt == CI && MaxRecurse)
if (Value *V = simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
SrcOp, Trunc, Q, MaxRecurse - 1))
return V;
if (RExt != CI) {
switch (Pred) {
default:
llvm_unreachable("Unknown ICmp predicate!");
case ICmpInst::ICMP_EQ:
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE:
return ConstantInt::getFalse(CI->getContext());
case ICmpInst::ICMP_NE:
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_ULE:
return ConstantInt::getTrue(CI->getContext());
case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE:
return CI->getValue().isNegative()
? ConstantInt::getTrue(CI->getContext())
: ConstantInt::getFalse(CI->getContext());
case ICmpInst::ICMP_SLT:
case ICmpInst::ICMP_SLE:
return CI->getValue().isNegative()
? ConstantInt::getFalse(CI->getContext())
: ConstantInt::getTrue(CI->getContext());
}
}
}
}
if (isa<SExtInst>(LHS)) {
if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
MaxRecurse - 1))
return V;
}
else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
if (SrcOp == RI->getOperand(0)) {
if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
return ConstantInt::getTrue(ITy);
if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
return ConstantInt::getFalse(ITy);
}
}
else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
if (RExt == CI && MaxRecurse)
if (Value *V =
simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
return V;
if (RExt != CI) {
switch (Pred) {
default:
llvm_unreachable("Unknown ICmp predicate!");
case ICmpInst::ICMP_EQ:
return ConstantInt::getFalse(CI->getContext());
case ICmpInst::ICMP_NE:
return ConstantInt::getTrue(CI->getContext());
case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE:
return CI->getValue().isNegative()
? ConstantInt::getTrue(CI->getContext())
: ConstantInt::getFalse(CI->getContext());
case ICmpInst::ICMP_SLT:
case ICmpInst::ICMP_SLE:
return CI->getValue().isNegative()
? ConstantInt::getFalse(CI->getContext())
: ConstantInt::getTrue(CI->getContext());
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE:
if (MaxRecurse)
if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
Constant::getNullValue(SrcTy), Q,
MaxRecurse - 1))
return V;
break;
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_ULE:
if (MaxRecurse)
if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
Constant::getNullValue(SrcTy), Q,
MaxRecurse - 1))
return V;
break;
}
}
}
}
}
if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
}
if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
return V;
if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
return V;
if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
return V;
if (LHS->getType()->isPointerTy())
if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
return C;
if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
Q.DL.getTypeSizeInBits(CLHS->getType()) &&
Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
Q.DL.getTypeSizeInBits(CRHS->getType()))
if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
CRHS->getPointerOperand(), Q))
return C;
if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
return V;
if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
return V;
return nullptr;
}
Value *llvm::simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
const SimplifyQuery &Q) {
return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
}
static Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
FastMathFlags FMF, const SimplifyQuery &Q,
unsigned MaxRecurse) {
CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
if (Constant *CRHS = dyn_cast<Constant>(RHS))
return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI,
Q.CxtI);
std::swap(LHS, RHS);
Pred = CmpInst::getSwappedPredicate(Pred);
}
Type *RetTy = getCompareTy(LHS);
if (Pred == FCmpInst::FCMP_FALSE)
return getFalse(RetTy);
if (Pred == FCmpInst::FCMP_TRUE)
return getTrue(RetTy);
if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
if (FMF.noNaNs() ||
(isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
"Comparison must be either ordered or unordered");
if (match(RHS, m_NaN()))
return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
return PoisonValue::get(RetTy);
if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
}
if (LHS == RHS) {
if (CmpInst::isTrueWhenEqual(Pred))
return getTrue(RetTy);
if (CmpInst::isFalseWhenEqual(Pred))
return getFalse(RetTy);
}
const APFloat *C;
if (match(RHS, m_APFloat(C))) {
if (C->isInfinity()) {
if (C->isNegative()) {
switch (Pred) {
case FCmpInst::FCMP_OLT:
return getFalse(RetTy);
case FCmpInst::FCMP_UGE:
return getTrue(RetTy);
default:
break;
}
} else {
switch (Pred) {
case FCmpInst::FCMP_OGT:
return getFalse(RetTy);
case FCmpInst::FCMP_ULE:
return getTrue(RetTy);
default:
break;
}
}
if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
return getFalse(RetTy);
if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
return getTrue(RetTy);
if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
isKnownNeverNaN(LHS, Q.TLI))
return getFalse(RetTy);
if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
isKnownNeverNaN(LHS, Q.TLI))
return getTrue(RetTy);
}
if (C->isNegative() && !C->isNegZero()) {
assert(!C->isNaN() && "Unexpected NaN constant!");
switch (Pred) {
case FCmpInst::FCMP_UGE:
case FCmpInst::FCMP_UGT:
case FCmpInst::FCMP_UNE:
if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
return getTrue(RetTy);
break;
case FCmpInst::FCMP_OEQ:
case FCmpInst::FCMP_OLE:
case FCmpInst::FCMP_OLT:
if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
return getFalse(RetTy);
break;
default:
break;
}
}
const APFloat *C2;
if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
*C2 < *C) ||
(match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
*C2 > *C)) {
bool IsMaxNum =
cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
switch (Pred) {
case FCmpInst::FCMP_OEQ:
case FCmpInst::FCMP_UEQ:
return getFalse(RetTy);
case FCmpInst::FCMP_ONE:
case FCmpInst::FCMP_UNE:
return getTrue(RetTy);
case FCmpInst::FCMP_OGE:
case FCmpInst::FCMP_UGE:
case FCmpInst::FCMP_OGT:
case FCmpInst::FCMP_UGT:
return ConstantInt::get(RetTy, IsMaxNum);
case FCmpInst::FCMP_OLE:
case FCmpInst::FCMP_ULE:
case FCmpInst::FCMP_OLT:
case FCmpInst::FCMP_ULT:
return ConstantInt::get(RetTy, !IsMaxNum);
default:
llvm_unreachable("Unexpected fcmp predicate");
}
}
}
if (match(RHS, m_AnyZeroFP())) {
switch (Pred) {
case FCmpInst::FCMP_OGE:
case FCmpInst::FCMP_ULT:
if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
CannotBeOrderedLessThanZero(LHS, Q.TLI))
return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
break;
case FCmpInst::FCMP_UGE:
case FCmpInst::FCMP_OLT:
if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
break;
default:
break;
}
}
if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
return V;
if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
return V;
return nullptr;
}
Value *llvm::simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
FastMathFlags FMF, const SimplifyQuery &Q) {
return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
}
static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
const SimplifyQuery &Q,
bool AllowRefinement,
unsigned MaxRecurse) {
assert(!Op->getType()->isVectorTy() && "This is not safe for vectors");
if (V == Op)
return RepOp;
if (isa<Constant>(Op))
return nullptr;
auto *I = dyn_cast<Instruction>(V);
if (!I || !is_contained(I->operands(), Op))
return nullptr;
SmallVector<Value *, 8> NewOps(I->getNumOperands());
transform(I->operands(), NewOps.begin(),
[&](Value *V) { return V == Op ? RepOp : V; });
if (!AllowRefinement) {
if (auto *BO = dyn_cast<BinaryOperator>(I)) {
unsigned Opcode = BO->getOpcode();
if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
return NewOps[1];
if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
true))
return NewOps[0];
if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
NewOps[0] == NewOps[1])
return NewOps[0];
}
if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
!GEP->isInBounds())
return NewOps[0];
}
} else if (MaxRecurse) {
auto PreventSelfSimplify = [V](Value *Simplified) {
return Simplified != V ? Simplified : nullptr;
};
if (auto *B = dyn_cast<BinaryOperator>(I))
return PreventSelfSimplify(simplifyBinOp(B->getOpcode(), NewOps[0],
NewOps[1], Q, MaxRecurse - 1));
if (CmpInst *C = dyn_cast<CmpInst>(I))
return PreventSelfSimplify(simplifyCmpInst(C->getPredicate(), NewOps[0],
NewOps[1], Q, MaxRecurse - 1));
if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
return PreventSelfSimplify(simplifyGEPInst(
GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1),
GEP->isInBounds(), Q, MaxRecurse - 1));
if (isa<SelectInst>(I))
return PreventSelfSimplify(simplifySelectInst(
NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse - 1));
}
SmallVector<Constant *, 8> ConstOps;
for (Value *NewOp : NewOps) {
if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
ConstOps.push_back(ConstOp);
else
return nullptr;
}
if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
return nullptr;
return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
}
Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
const SimplifyQuery &Q,
bool AllowRefinement) {
return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
RecursionLimit);
}
static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
const APInt *Y, bool TrueWhenUnset) {
const APInt *C;
if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
*Y == ~*C)
return TrueWhenUnset ? FalseVal : TrueVal;
if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
*Y == ~*C)
return TrueWhenUnset ? FalseVal : TrueVal;
if (Y->isPowerOf2()) {
if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
*Y == *C)
return TrueWhenUnset ? TrueVal : FalseVal;
if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
*Y == *C)
return TrueWhenUnset ? TrueVal : FalseVal;
}
return nullptr;
}
static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
ICmpInst::Predicate Pred,
Value *TrueVal, Value *FalseVal) {
Value *X;
APInt Mask;
if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
return nullptr;
return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
Pred == ICmpInst::ICMP_EQ);
}
static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
Value *FalseVal,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
ICmpInst::Predicate Pred;
Value *CmpLHS, *CmpRHS;
if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
return nullptr;
if (Pred == ICmpInst::ICMP_NE) {
Pred = ICmpInst::ICMP_EQ;
std::swap(TrueVal, FalseVal);
}
if (TrueVal->getType()->isIntOrIntVectorTy()) {
Value *X, *Y;
SelectPatternFlavor SPF =
matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
X, Y)
.Flavor;
if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
X->getType()->getScalarSizeInBits());
if (match(Y, m_SpecificInt(LimitC)))
return X;
}
}
if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
Value *X;
const APInt *Y;
if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
true))
return V;
Value *ShAmt;
auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
return X;
auto isRotate =
m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
Pred == ICmpInst::ICMP_EQ)
return FalseVal;
if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
return FalseVal;
if (match(TrueVal,
m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
return FalseVal;
}
if (Value *V =
simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
return V;
if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) {
if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
false,
MaxRecurse) == TrueVal ||
simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
false,
MaxRecurse) == TrueVal)
return FalseVal;
if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
true,
MaxRecurse) == FalseVal ||
simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
true,
MaxRecurse) == FalseVal)
return FalseVal;
}
return nullptr;
}
static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
const SimplifyQuery &Q) {
FCmpInst::Predicate Pred;
if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
!match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
return nullptr;
bool HasNoSignedZeros =
Q.CxtI && isa<FPMathOperator>(Q.CxtI) && Q.CxtI->hasNoSignedZeros();
const APFloat *C;
if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
(match(F, m_APFloat(C)) && C->isNonZero())) {
if (Pred == FCmpInst::FCMP_OEQ)
return F;
if (Pred == FCmpInst::FCMP_UNE)
return T;
}
return nullptr;
}
static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (auto *CondC = dyn_cast<Constant>(Cond)) {
if (auto *TrueC = dyn_cast<Constant>(TrueVal))
if (auto *FalseC = dyn_cast<Constant>(FalseVal))
return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
if (isa<PoisonValue>(CondC))
return PoisonValue::get(TrueVal->getType());
if (Q.isUndefValue(CondC))
return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
if (match(CondC, m_One()))
return TrueVal;
if (match(CondC, m_Zero()))
return FalseVal;
}
assert(Cond->getType()->isIntOrIntVectorTy(1) &&
"Select must have bool or bool vector condition");
assert(TrueVal->getType() == FalseVal->getType() &&
"Select must have same types for true/false ops");
if (Cond->getType() == TrueVal->getType()) {
if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
return Cond;
Value *X, *Y;
if (match(FalseVal, m_ZeroInt())) {
if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
return X;
if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
return X;
}
}
if (TrueVal == FalseVal)
return TrueVal;
if (isa<PoisonValue>(TrueVal) ||
(Q.isUndefValue(TrueVal) &&
isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
return FalseVal;
if (isa<PoisonValue>(FalseVal) ||
(Q.isUndefValue(FalseVal) &&
isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
return TrueVal;
Constant *TrueC, *FalseC;
if (isa<FixedVectorType>(TrueVal->getType()) &&
match(TrueVal, m_Constant(TrueC)) &&
match(FalseVal, m_Constant(FalseC))) {
unsigned NumElts =
cast<FixedVectorType>(TrueC->getType())->getNumElements();
SmallVector<Constant *, 16> NewC;
for (unsigned i = 0; i != NumElts; ++i) {
Constant *TEltC = TrueC->getAggregateElement(i);
Constant *FEltC = FalseC->getAggregateElement(i);
if (!TEltC || !FEltC)
break;
if (TEltC == FEltC)
NewC.push_back(TEltC);
else if (isa<PoisonValue>(TEltC) ||
(Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
NewC.push_back(FEltC);
else if (isa<PoisonValue>(FEltC) ||
(Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
NewC.push_back(TEltC);
else
break;
}
if (NewC.size() == NumElts)
return ConstantVector::get(NewC);
}
if (Value *V =
simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
return V;
if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
return V;
if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
return V;
Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
if (Imp)
return *Imp ? TrueVal : FalseVal;
return nullptr;
}
Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
const SimplifyQuery &Q) {
return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
}
static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
ArrayRef<Value *> Indices, bool InBounds,
const SimplifyQuery &Q, unsigned) {
unsigned AS =
cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
if (Indices.empty())
return Ptr;
Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
Type *GEPTy = PointerType::get(LastType, AS);
if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
GEPTy = VectorType::get(GEPTy, VT->getElementCount());
else {
for (Value *Op : Indices) {
if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
GEPTy = VectorType::get(GEPTy, VT->getElementCount());
break;
}
}
}
if (Ptr->getType()->getScalarType()->isOpaquePointerTy() &&
Ptr->getType() == GEPTy &&
all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
return Ptr;
if (isa<PoisonValue>(Ptr) ||
any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
return PoisonValue::get(GEPTy);
if (Q.isUndefValue(Ptr))
return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
bool IsScalableVec =
isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
return isa<ScalableVectorType>(V->getType());
});
if (Indices.size() == 1) {
if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
return Ptr;
Type *Ty = SrcTy;
if (!IsScalableVec && Ty->isSized()) {
Value *P;
uint64_t C;
uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
return Ptr;
if (Indices[0]->getType()->getScalarSizeInBits() ==
Q.DL.getPointerSizeInBits(AS)) {
auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
return P->getType() == GEPTy &&
getUnderlyingObject(P) == getUnderlyingObject(Ptr);
};
if (TyAllocSize == 1 &&
match(Indices[0],
m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
CanSimplify())
return P;
if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
m_PtrToInt(m_Specific(Ptr))),
m_ConstantInt(C))) &&
TyAllocSize == 1ULL << C && CanSimplify())
return P;
if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
m_PtrToInt(m_Specific(Ptr))),
m_SpecificInt(TyAllocSize))) &&
CanSimplify())
return P;
}
}
}
if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
all_of(Indices.drop_back(1),
[](Value *Idx) { return match(Idx, m_Zero()); })) {
unsigned IdxWidth =
Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
APInt BasePtrOffset(IdxWidth, 0);
Value *StrippedBasePtr =
Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
if (match(Indices.back(),
m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
!BasePtrOffset.isZero()) {
auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
return ConstantExpr::getIntToPtr(CI, GEPTy);
}
if (match(Indices.back(),
m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
!BasePtrOffset.isOne()) {
auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
return ConstantExpr::getIntToPtr(CI, GEPTy);
}
}
}
if (!isa<Constant>(Ptr) ||
!all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
return nullptr;
auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
InBounds);
return ConstantFoldConstant(CE, Q.DL);
}
Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
bool InBounds, const SimplifyQuery &Q) {
return ::simplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
}
static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
ArrayRef<unsigned> Idxs,
const SimplifyQuery &Q, unsigned) {
if (Constant *CAgg = dyn_cast<Constant>(Agg))
if (Constant *CVal = dyn_cast<Constant>(Val))
return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
if (Q.isUndefValue(Val))
return Agg;
if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
if (EV->getAggregateOperand()->getType() == Agg->getType() &&
EV->getIndices() == Idxs) {
if (Q.isUndefValue(Agg))
return EV->getAggregateOperand();
if (Agg == EV->getAggregateOperand())
return Agg;
}
return nullptr;
}
Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
ArrayRef<unsigned> Idxs,
const SimplifyQuery &Q) {
return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
}
Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
const SimplifyQuery &Q) {
auto *VecC = dyn_cast<Constant>(Vec);
auto *ValC = dyn_cast<Constant>(Val);
auto *IdxC = dyn_cast<Constant>(Idx);
if (VecC && ValC && IdxC)
return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
if (isa<FixedVectorType>(Vec->getType()) &&
CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
return PoisonValue::get(Vec->getType());
}
if (Q.isUndefValue(Idx))
return PoisonValue::get(Vec->getType());
if (isa<PoisonValue>(Val) ||
(Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
return Vec;
if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
return Vec;
return nullptr;
}
static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
const SimplifyQuery &, unsigned) {
if (auto *CAgg = dyn_cast<Constant>(Agg))
return ConstantFoldExtractValueInstruction(CAgg, Idxs);
unsigned NumIdxs = Idxs.size();
for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
unsigned NumInsertValueIdxs = InsertValueIdxs.size();
unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
Idxs.slice(0, NumCommonIdxs)) {
if (NumIdxs == NumInsertValueIdxs)
return IVI->getInsertedValueOperand();
break;
}
}
return nullptr;
}
Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
const SimplifyQuery &Q) {
return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
}
static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
const SimplifyQuery &Q, unsigned) {
auto *VecVTy = cast<VectorType>(Vec->getType());
if (auto *CVec = dyn_cast<Constant>(Vec)) {
if (auto *CIdx = dyn_cast<Constant>(Idx))
return ConstantExpr::getExtractElement(CVec, CIdx);
if (Q.isUndefValue(Vec))
return UndefValue::get(VecVTy->getElementType());
}
if (Q.isUndefValue(Idx))
return PoisonValue::get(VecVTy->getElementType());
if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
return PoisonValue::get(VecVTy->getElementType());
if (IdxC->getValue().ult(MinNumElts))
if (auto *Splat = getSplatValue(Vec))
return Splat;
if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
return Elt;
} else {
if (Value *Splat = getSplatValue(Vec))
return Splat;
}
return nullptr;
}
Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
const SimplifyQuery &Q) {
return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
}
static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
const SimplifyQuery &Q) {
Value *CommonValue = nullptr;
bool HasUndefInput = false;
for (Value *Incoming : IncomingValues) {
if (Incoming == PN)
continue;
if (Q.isUndefValue(Incoming)) {
HasUndefInput = true;
continue;
}
if (CommonValue && Incoming != CommonValue)
return nullptr; CommonValue = Incoming;
}
if (!CommonValue)
return UndefValue::get(PN->getType());
if (HasUndefInput) {
return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
}
return CommonValue;
}
static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (auto *C = dyn_cast<Constant>(Op))
return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
if (auto *CI = dyn_cast<CastInst>(Op)) {
auto *Src = CI->getOperand(0);
Type *SrcTy = Src->getType();
Type *MidTy = CI->getType();
Type *DstTy = Ty;
if (Src->getType() == Ty) {
auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
Type *SrcIntPtrTy =
SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
Type *MidIntPtrTy =
MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
Type *DstIntPtrTy =
DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
SrcIntPtrTy, MidIntPtrTy,
DstIntPtrTy) == Instruction::BitCast)
return Src;
}
}
if (CastOpc == Instruction::BitCast)
if (Op->getType() == Ty)
return Op;
return nullptr;
}
Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
const SimplifyQuery &Q) {
return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
}
static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
int MaskVal, Value *RootVec,
unsigned MaxRecurse) {
if (!MaxRecurse--)
return nullptr;
if (MaskVal == -1)
return nullptr;
int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
int RootElt = MaskVal;
Value *SourceOp = Op0;
if (MaskVal >= InVecNumElts) {
RootElt = MaskVal - InVecNumElts;
SourceOp = Op1;
}
if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
return foldIdentityShuffles(
DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
}
if (!RootVec)
RootVec = SourceOp;
if (RootVec != SourceOp)
return nullptr;
if (RootElt != DestElt)
return nullptr;
return RootVec;
}
static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
ArrayRef<int> Mask, Type *RetTy,
const SimplifyQuery &Q,
unsigned MaxRecurse) {
if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
return UndefValue::get(RetTy);
auto *InVecTy = cast<VectorType>(Op0->getType());
unsigned MaskNumElts = Mask.size();
ElementCount InVecEltCount = InVecTy->getElementCount();
bool Scalable = InVecEltCount.isScalable();
SmallVector<int, 32> Indices;
Indices.assign(Mask.begin(), Mask.end());
if (!Scalable) {
bool MaskSelects0 = false, MaskSelects1 = false;
unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
for (unsigned i = 0; i != MaskNumElts; ++i) {
if (Indices[i] == -1)
continue;
if ((unsigned)Indices[i] < InVecNumElts)
MaskSelects0 = true;
else
MaskSelects1 = true;
}
if (!MaskSelects0)
Op0 = PoisonValue::get(InVecTy);
if (!MaskSelects1)
Op1 = PoisonValue::get(InVecTy);
}
auto *Op0Const = dyn_cast<Constant>(Op0);
auto *Op1Const = dyn_cast<Constant>(Op1);
if (Op0Const && Op1Const)
return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
if (!Scalable && Op0Const && !Op1Const) {
std::swap(Op0, Op1);
ShuffleVectorInst::commuteShuffleMask(Indices,
InVecEltCount.getKnownMinValue());
}
Constant *C;
ConstantInt *IndexC;
if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
m_ConstantInt(IndexC)))) {
int InsertIndex = IndexC->getZExtValue();
if (all_of(Indices, [InsertIndex](int MaskElt) {
return MaskElt == InsertIndex || MaskElt == -1;
})) {
assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
SmallVector<Constant *, 16> VecC(MaskNumElts, C);
for (unsigned i = 0; i != MaskNumElts; ++i)
if (Indices[i] == -1)
VecC[i] = UndefValue::get(C->getType());
return ConstantVector::get(VecC);
}
}
if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
is_splat(OpShuf->getShuffleMask()))
return Op0;
if (Scalable)
return nullptr;
if (is_contained(Indices, -1))
return nullptr;
Value *RootVec = nullptr;
for (unsigned i = 0; i != MaskNumElts; ++i) {
RootVec =
foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
if (!RootVec || RootVec->getType() != RetTy)
return nullptr;
}
return RootVec;
}
Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
ArrayRef<int> Mask, Type *RetTy,
const SimplifyQuery &Q) {
return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
}
static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
const SimplifyQuery &Q) {
if (auto *C = dyn_cast<Constant>(Op))
return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
return nullptr;
}
static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
return C;
Value *X;
if (match(Op, m_FNeg(m_Value(X))))
return X;
return nullptr;
}
Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
const SimplifyQuery &Q) {
return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
}
static Constant *propagateNaN(Constant *In) {
if (!In->isNaN())
return ConstantFP::getNaN(In->getType());
return In;
}
static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
return PoisonValue::get(Ops[0]->getType());
for (Value *V : Ops) {
bool IsNan = match(V, m_NaN());
bool IsInf = match(V, m_Inf());
bool IsUndef = Q.isUndefValue(V);
if (FMF.noNaNs() && (IsNan || IsUndef))
return PoisonValue::get(V->getType());
if (FMF.noInfs() && (IsInf || IsUndef))
return PoisonValue::get(V->getType());
if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
if (IsUndef || IsNan)
return propagateNaN(cast<Constant>(V));
} else if (ExBehavior != fp::ebStrict) {
if (IsNan)
return propagateNaN(cast<Constant>(V));
}
}
return nullptr;
}
static Value *
simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned MaxRecurse,
fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
if (isDefaultFPEnvironment(ExBehavior, Rounding))
if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
return C;
if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
return C;
if (canIgnoreSNaN(ExBehavior, FMF) &&
(!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
FMF.noSignedZeros()))
if (match(Op1, m_NegZeroFP()))
return Op0;
if (canIgnoreSNaN(ExBehavior, FMF))
if (match(Op1, m_PosZeroFP()) &&
(FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
return Op0;
if (!isDefaultFPEnvironment(ExBehavior, Rounding))
return nullptr;
if (FMF.noNaNs()) {
if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
return ConstantFP::getNullValue(Op0->getType());
if (match(Op0, m_FNeg(m_Specific(Op1))) ||
match(Op1, m_FNeg(m_Specific(Op0))))
return ConstantFP::getNullValue(Op0->getType());
}
Value *X;
if (FMF.noSignedZeros() && FMF.allowReassoc() &&
(match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
return X;
return nullptr;
}
static Value *
simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned MaxRecurse,
fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
if (isDefaultFPEnvironment(ExBehavior, Rounding))
if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
return C;
if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
return C;
if (canIgnoreSNaN(ExBehavior, FMF) &&
(!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
FMF.noSignedZeros()))
if (match(Op1, m_PosZeroFP()))
return Op0;
if (canIgnoreSNaN(ExBehavior, FMF))
if (match(Op1, m_NegZeroFP()) &&
(FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
return Op0;
Value *X;
if (canIgnoreSNaN(ExBehavior, FMF))
if (match(Op0, m_NegZeroFP()) && match(Op1, m_FNeg(m_Value(X))))
return X;
if (!isDefaultFPEnvironment(ExBehavior, Rounding))
return nullptr;
if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
(match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
match(Op1, m_FNeg(m_Value(X)))))
return X;
if (FMF.noNaNs() && Op0 == Op1)
return Constant::getNullValue(Op0->getType());
if (FMF.noSignedZeros() && FMF.allowReassoc() &&
(match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
return X;
return nullptr;
}
static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned MaxRecurse,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
return C;
if (!isDefaultFPEnvironment(ExBehavior, Rounding))
return nullptr;
if (match(Op1, m_FPOne()))
return Op0;
if (match(Op0, m_FPOne()))
return Op1;
if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
return ConstantFP::getNullValue(Op0->getType());
if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
return ConstantFP::getNullValue(Op1->getType());
Value *X;
if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
FMF.noNaNs() && FMF.noSignedZeros())
return X;
return nullptr;
}
static Value *
simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned MaxRecurse,
fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
if (isDefaultFPEnvironment(ExBehavior, Rounding))
if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
return C;
return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
}
Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
Rounding);
}
Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
Rounding);
}
Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
Rounding);
}
Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
Rounding);
}
static Value *
simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned,
fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
if (isDefaultFPEnvironment(ExBehavior, Rounding))
if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
return C;
if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
return C;
if (!isDefaultFPEnvironment(ExBehavior, Rounding))
return nullptr;
if (match(Op1, m_FPOne()))
return Op0;
if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
return ConstantFP::getNullValue(Op0->getType());
if (FMF.noNaNs()) {
if (Op0 == Op1)
return ConstantFP::get(Op0->getType(), 1.0);
Value *X;
if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
return X;
if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
match(Op1, m_FNegNSZ(m_Specific(Op0))))
return ConstantFP::get(Op0->getType(), -1.0);
}
return nullptr;
}
Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
Rounding);
}
static Value *
simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q, unsigned,
fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
if (isDefaultFPEnvironment(ExBehavior, Rounding))
if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
return C;
if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
return C;
if (!isDefaultFPEnvironment(ExBehavior, Rounding))
return nullptr;
if (FMF.noNaNs()) {
if (match(Op0, m_PosZeroFP()))
return ConstantFP::getNullValue(Op0->getType());
if (match(Op0, m_NegZeroFP()))
return ConstantFP::getNegativeZero(Op0->getType());
}
return nullptr;
}
Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
const SimplifyQuery &Q,
fp::ExceptionBehavior ExBehavior,
RoundingMode Rounding) {
return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
Rounding);
}
static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
unsigned MaxRecurse) {
switch (Opcode) {
case Instruction::FNeg:
return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
default:
llvm_unreachable("Unexpected opcode");
}
}
static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
const FastMathFlags &FMF, const SimplifyQuery &Q,
unsigned MaxRecurse) {
switch (Opcode) {
case Instruction::FNeg:
return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
default:
return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
}
}
Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
}
Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
const SimplifyQuery &Q) {
return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
}
static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
const SimplifyQuery &Q, unsigned MaxRecurse) {
switch (Opcode) {
case Instruction::Add:
return simplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
case Instruction::Sub:
return simplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
case Instruction::Mul:
return simplifyMulInst(LHS, RHS, Q, MaxRecurse);
case Instruction::SDiv:
return simplifySDivInst(LHS, RHS, Q, MaxRecurse);
case Instruction::UDiv:
return simplifyUDivInst(LHS, RHS, Q, MaxRecurse);
case Instruction::SRem:
return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
case Instruction::URem:
return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
case Instruction::Shl:
return simplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
case Instruction::LShr:
return simplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
case Instruction::AShr:
return simplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
case Instruction::And:
return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
case Instruction::Or:
return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
case Instruction::Xor:
return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
case Instruction::FAdd:
return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
case Instruction::FSub:
return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
case Instruction::FMul:
return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
case Instruction::FDiv:
return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
case Instruction::FRem:
return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
default:
llvm_unreachable("Unexpected opcode");
}
}
static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
const FastMathFlags &FMF, const SimplifyQuery &Q,
unsigned MaxRecurse) {
switch (Opcode) {
case Instruction::FAdd:
return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
case Instruction::FSub:
return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
case Instruction::FMul:
return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
case Instruction::FDiv:
return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
default:
return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
}
}
Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
const SimplifyQuery &Q) {
return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
}
Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
FastMathFlags FMF, const SimplifyQuery &Q) {
return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
}
static Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
const SimplifyQuery &Q, unsigned MaxRecurse) {
if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
}
Value *llvm::simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
const SimplifyQuery &Q) {
return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
}
static bool isIdempotent(Intrinsic::ID ID) {
switch (ID) {
default:
return false;
case Intrinsic::fabs:
case Intrinsic::floor:
case Intrinsic::ceil:
case Intrinsic::trunc:
case Intrinsic::rint:
case Intrinsic::nearbyint:
case Intrinsic::round:
case Intrinsic::roundeven:
case Intrinsic::canonicalize:
return true;
}
}
static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
const DataLayout &DL) {
GlobalValue *PtrSym;
APInt PtrOffset;
if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
return nullptr;
Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
Type *Int32PtrTy = Int32Ty->getPointerTo();
Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
return nullptr;
uint64_t OffsetInt = OffsetConstInt->getSExtValue();
if (OffsetInt % 4 != 0)
return nullptr;
Constant *C = ConstantExpr::getGetElementPtr(
Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
ConstantInt::get(Int64Ty, OffsetInt / 4));
Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
if (!Loaded)
return nullptr;
auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
if (!LoadedCE)
return nullptr;
if (LoadedCE->getOpcode() == Instruction::Trunc) {
LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
if (!LoadedCE)
return nullptr;
}
if (LoadedCE->getOpcode() != Instruction::Sub)
return nullptr;
auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
return nullptr;
auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
Constant *LoadedRHS = LoadedCE->getOperand(1);
GlobalValue *LoadedRHSSym;
APInt LoadedRHSOffset;
if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
DL) ||
PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
return nullptr;
return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
}
static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
const SimplifyQuery &Q) {
Intrinsic::ID IID = F->getIntrinsicID();
if (isIdempotent(IID))
if (auto *II = dyn_cast<IntrinsicInst>(Op0))
if (II->getIntrinsicID() == IID)
return II;
Value *X;
switch (IID) {
case Intrinsic::fabs:
if (SignBitMustBeZero(Op0, Q.TLI))
return Op0;
break;
case Intrinsic::bswap:
if (match(Op0, m_BSwap(m_Value(X))))
return X;
break;
case Intrinsic::bitreverse:
if (match(Op0, m_BitReverse(m_Value(X))))
return X;
break;
case Intrinsic::ctpop: {
unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
return Op0;
break;
}
case Intrinsic::exp:
if (Q.CxtI->hasAllowReassoc() &&
match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X))))
return X;
break;
case Intrinsic::exp2:
if (Q.CxtI->hasAllowReassoc() &&
match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
return X;
break;
case Intrinsic::log:
if (Q.CxtI->hasAllowReassoc() &&
match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
return X;
break;
case Intrinsic::log2:
if (Q.CxtI->hasAllowReassoc() &&
(match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
match(Op0,
m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), m_Value(X)))))
return X;
break;
case Intrinsic::log10:
if (Q.CxtI->hasAllowReassoc() &&
match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), m_Value(X))))
return X;
break;
case Intrinsic::floor:
case Intrinsic::trunc:
case Intrinsic::ceil:
case Intrinsic::round:
case Intrinsic::roundeven:
case Intrinsic::nearbyint:
case Intrinsic::rint: {
if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
return Op0;
break;
}
case Intrinsic::experimental_vector_reverse:
if (match(Op0,
m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X))))
return X;
if (isSplatValue(Op0))
return Op0;
break;
default:
break;
}
return nullptr;
}
static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
Value *X, *Y;
if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
return nullptr;
auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
if (!MM0)
return nullptr;
Intrinsic::ID IID0 = MM0->getIntrinsicID();
if (Op1 == X || Op1 == Y ||
match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
if (IID0 == IID)
return MM0;
if (IID0 == getInverseMinMaxIntrinsic(IID))
return Op1;
}
return nullptr;
}
static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
const SimplifyQuery &Q) {
Intrinsic::ID IID = F->getIntrinsicID();
Type *ReturnType = F->getReturnType();
unsigned BitWidth = ReturnType->getScalarSizeInBits();
switch (IID) {
case Intrinsic::abs:
if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
return Op0;
break;
case Intrinsic::cttz: {
Value *X;
if (match(Op0, m_Shl(m_One(), m_Value(X))))
return X;
break;
}
case Intrinsic::ctlz: {
Value *X;
if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
return X;
if (match(Op0, m_AShr(m_Negative(), m_Value())))
return Constant::getNullValue(ReturnType);
break;
}
case Intrinsic::smax:
case Intrinsic::smin:
case Intrinsic::umax:
case Intrinsic::umin: {
if (Op0 == Op1)
return Op0;
if (isa<Constant>(Op0))
std::swap(Op0, Op1);
if (Q.isUndefValue(Op1))
return ConstantInt::get(
ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
const APInt *C;
if (match(Op1, m_APIntAllowUndef(C))) {
if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
return ConstantInt::get(ReturnType, *C);
if (*C == MinMaxIntrinsic::getSaturationPoint(
getInverseMinMaxIntrinsic(IID), BitWidth))
return Op0;
auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
const APInt *InnerC;
if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
ICmpInst::compare(*InnerC, *C,
ICmpInst::getNonStrictPredicate(
MinMaxIntrinsic::getPredicate(IID))))
return Op0;
}
}
if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
return V;
if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
return V;
ICmpInst::Predicate Pred =
ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
return Op0;
if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
return Op1;
if (Optional<bool> Imp =
isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
return *Imp ? Op0 : Op1;
if (Optional<bool> Imp =
isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
return *Imp ? Op1 : Op0;
break;
}
case Intrinsic::usub_with_overflow:
case Intrinsic::ssub_with_overflow:
if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
return Constant::getNullValue(ReturnType);
break;
case Intrinsic::uadd_with_overflow:
case Intrinsic::sadd_with_overflow:
if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
return ConstantStruct::get(
cast<StructType>(ReturnType),
{Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
Constant::getNullValue(ReturnType->getStructElementType(1))});
}
break;
case Intrinsic::umul_with_overflow:
case Intrinsic::smul_with_overflow:
if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
return Constant::getNullValue(ReturnType);
if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
return Constant::getNullValue(ReturnType);
break;
case Intrinsic::uadd_sat:
if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
return Constant::getAllOnesValue(ReturnType);
LLVM_FALLTHROUGH;
case Intrinsic::sadd_sat:
if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
return Constant::getAllOnesValue(ReturnType);
if (match(Op1, m_Zero()))
return Op0;
if (match(Op0, m_Zero()))
return Op1;
break;
case Intrinsic::usub_sat:
if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
return Constant::getNullValue(ReturnType);
LLVM_FALLTHROUGH;
case Intrinsic::ssub_sat:
if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
return Constant::getNullValue(ReturnType);
if (match(Op1, m_Zero()))
return Op0;
break;
case Intrinsic::load_relative:
if (auto *C0 = dyn_cast<Constant>(Op0))
if (auto *C1 = dyn_cast<Constant>(Op1))
return simplifyRelativeLoad(C0, C1, Q.DL);
break;
case Intrinsic::powi:
if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
if (Power->isZero())
return ConstantFP::get(Op0->getType(), 1.0);
if (Power->isOne())
return Op0;
}
break;
case Intrinsic::copysign:
if (Op0 == Op1)
return Op0;
if (match(Op0, m_FNeg(m_Specific(Op1))) ||
match(Op1, m_FNeg(m_Specific(Op0))))
return Op1;
break;
case Intrinsic::maxnum:
case Intrinsic::minnum:
case Intrinsic::maximum:
case Intrinsic::minimum: {
if (Op0 == Op1)
return Op0;
if (isa<Constant>(Op0))
std::swap(Op0, Op1);
if (Q.isUndefValue(Op1))
return Op0;
bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
if (match(Op1, m_NaN()))
return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
const APFloat *C;
if (match(Op1, m_APFloat(C)) &&
(C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
return ConstantFP::get(ReturnType, *C);
if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
return Op0;
}
if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
if (M0->getIntrinsicID() == IID &&
(M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
return Op0;
if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
if (M1->getIntrinsicID() == IID &&
(M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
return Op1;
break;
}
case Intrinsic::vector_extract: {
Type *ReturnType = F->getReturnType();
unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
Value *X = nullptr;
if (match(Op0, m_Intrinsic<Intrinsic::vector_insert>(m_Value(), m_Value(X),
m_Zero())) &&
IdxN == 0 && X->getType() == ReturnType)
return X;
break;
}
default:
break;
}
return nullptr;
}
static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
unsigned NumOperands = Call->arg_size();
Function *F = cast<Function>(Call->getCalledFunction());
Intrinsic::ID IID = F->getIntrinsicID();
if (!NumOperands) {
switch (IID) {
case Intrinsic::vscale: {
if (!Call->getParent() || !Call->getParent()->getParent())
return nullptr;
auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
if (!Attr.isValid())
return nullptr;
unsigned VScaleMin = Attr.getVScaleRangeMin();
Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
if (VScaleMax && VScaleMin == VScaleMax)
return ConstantInt::get(F->getReturnType(), VScaleMin);
return nullptr;
}
default:
return nullptr;
}
}
if (NumOperands == 1)
return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
if (NumOperands == 2)
return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
Call->getArgOperand(1), Q);
switch (IID) {
case Intrinsic::masked_load:
case Intrinsic::masked_gather: {
Value *MaskArg = Call->getArgOperand(2);
Value *PassthruArg = Call->getArgOperand(3);
if (maskIsAllZeroOrUndef(MaskArg))
return PassthruArg;
return nullptr;
}
case Intrinsic::fshl:
case Intrinsic::fshr: {
Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
*ShAmtArg = Call->getArgOperand(2);
if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
return UndefValue::get(F->getReturnType());
if (Q.isUndefValue(ShAmtArg))
return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
const APInt *ShAmtC;
if (match(ShAmtArg, m_APInt(ShAmtC))) {
APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
if (ShAmtC->urem(BitWidth).isZero())
return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
}
if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
return ConstantInt::getNullValue(F->getReturnType());
if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
return ConstantInt::getAllOnesValue(F->getReturnType());
return nullptr;
}
case Intrinsic::experimental_constrained_fma: {
Value *Op0 = Call->getArgOperand(0);
Value *Op1 = Call->getArgOperand(1);
Value *Op2 = Call->getArgOperand(2);
auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q,
FPI->getExceptionBehavior().value(),
FPI->getRoundingMode().value()))
return V;
return nullptr;
}
case Intrinsic::fma:
case Intrinsic::fmuladd: {
Value *Op0 = Call->getArgOperand(0);
Value *Op1 = Call->getArgOperand(1);
Value *Op2 = Call->getArgOperand(2);
if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
RoundingMode::NearestTiesToEven))
return V;
return nullptr;
}
case Intrinsic::smul_fix:
case Intrinsic::smul_fix_sat: {
Value *Op0 = Call->getArgOperand(0);
Value *Op1 = Call->getArgOperand(1);
Value *Op2 = Call->getArgOperand(2);
Type *ReturnType = F->getReturnType();
if (isa<Constant>(Op0))
std::swap(Op0, Op1);
if (match(Op1, m_Zero()))
return Constant::getNullValue(ReturnType);
if (Q.isUndefValue(Op1))
return Constant::getNullValue(ReturnType);
APInt ScaledOne =
APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
cast<ConstantInt>(Op2)->getZExtValue());
if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
return Op0;
return nullptr;
}
case Intrinsic::vector_insert: {
Value *Vec = Call->getArgOperand(0);
Value *SubVec = Call->getArgOperand(1);
Value *Idx = Call->getArgOperand(2);
Type *ReturnType = F->getReturnType();
unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
Value *X = nullptr;
if (match(SubVec,
m_Intrinsic<Intrinsic::vector_extract>(m_Value(X), m_Zero())) &&
(Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
X->getType() == ReturnType)
return X;
return nullptr;
}
case Intrinsic::experimental_constrained_fadd: {
auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
return simplifyFAddInst(
FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
Q, FPI->getExceptionBehavior().value(), FPI->getRoundingMode().value());
}
case Intrinsic::experimental_constrained_fsub: {
auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
return simplifyFSubInst(
FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
Q, FPI->getExceptionBehavior().value(), FPI->getRoundingMode().value());
}
case Intrinsic::experimental_constrained_fmul: {
auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
return simplifyFMulInst(
FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
Q, FPI->getExceptionBehavior().value(), FPI->getRoundingMode().value());
}
case Intrinsic::experimental_constrained_fdiv: {
auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
return simplifyFDivInst(
FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
Q, FPI->getExceptionBehavior().value(), FPI->getRoundingMode().value());
}
case Intrinsic::experimental_constrained_frem: {
auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
return simplifyFRemInst(
FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
Q, FPI->getExceptionBehavior().value(), FPI->getRoundingMode().value());
}
default:
return nullptr;
}
}
static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
auto *F = dyn_cast<Function>(Call->getCalledOperand());
if (!F || !canConstantFoldCallTo(Call, F))
return nullptr;
SmallVector<Constant *, 4> ConstantArgs;
unsigned NumArgs = Call->arg_size();
ConstantArgs.reserve(NumArgs);
for (auto &Arg : Call->args()) {
Constant *C = dyn_cast<Constant>(&Arg);
if (!C) {
if (isa<MetadataAsValue>(Arg.get()))
continue;
return nullptr;
}
ConstantArgs.push_back(C);
}
return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
}
Value *llvm::simplifyCall(CallBase *Call, const SimplifyQuery &Q) {
if (Call->isMustTailCall())
return nullptr;
Value *Callee = Call->getCalledOperand();
if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
return PoisonValue::get(Call->getType());
if (Value *V = tryConstantFoldCall(Call, Q))
return V;
auto *F = dyn_cast<Function>(Callee);
if (F && F->isIntrinsic())
if (Value *Ret = simplifyIntrinsic(Call, Q))
return Ret;
return nullptr;
}
Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
assert(isa<ConstrainedFPIntrinsic>(Call));
if (Value *V = tryConstantFoldCall(Call, Q))
return V;
if (Value *Ret = simplifyIntrinsic(Call, Q))
return Ret;
return nullptr;
}
static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
return Op0;
return nullptr;
}
Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
return ::simplifyFreezeInst(Op0, Q);
}
static Value *simplifyLoadInst(LoadInst *LI, Value *PtrOp,
const SimplifyQuery &Q) {
if (LI->isVolatile())
return nullptr;
APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
auto *PtrOpC = dyn_cast<Constant>(PtrOp);
if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
Q.DL, Offset, true,
true);
Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
PtrOpC = dyn_cast<Constant>(PtrOp);
}
if (PtrOpC)
return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
return nullptr;
}
static Value *simplifyInstructionWithOperands(Instruction *I,
ArrayRef<Value *> NewOps,
const SimplifyQuery &SQ,
OptimizationRemarkEmitter *ORE) {
const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
Value *Result = nullptr;
switch (I->getOpcode()) {
default:
if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
SmallVector<Constant *, 8> NewConstOps(NewOps.size());
transform(NewOps, NewConstOps.begin(),
[](Value *V) { return cast<Constant>(V); });
Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
}
break;
case Instruction::FNeg:
Result = simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
break;
case Instruction::FAdd:
Result = simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
break;
case Instruction::Add:
Result = simplifyAddInst(
NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
break;
case Instruction::FSub:
Result = simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
break;
case Instruction::Sub:
Result = simplifySubInst(
NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
break;
case Instruction::FMul:
Result = simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
break;
case Instruction::Mul:
Result = simplifyMulInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::SDiv:
Result = simplifySDivInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::UDiv:
Result = simplifyUDivInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::FDiv:
Result = simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
break;
case Instruction::SRem:
Result = simplifySRemInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::URem:
Result = simplifyURemInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::FRem:
Result = simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
break;
case Instruction::Shl:
Result = simplifyShlInst(
NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
break;
case Instruction::LShr:
Result = simplifyLShrInst(NewOps[0], NewOps[1],
Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
break;
case Instruction::AShr:
Result = simplifyAShrInst(NewOps[0], NewOps[1],
Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
break;
case Instruction::And:
Result = simplifyAndInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::Or:
Result = simplifyOrInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::Xor:
Result = simplifyXorInst(NewOps[0], NewOps[1], Q);
break;
case Instruction::ICmp:
Result = simplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
NewOps[1], Q);
break;
case Instruction::FCmp:
Result = simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
NewOps[1], I->getFastMathFlags(), Q);
break;
case Instruction::Select:
Result = simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
break;
case Instruction::GetElementPtr: {
auto *GEPI = cast<GetElementPtrInst>(I);
Result =
simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
makeArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
break;
}
case Instruction::InsertValue: {
InsertValueInst *IV = cast<InsertValueInst>(I);
Result = simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
break;
}
case Instruction::InsertElement: {
Result = simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
break;
}
case Instruction::ExtractValue: {
auto *EVI = cast<ExtractValueInst>(I);
Result = simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
break;
}
case Instruction::ExtractElement: {
Result = simplifyExtractElementInst(NewOps[0], NewOps[1], Q);
break;
}
case Instruction::ShuffleVector: {
auto *SVI = cast<ShuffleVectorInst>(I);
Result = simplifyShuffleVectorInst(
NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q);
break;
}
case Instruction::PHI:
Result = simplifyPHINode(cast<PHINode>(I), NewOps, Q);
break;
case Instruction::Call: {
Result = simplifyCall(cast<CallInst>(I), Q);
break;
}
case Instruction::Freeze:
Result = llvm::simplifyFreezeInst(NewOps[0], Q);
break;
#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
#include "llvm/IR/Instruction.def"
#undef HANDLE_CAST_INST
Result = simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
break;
case Instruction::Alloca:
Result = nullptr;
break;
case Instruction::Load:
Result = simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
break;
}
return Result == I ? UndefValue::get(I->getType()) : Result;
}
Value *llvm::simplifyInstructionWithOperands(Instruction *I,
ArrayRef<Value *> NewOps,
const SimplifyQuery &SQ,
OptimizationRemarkEmitter *ORE) {
assert(NewOps.size() == I->getNumOperands() &&
"Number of operands should match the instruction!");
return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
}
Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
OptimizationRemarkEmitter *ORE) {
SmallVector<Value *, 8> Ops(I->operands());
return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
}
static bool replaceAndRecursivelySimplifyImpl(
Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
const DominatorTree *DT, AssumptionCache *AC,
SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
bool Simplified = false;
SmallSetVector<Instruction *, 8> Worklist;
const DataLayout &DL = I->getModule()->getDataLayout();
if (SimpleV) {
for (User *U : I->users())
if (U != I)
Worklist.insert(cast<Instruction>(U));
I->replaceAllUsesWith(SimpleV);
if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
!I->mayHaveSideEffects())
I->eraseFromParent();
} else {
Worklist.insert(I);
}
for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
I = Worklist[Idx];
SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
if (!SimpleV) {
if (UnsimplifiedUsers)
UnsimplifiedUsers->insert(I);
continue;
}
Simplified = true;
for (User *U : I->users())
Worklist.insert(cast<Instruction>(U));
I->replaceAllUsesWith(SimpleV);
if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
!I->mayHaveSideEffects())
I->eraseFromParent();
}
return Simplified;
}
bool llvm::replaceAndRecursivelySimplify(
Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
const DominatorTree *DT, AssumptionCache *AC,
SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
assert(SimpleV && "Must provide a simplified value.");
return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
UnsimplifiedUsers);
}
namespace llvm {
const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
return {F.getParent()->getDataLayout(), TLI, DT, AC};
}
const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
const DataLayout &DL) {
return {DL, &AR.TLI, &AR.DT, &AR.AC};
}
template <class T, class... TArgs>
const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
Function &F) {
auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
return {F.getParent()->getDataLayout(), TLI, DT, AC};
}
template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
Function &);
}
void InstSimplifyFolder::anchor() {}