#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/Local.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_TYPE "sccp"
STATISTIC(NumInstRemoved, "Number of instructions removed");
STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
namespace {
class LatticeVal {
enum LatticeValueTy {
undefined,
constant,
forcedconstant,
overdefined
};
PointerIntPair<Constant *, 2, LatticeValueTy> Val;
LatticeValueTy getLatticeValue() const {
return Val.getInt();
}
public:
LatticeVal() : Val(nullptr, undefined) {}
bool isUndefined() const { return getLatticeValue() == undefined; }
bool isConstant() const {
return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
}
bool isOverdefined() const { return getLatticeValue() == overdefined; }
Constant *getConstant() const {
assert(isConstant() && "Cannot get the constant of a non-constant!");
return Val.getPointer();
}
bool markOverdefined() {
if (isOverdefined())
return false;
Val.setInt(overdefined);
return true;
}
bool markConstant(Constant *V) {
if (getLatticeValue() == constant) { assert(getConstant() == V && "Marking constant with different value");
return false;
}
if (isUndefined()) {
Val.setInt(constant);
assert(V && "Marking constant with NULL");
Val.setPointer(V);
} else {
assert(getLatticeValue() == forcedconstant &&
"Cannot move from overdefined to constant!");
if (V == getConstant()) return false;
Val.setInt(overdefined);
}
return true;
}
ConstantInt *getConstantInt() const {
if (isConstant())
return dyn_cast<ConstantInt>(getConstant());
return nullptr;
}
void markForcedConstant(Constant *V) {
assert(isUndefined() && "Can't force a defined value!");
Val.setInt(forcedconstant);
Val.setPointer(V);
}
};
}
namespace {
class SCCPSolver : public InstVisitor<SCCPSolver> {
const DataLayout *DL;
const TargetLibraryInfo *TLI;
SmallPtrSet<BasicBlock*, 8> BBExecutable; DenseMap<Value*, LatticeVal> ValueState;
DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
DenseMap<Function*, LatticeVal> TrackedRetVals;
DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
SmallPtrSet<Function*, 16> MRVFunctionsTracked;
SmallPtrSet<Function*, 16> TrackingIncomingArguments;
SmallVector<Value*, 64> OverdefinedInstWorkList;
SmallVector<Value*, 64> InstWorkList;
SmallVector<BasicBlock*, 64> BBWorkList;
typedef std::pair<BasicBlock*, BasicBlock*> Edge;
DenseSet<Edge> KnownFeasibleEdges;
public:
SCCPSolver(const DataLayout *DL, const TargetLibraryInfo *tli)
: DL(DL), TLI(tli) {}
bool MarkBlockExecutable(BasicBlock *BB) {
if (!BBExecutable.insert(BB)) return false;
DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
BBWorkList.push_back(BB); return true;
}
void TrackValueOfGlobalVariable(GlobalVariable *GV) {
if (GV->getType()->getElementType()->isSingleValueType()) {
LatticeVal &IV = TrackedGlobals[GV];
if (!isa<UndefValue>(GV->getInitializer()))
IV.markConstant(GV->getInitializer());
}
}
void AddTrackedFunction(Function *F) {
if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
MRVFunctionsTracked.insert(F);
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
LatticeVal()));
} else
TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
}
void AddArgumentTrackedFunction(Function *F) {
TrackingIncomingArguments.insert(F);
}
void Solve();
bool ResolvedUndefsIn(Function &F);
bool isBlockExecutable(BasicBlock *BB) const {
return BBExecutable.count(BB);
}
LatticeVal getLatticeValueFor(Value *V) const {
DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
assert(I != ValueState.end() && "V is not in valuemap!");
return I->second;
}
const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
return TrackedRetVals;
}
const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
return TrackedGlobals;
}
void markOverdefined(Value *V) {
assert(!V->getType()->isStructTy() && "Should use other method");
markOverdefined(ValueState[V], V);
}
void markAnythingOverdefined(Value *V) {
if (StructType *STy = dyn_cast<StructType>(V->getType()))
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
markOverdefined(getStructValueState(V, i), V);
else
markOverdefined(V);
}
private:
void markConstant(LatticeVal &IV, Value *V, Constant *C) {
if (!IV.markConstant(C)) return;
DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
if (IV.isOverdefined())
OverdefinedInstWorkList.push_back(V);
else
InstWorkList.push_back(V);
}
void markConstant(Value *V, Constant *C) {
assert(!V->getType()->isStructTy() && "Should use other method");
markConstant(ValueState[V], V, C);
}
void markForcedConstant(Value *V, Constant *C) {
assert(!V->getType()->isStructTy() && "Should use other method");
LatticeVal &IV = ValueState[V];
IV.markForcedConstant(C);
DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
if (IV.isOverdefined())
OverdefinedInstWorkList.push_back(V);
else
InstWorkList.push_back(V);
}
void markOverdefined(LatticeVal &IV, Value *V) {
if (!IV.markOverdefined()) return;
DEBUG(dbgs() << "markOverdefined: ";
if (Function *F = dyn_cast<Function>(V))
dbgs() << "Function '" << F->getName() << "'\n";
else
dbgs() << *V << '\n');
OverdefinedInstWorkList.push_back(V);
}
void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
if (IV.isOverdefined() || MergeWithV.isUndefined())
return; if (MergeWithV.isOverdefined())
markOverdefined(IV, V);
else if (IV.isUndefined())
markConstant(IV, V, MergeWithV.getConstant());
else if (IV.getConstant() != MergeWithV.getConstant())
markOverdefined(IV, V);
}
void mergeInValue(Value *V, LatticeVal MergeWithV) {
assert(!V->getType()->isStructTy() && "Should use other method");
mergeInValue(ValueState[V], V, MergeWithV);
}
LatticeVal &getValueState(Value *V) {
assert(!V->getType()->isStructTy() && "Should use getStructValueState");
std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
ValueState.insert(std::make_pair(V, LatticeVal()));
LatticeVal &LV = I.first->second;
if (!I.second)
return LV;
if (Constant *C = dyn_cast<Constant>(V)) {
if (!isa<UndefValue>(V))
LV.markConstant(C); }
return LV;
}
LatticeVal &getStructValueState(Value *V, unsigned i) {
assert(V->getType()->isStructTy() && "Should use getValueState");
assert(i < cast<StructType>(V->getType())->getNumElements() &&
"Invalid element #");
std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
bool> I = StructValueState.insert(
std::make_pair(std::make_pair(V, i), LatticeVal()));
LatticeVal &LV = I.first->second;
if (!I.second)
return LV;
if (Constant *C = dyn_cast<Constant>(V)) {
Constant *Elt = C->getAggregateElement(i);
if (!Elt)
LV.markOverdefined(); else if (isa<UndefValue>(Elt))
; else
LV.markConstant(Elt); }
return LV;
}
void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
return;
if (!MarkBlockExecutable(Dest)) {
DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
<< " -> " << Dest->getName() << '\n');
PHINode *PN;
for (BasicBlock::iterator I = Dest->begin();
(PN = dyn_cast<PHINode>(I)); ++I)
visitPHINode(*PN);
}
}
void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
void OperandChangedState(Instruction *I) {
if (BBExecutable.count(I->getParent())) visit(*I);
}
private:
friend class InstVisitor<SCCPSolver>;
void visitPHINode(PHINode &I);
void visitReturnInst(ReturnInst &I);
void visitTerminatorInst(TerminatorInst &TI);
void visitCastInst(CastInst &I);
void visitSelectInst(SelectInst &I);
void visitBinaryOperator(Instruction &I);
void visitCmpInst(CmpInst &I);
void visitExtractElementInst(ExtractElementInst &I);
void visitInsertElementInst(InsertElementInst &I);
void visitShuffleVectorInst(ShuffleVectorInst &I);
void visitExtractValueInst(ExtractValueInst &EVI);
void visitInsertValueInst(InsertValueInst &IVI);
void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
void visitStoreInst (StoreInst &I);
void visitLoadInst (LoadInst &I);
void visitGetElementPtrInst(GetElementPtrInst &I);
void visitCallInst (CallInst &I) {
visitCallSite(&I);
}
void visitInvokeInst (InvokeInst &II) {
visitCallSite(&II);
visitTerminatorInst(II);
}
void visitCallSite (CallSite CS);
void visitResumeInst (TerminatorInst &I) { }
void visitUnreachableInst(TerminatorInst &I) { }
void visitFenceInst (FenceInst &I) { }
void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
markAnythingOverdefined(&I);
}
void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
void visitInstruction(Instruction &I) {
dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
markAnythingOverdefined(&I); }
};
}
void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
SmallVectorImpl<bool> &Succs) {
Succs.resize(TI.getNumSuccessors());
if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
if (BI->isUnconditional()) {
Succs[0] = true;
return;
}
LatticeVal BCValue = getValueState(BI->getCondition());
ConstantInt *CI = BCValue.getConstantInt();
if (!CI) {
if (!BCValue.isUndefined())
Succs[0] = Succs[1] = true;
return;
}
Succs[CI->isZero()] = true;
return;
}
if (isa<InvokeInst>(TI)) {
Succs[0] = Succs[1] = true;
return;
}
if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
if (!SI->getNumCases()) {
Succs[0] = true;
return;
}
LatticeVal SCValue = getValueState(SI->getCondition());
ConstantInt *CI = SCValue.getConstantInt();
if (!CI) { if (!SCValue.isUndefined())
Succs.assign(TI.getNumSuccessors(), true);
return;
}
Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
return;
}
if (isa<IndirectBrInst>(&TI)) {
Succs.assign(TI.getNumSuccessors(), true);
return;
}
#ifndef NDEBUG
dbgs() << "Unknown terminator instruction: " << TI << '\n';
#endif
llvm_unreachable("SCCP: Don't know how to handle this terminator!");
}
bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
assert(BBExecutable.count(To) && "Dest should always be alive!");
if (!BBExecutable.count(From)) return false;
TerminatorInst *TI = From->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isUnconditional())
return true;
LatticeVal BCValue = getValueState(BI->getCondition());
ConstantInt *CI = BCValue.getConstantInt();
if (!CI)
return !BCValue.isUndefined();
return BI->getSuccessor(CI->isZero()) == To;
}
if (isa<InvokeInst>(TI))
return true;
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
if (SI->getNumCases() < 1)
return true;
LatticeVal SCValue = getValueState(SI->getCondition());
ConstantInt *CI = SCValue.getConstantInt();
if (!CI)
return !SCValue.isUndefined();
return SI->findCaseValue(CI).getCaseSuccessor() == To;
}
if (isa<IndirectBrInst>(TI))
return true;
#ifndef NDEBUG
dbgs() << "Unknown terminator instruction: " << *TI << '\n';
#endif
llvm_unreachable(nullptr);
}
void SCCPSolver::visitPHINode(PHINode &PN) {
if (PN.getType()->isStructTy())
return markAnythingOverdefined(&PN);
if (getValueState(&PN).isOverdefined())
return;
if (PN.getNumIncomingValues() > 64)
return markOverdefined(&PN);
Constant *OperandVal = nullptr;
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
LatticeVal IV = getValueState(PN.getIncomingValue(i));
if (IV.isUndefined()) continue;
if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
continue;
if (IV.isOverdefined()) return markOverdefined(&PN);
if (!OperandVal) { OperandVal = IV.getConstant();
continue;
}
if (IV.getConstant() != OperandVal)
return markOverdefined(&PN);
}
if (OperandVal)
markConstant(&PN, OperandVal); }
void SCCPSolver::visitReturnInst(ReturnInst &I) {
if (I.getNumOperands() == 0) return;
Function *F = I.getParent()->getParent();
Value *ResultOp = I.getOperand(0);
if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
DenseMap<Function*, LatticeVal>::iterator TFRVI =
TrackedRetVals.find(F);
if (TFRVI != TrackedRetVals.end()) {
mergeInValue(TFRVI->second, F, getValueState(ResultOp));
return;
}
}
if (!TrackedMultipleRetVals.empty()) {
if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
if (MRVFunctionsTracked.count(F))
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
getStructValueState(ResultOp, i));
}
}
void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
SmallVector<bool, 16> SuccFeasible;
getFeasibleSuccessors(TI, SuccFeasible);
BasicBlock *BB = TI.getParent();
for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
if (SuccFeasible[i])
markEdgeExecutable(BB, TI.getSuccessor(i));
}
void SCCPSolver::visitCastInst(CastInst &I) {
LatticeVal OpSt = getValueState(I.getOperand(0));
if (OpSt.isOverdefined()) markOverdefined(&I);
else if (OpSt.isConstant()) markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
OpSt.getConstant(), I.getType()));
}
void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
if (EVI.getType()->isStructTy())
return markAnythingOverdefined(&EVI);
if (EVI.getNumIndices() != 1)
return markOverdefined(&EVI);
Value *AggVal = EVI.getAggregateOperand();
if (AggVal->getType()->isStructTy()) {
unsigned i = *EVI.idx_begin();
LatticeVal EltVal = getStructValueState(AggVal, i);
mergeInValue(getValueState(&EVI), &EVI, EltVal);
} else {
return markOverdefined(&EVI);
}
}
void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
StructType *STy = dyn_cast<StructType>(IVI.getType());
if (!STy)
return markOverdefined(&IVI);
if (IVI.getNumIndices() != 1)
return markAnythingOverdefined(&IVI);
Value *Aggr = IVI.getAggregateOperand();
unsigned Idx = *IVI.idx_begin();
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
if (i != Idx) {
LatticeVal EltVal = getStructValueState(Aggr, i);
mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
continue;
}
Value *Val = IVI.getInsertedValueOperand();
if (Val->getType()->isStructTy())
markOverdefined(getStructValueState(&IVI, i), &IVI);
else {
LatticeVal InVal = getValueState(Val);
mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
}
}
}
void SCCPSolver::visitSelectInst(SelectInst &I) {
if (I.getType()->isStructTy())
return markAnythingOverdefined(&I);
LatticeVal CondValue = getValueState(I.getCondition());
if (CondValue.isUndefined())
return;
if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
mergeInValue(&I, getValueState(OpVal));
return;
}
LatticeVal TVal = getValueState(I.getTrueValue());
LatticeVal FVal = getValueState(I.getFalseValue());
if (TVal.isConstant() && FVal.isConstant() &&
TVal.getConstant() == FVal.getConstant())
return markConstant(&I, FVal.getConstant());
if (TVal.isUndefined()) return mergeInValue(&I, FVal);
if (FVal.isUndefined()) return mergeInValue(&I, TVal);
markOverdefined(&I);
}
void SCCPSolver::visitBinaryOperator(Instruction &I) {
LatticeVal V1State = getValueState(I.getOperand(0));
LatticeVal V2State = getValueState(I.getOperand(1));
LatticeVal &IV = ValueState[&I];
if (IV.isOverdefined()) return;
if (V1State.isConstant() && V2State.isConstant())
return markConstant(IV, &I,
ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
V2State.getConstant()));
if (!V1State.isOverdefined() && !V2State.isOverdefined())
return;
if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
LatticeVal *NonOverdefVal = nullptr;
if (!V1State.isOverdefined())
NonOverdefVal = &V1State;
else if (!V2State.isOverdefined())
NonOverdefVal = &V2State;
if (NonOverdefVal) {
if (NonOverdefVal->isUndefined()) {
if (I.getOpcode() == Instruction::And)
markConstant(IV, &I, Constant::getNullValue(I.getType()));
else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
markConstant(IV, &I, Constant::getAllOnesValue(PT));
else
markConstant(IV, &I,
Constant::getAllOnesValue(I.getType()));
return;
}
if (I.getOpcode() == Instruction::And) {
if (NonOverdefVal->getConstant()->isNullValue())
return markConstant(IV, &I, NonOverdefVal->getConstant());
} else {
if (ConstantInt *CI = NonOverdefVal->getConstantInt())
if (CI->isAllOnesValue()) return markConstant(IV, &I, NonOverdefVal->getConstant());
}
}
}
markOverdefined(&I);
}
void SCCPSolver::visitCmpInst(CmpInst &I) {
LatticeVal V1State = getValueState(I.getOperand(0));
LatticeVal V2State = getValueState(I.getOperand(1));
LatticeVal &IV = ValueState[&I];
if (IV.isOverdefined()) return;
if (V1State.isConstant() && V2State.isConstant())
return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
V1State.getConstant(),
V2State.getConstant()));
if (!V1State.isOverdefined() && !V2State.isOverdefined())
return;
markOverdefined(&I);
}
void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
return markOverdefined(&I);
#if 0
LatticeVal &ValState = getValueState(I.getOperand(0));
LatticeVal &IdxState = getValueState(I.getOperand(1));
if (ValState.isOverdefined() || IdxState.isOverdefined())
markOverdefined(&I);
else if(ValState.isConstant() && IdxState.isConstant())
markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
IdxState.getConstant()));
#endif
}
void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
return markOverdefined(&I);
#if 0
LatticeVal &ValState = getValueState(I.getOperand(0));
LatticeVal &EltState = getValueState(I.getOperand(1));
LatticeVal &IdxState = getValueState(I.getOperand(2));
if (ValState.isOverdefined() || EltState.isOverdefined() ||
IdxState.isOverdefined())
markOverdefined(&I);
else if(ValState.isConstant() && EltState.isConstant() &&
IdxState.isConstant())
markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
EltState.getConstant(),
IdxState.getConstant()));
else if (ValState.isUndefined() && EltState.isConstant() &&
IdxState.isConstant())
markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
EltState.getConstant(),
IdxState.getConstant()));
#endif
}
void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
return markOverdefined(&I);
#if 0
LatticeVal &V1State = getValueState(I.getOperand(0));
LatticeVal &V2State = getValueState(I.getOperand(1));
LatticeVal &MaskState = getValueState(I.getOperand(2));
if (MaskState.isUndefined() ||
(V1State.isUndefined() && V2State.isUndefined()))
return;
if (V1State.isOverdefined() || V2State.isOverdefined() ||
MaskState.isOverdefined()) {
markOverdefined(&I);
} else {
Constant *V1 = V1State.isConstant() ?
V1State.getConstant() : UndefValue::get(I.getType());
Constant *V2 = V2State.isConstant() ?
V2State.getConstant() : UndefValue::get(I.getType());
Constant *Mask = MaskState.isConstant() ?
MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
}
#endif
}
void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
if (ValueState[&I].isOverdefined()) return;
SmallVector<Constant*, 8> Operands;
Operands.reserve(I.getNumOperands());
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
LatticeVal State = getValueState(I.getOperand(i));
if (State.isUndefined())
return;
if (State.isOverdefined())
return markOverdefined(&I);
assert(State.isConstant() && "Unknown state!");
Operands.push_back(State.getConstant());
}
Constant *Ptr = Operands[0];
ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
}
void SCCPSolver::visitStoreInst(StoreInst &SI) {
if (SI.getOperand(0)->getType()->isStructTy())
return;
if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
return;
GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
if (I->second.isOverdefined())
TrackedGlobals.erase(I); }
void SCCPSolver::visitLoadInst(LoadInst &I) {
if (I.getType()->isStructTy())
return markAnythingOverdefined(&I);
LatticeVal PtrVal = getValueState(I.getOperand(0));
if (PtrVal.isUndefined()) return;
LatticeVal &IV = ValueState[&I];
if (IV.isOverdefined()) return;
if (!PtrVal.isConstant() || I.isVolatile())
return markOverdefined(IV, &I);
Constant *Ptr = PtrVal.getConstant();
if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
return markConstant(IV, &I, Constant::getNullValue(I.getType()));
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
if (!TrackedGlobals.empty()) {
DenseMap<GlobalVariable*, LatticeVal>::iterator It =
TrackedGlobals.find(GV);
if (It != TrackedGlobals.end()) {
mergeInValue(IV, &I, It->second);
return;
}
}
}
if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
return markConstant(IV, &I, C);
markOverdefined(IV, &I);
}
void SCCPSolver::visitCallSite(CallSite CS) {
Function *F = CS.getCalledFunction();
Instruction *I = CS.getInstruction();
if (!F || F->isDeclaration()) {
CallOverdefined:
if (I->getType()->isVoidTy()) return;
if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
canConstantFoldCallTo(F)) {
SmallVector<Constant*, 8> Operands;
for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
AI != E; ++AI) {
LatticeVal State = getValueState(*AI);
if (State.isUndefined())
return; if (State.isOverdefined())
return markOverdefined(I);
assert(State.isConstant() && "Unknown state!");
Operands.push_back(State.getConstant());
}
if (getValueState(I).isOverdefined())
return;
if (Constant *C = ConstantFoldCall(F, Operands, TLI))
return markConstant(I, C);
}
return markAnythingOverdefined(I);
}
if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
MarkBlockExecutable(F->begin());
CallSite::arg_iterator CAI = CS.arg_begin();
for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
AI != E; ++AI, ++CAI) {
if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
markOverdefined(AI);
continue;
}
if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
LatticeVal CallArg = getStructValueState(*CAI, i);
mergeInValue(getStructValueState(AI, i), AI, CallArg);
}
} else {
mergeInValue(AI, getValueState(*CAI));
}
}
}
if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
if (!MRVFunctionsTracked.count(F))
goto CallOverdefined;
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
mergeInValue(getStructValueState(I, i), I,
TrackedMultipleRetVals[std::make_pair(F, i)]);
} else {
DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
if (TFRVI == TrackedRetVals.end())
goto CallOverdefined;
mergeInValue(I, TFRVI->second);
}
}
void SCCPSolver::Solve() {
while (!BBWorkList.empty() || !InstWorkList.empty() ||
!OverdefinedInstWorkList.empty()) {
while (!OverdefinedInstWorkList.empty()) {
Value *I = OverdefinedInstWorkList.pop_back_val();
DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
for (User *U : I->users())
if (Instruction *UI = dyn_cast<Instruction>(U))
OperandChangedState(UI);
}
while (!InstWorkList.empty()) {
Value *I = InstWorkList.pop_back_val();
DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
for (User *U : I->users())
if (Instruction *UI = dyn_cast<Instruction>(U))
OperandChangedState(UI);
}
while (!BBWorkList.empty()) {
BasicBlock *BB = BBWorkList.back();
BBWorkList.pop_back();
DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
visit(BB);
}
}
}
bool SCCPSolver::ResolvedUndefsIn(Function &F) {
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
if (!BBExecutable.count(BB))
continue;
for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
if (I->getType()->isVoidTy()) continue;
if (StructType *STy = dyn_cast<StructType>(I->getType())) {
if (CallSite CS = CallSite(I))
if (Function *F = CS.getCalledFunction())
if (MRVFunctionsTracked.count(F))
continue;
if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
continue;
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
LatticeVal &LV = getStructValueState(I, i);
if (LV.isUndefined())
markOverdefined(LV, I);
}
continue;
}
LatticeVal &LV = getValueState(I);
if (!LV.isUndefined()) continue;
if (isa<ExtractValueInst>(I))
continue;
if (I->getOperand(0)->getType()->isStructTy()) {
markOverdefined(I);
return true;
}
LatticeVal Op0LV = getValueState(I->getOperand(0));
LatticeVal Op1LV;
if (I->getNumOperands() == 2) {
if (I->getOperand(1)->getType()->isStructTy()) {
markOverdefined(I);
return true;
}
Op1LV = getValueState(I->getOperand(1));
}
Type *ITy = I->getType();
switch (I->getOpcode()) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Trunc:
case Instruction::FPTrunc:
case Instruction::BitCast:
break; case Instruction::FSub:
case Instruction::FAdd:
case Instruction::FMul:
case Instruction::FDiv:
case Instruction::FRem:
if (Op0LV.isUndefined() && Op1LV.isUndefined())
markForcedConstant(I, Constant::getNullValue(ITy));
else
markOverdefined(I);
return true;
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::FPExt:
case Instruction::PtrToInt:
case Instruction::IntToPtr:
case Instruction::SIToFP:
case Instruction::UIToFP:
markForcedConstant(I, Constant::getNullValue(ITy));
return true;
case Instruction::Mul:
case Instruction::And:
if (Op0LV.isUndefined() && Op1LV.isUndefined())
break;
markForcedConstant(I, Constant::getNullValue(ITy));
return true;
case Instruction::Or:
if (Op0LV.isUndefined() && Op1LV.isUndefined())
break;
markForcedConstant(I, Constant::getAllOnesValue(ITy));
return true;
case Instruction::Xor:
if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
markForcedConstant(I, Constant::getNullValue(ITy));
return true;
}
break;
case Instruction::SDiv:
case Instruction::UDiv:
case Instruction::SRem:
case Instruction::URem:
if (Op1LV.isUndefined()) break;
markForcedConstant(I, Constant::getNullValue(ITy));
return true;
case Instruction::AShr:
if (Op1LV.isUndefined()) break;
markForcedConstant(I, Constant::getAllOnesValue(ITy));
return true;
case Instruction::LShr:
case Instruction::Shl:
if (Op1LV.isUndefined()) break;
markForcedConstant(I, Constant::getNullValue(ITy));
return true;
case Instruction::Select:
Op1LV = getValueState(I->getOperand(1));
if (Op0LV.isUndefined()) {
if (!Op1LV.isConstant()) Op1LV = getValueState(I->getOperand(2));
} else if (Op1LV.isUndefined()) {
Op1LV = getValueState(I->getOperand(2));
if (Op1LV.isUndefined())
break;
} else {
}
if (Op1LV.isConstant())
markForcedConstant(I, Op1LV.getConstant());
else
markOverdefined(I);
return true;
case Instruction::Load:
break;
case Instruction::ICmp:
if (cast<ICmpInst>(I)->isEquality())
break;
markOverdefined(I);
return true;
case Instruction::Call:
case Instruction::Invoke: {
if (Function *F = CallSite(I).getCalledFunction())
if (TrackedRetVals.count(F))
break;
markOverdefined(I);
return true;
}
default:
markOverdefined(I);
return true;
}
}
TerminatorInst *TI = BB->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (!BI->isConditional()) continue;
if (!getValueState(BI->getCondition()).isUndefined())
continue;
if (isa<UndefValue>(BI->getCondition())) {
BI->setCondition(ConstantInt::getFalse(BI->getContext()));
markEdgeExecutable(BB, TI->getSuccessor(1));
return true;
}
markForcedConstant(BI->getCondition(),
ConstantInt::getFalse(TI->getContext()));
return true;
}
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
if (!SI->getNumCases())
continue;
if (!getValueState(SI->getCondition()).isUndefined())
continue;
if (isa<UndefValue>(SI->getCondition())) {
SI->setCondition(SI->case_begin().getCaseValue());
markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
return true;
}
markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
return true;
}
}
return false;
}
namespace {
struct SCCP : public FunctionPass {
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<TargetLibraryInfo>();
}
static char ID; SCCP() : FunctionPass(ID) {
initializeSCCPPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
};
}
char SCCP::ID = 0;
INITIALIZE_PASS(SCCP, "sccp",
"Sparse Conditional Constant Propagation", false, false)
FunctionPass *llvm::createSCCPPass() {
return new SCCP();
}
static void DeleteInstructionInBlock(BasicBlock *BB) {
DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
++NumDeadBlocks;
if (isa<TerminatorInst>(BB->begin()))
return;
Instruction *EndInst = BB->getTerminator(); while (EndInst != BB->begin()) {
BasicBlock::iterator I = EndInst;
Instruction *Inst = --I;
if (!Inst->use_empty())
Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
if (isa<LandingPadInst>(Inst)) {
EndInst = Inst;
continue;
}
BB->getInstList().erase(Inst);
++NumInstRemoved;
}
}
bool SCCP::runOnFunction(Function &F) {
if (skipOptnoneFunction(F))
return false;
DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
const DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
SCCPSolver Solver(DL, TLI);
Solver.MarkBlockExecutable(F.begin());
for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Solver.markAnythingOverdefined(AI);
bool ResolvedUndefs = true;
while (ResolvedUndefs) {
Solver.Solve();
DEBUG(dbgs() << "RESOLVING UNDEFs\n");
ResolvedUndefs = Solver.ResolvedUndefsIn(F);
}
bool MadeChanges = false;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
if (!Solver.isBlockExecutable(BB)) {
DeleteInstructionInBlock(BB);
MadeChanges = true;
continue;
}
for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Instruction *Inst = BI++;
if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
continue;
if (Inst->getType()->isStructTy())
continue;
LatticeVal IV = Solver.getLatticeValueFor(Inst);
if (IV.isOverdefined())
continue;
Constant *Const = IV.isConstant()
? IV.getConstant() : UndefValue::get(Inst->getType());
DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Inst->replaceAllUsesWith(Const);
Inst->eraseFromParent();
MadeChanges = true;
++NumInstRemoved;
}
}
return MadeChanges;
}
namespace {
struct IPSCCP : public ModulePass {
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<TargetLibraryInfo>();
}
static char ID;
IPSCCP() : ModulePass(ID) {
initializeIPSCCPPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override;
};
}
char IPSCCP::ID = 0;
INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
"Interprocedural Sparse Conditional Constant Propagation",
false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
INITIALIZE_PASS_END(IPSCCP, "ipsccp",
"Interprocedural Sparse Conditional Constant Propagation",
false, false)
ModulePass *llvm::createIPSCCPPass() {
return new IPSCCP();
}
static bool AddressIsTaken(const GlobalValue *GV) {
GV->removeDeadConstantUsers();
for (const Use &U : GV->uses()) {
const User *UR = U.getUser();
if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
if (SI->getOperand(0) == GV || SI->isVolatile())
return true; } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
ImmutableCallSite CS(cast<Instruction>(UR));
if (!CS.isCallee(&U))
return true;
} else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
if (LI->isVolatile())
return true;
} else if (isa<BlockAddress>(UR)) {
} else {
return true;
}
}
return false;
}
bool IPSCCP::runOnModule(Module &M) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
SCCPSolver Solver(DL, TLI);
SmallPtrSet<Function*, 32> AddressTakenFunctions;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
if (F->isDeclaration())
continue;
if (!F->mayBeOverridden())
Solver.AddTrackedFunction(F);
if (F->hasLocalLinkage()) {
if (AddressIsTaken(F))
AddressTakenFunctions.insert(F);
else {
Solver.AddArgumentTrackedFunction(F);
continue;
}
}
Solver.MarkBlockExecutable(F->begin());
for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
AI != E; ++AI)
Solver.markAnythingOverdefined(AI);
}
for (Module::global_iterator G = M.global_begin(), E = M.global_end();
G != E; ++G)
if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Solver.TrackValueOfGlobalVariable(G);
bool ResolvedUndefs = true;
while (ResolvedUndefs) {
Solver.Solve();
DEBUG(dbgs() << "RESOLVING UNDEFS\n");
ResolvedUndefs = false;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
}
bool MadeChanges = false;
SmallVector<BasicBlock*, 512> BlocksToErase;
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
if (Solver.isBlockExecutable(F->begin())) {
for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
AI != E; ++AI) {
if (AI->use_empty() || AI->getType()->isStructTy()) continue;
LatticeVal IV = Solver.getLatticeValueFor(AI);
if (IV.isOverdefined()) continue;
Constant *CST = IV.isConstant() ?
IV.getConstant() : UndefValue::get(AI->getType());
DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
AI->replaceAllUsesWith(CST);
++IPNumArgsElimed;
}
}
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
if (!Solver.isBlockExecutable(BB)) {
DeleteInstructionInBlock(BB);
MadeChanges = true;
TerminatorInst *TI = BB->getTerminator();
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
BasicBlock *Succ = TI->getSuccessor(i);
if (!Succ->empty() && isa<PHINode>(Succ->begin()))
TI->getSuccessor(i)->removePredecessor(BB);
}
if (!TI->use_empty())
TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
TI->eraseFromParent();
if (&*BB != &F->front())
BlocksToErase.push_back(BB);
else
new UnreachableInst(M.getContext(), BB);
continue;
}
for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Instruction *Inst = BI++;
if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
continue;
LatticeVal IV = Solver.getLatticeValueFor(Inst);
if (IV.isOverdefined())
continue;
Constant *Const = IV.isConstant()
? IV.getConstant() : UndefValue::get(Inst->getType());
DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Inst->replaceAllUsesWith(Const);
if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Inst->eraseFromParent();
MadeChanges = true;
++IPNumInstRemoved;
}
}
for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
BasicBlock *DeadBB = BlocksToErase[i];
for (Value::user_iterator UI = DeadBB->user_begin(),
UE = DeadBB->user_end();
UI != UE;) {
Instruction *I = dyn_cast<Instruction>(*UI);
do { ++UI; } while (UI != UE && *UI == I);
if (!I) continue;
bool Folded = ConstantFoldTerminator(I->getParent());
if (!Folded) {
#ifndef NDEBUG
if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
"Branch should be foldable!");
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
} else {
llvm_unreachable("Didn't fold away reference to block!");
}
#endif
TerminatorInst *TI = I->getParent()->getTerminator();
BranchInst::Create(TI->getSuccessor(0), TI);
for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
TI->getSuccessor(i)->removePredecessor(TI->getParent());
TI->eraseFromParent();
}
}
F->getBasicBlockList().erase(DeadBB);
}
BlocksToErase.clear();
}
SmallVector<ReturnInst*, 8> ReturnsToZap;
const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
E = RV.end(); I != E; ++I) {
Function *F = I->first;
if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
continue;
if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
continue;
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
if (!isa<UndefValue>(RI->getOperand(0)))
ReturnsToZap.push_back(RI);
}
for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
Function *F = ReturnsToZap[i]->getParent()->getParent();
ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
}
const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
E = TG.end(); I != E; ++I) {
GlobalVariable *GV = I->first;
assert(!I->second.isOverdefined() &&
"Overdefined values should have been taken out of the map!");
DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
while (!GV->use_empty()) {
StoreInst *SI = cast<StoreInst>(GV->user_back());
SI->eraseFromParent();
}
M.getGlobalList().erase(GV);
++IPNumGlobalConst;
}
return MadeChanges;
}