#define DEBUG_TYPE "globalsmodref-aa"
#include "llvm/Analysis/Passes.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Instructions.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/SCCIterator.h"
#include <set>
using namespace llvm;
STATISTIC(NumNonAddrTakenGlobalVars,
"Number of global vars without address taken");
STATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
STATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
STATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
STATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
namespace {
struct FunctionRecord {
std::map<const GlobalValue*, unsigned> GlobalInfo;
bool MayReadAnyGlobal;
unsigned getInfoForGlobal(const GlobalValue *GV) const {
unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
std::map<const GlobalValue*, unsigned>::const_iterator I =
GlobalInfo.find(GV);
if (I != GlobalInfo.end())
Effect |= I->second;
return Effect;
}
unsigned FunctionEffect;
FunctionRecord() : MayReadAnyGlobal (false), FunctionEffect(0) {}
};
class GlobalsModRef : public ModulePass, public AliasAnalysis {
std::set<const GlobalValue*> NonAddressTakenGlobals;
std::set<const GlobalValue*> IndirectGlobals;
std::map<const Value*, const GlobalValue*> AllocsForIndirectGlobals;
std::map<const Function*, FunctionRecord> FunctionInfo;
public:
static char ID;
GlobalsModRef() : ModulePass(ID) {
initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) {
InitializeAliasAnalysis(this); AnalyzeGlobals(M); AnalyzeCallGraph(getAnalysis<CallGraph>(), M); return false;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
AU.addRequired<CallGraph>();
AU.setPreservesAll(); }
AliasResult alias(const Location &LocA, const Location &LocB);
ModRefResult getModRefInfo(ImmutableCallSite CS,
const Location &Loc);
ModRefResult getModRefInfo(ImmutableCallSite CS1,
ImmutableCallSite CS2) {
return AliasAnalysis::getModRefInfo(CS1, CS2);
}
ModRefBehavior getModRefBehavior(const Function *F) {
ModRefBehavior Min = UnknownModRefBehavior;
if (FunctionRecord *FR = getFunctionInfo(F)) {
if (FR->FunctionEffect == 0)
Min = DoesNotAccessMemory;
else if ((FR->FunctionEffect & Mod) == 0)
Min = OnlyReadsMemory;
}
return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
}
ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
ModRefBehavior Min = UnknownModRefBehavior;
if (const Function* F = CS.getCalledFunction())
if (FunctionRecord *FR = getFunctionInfo(F)) {
if (FR->FunctionEffect == 0)
Min = DoesNotAccessMemory;
else if ((FR->FunctionEffect & Mod) == 0)
Min = OnlyReadsMemory;
}
return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
}
virtual void deleteValue(Value *V);
virtual void copyValue(Value *From, Value *To);
virtual void addEscapingUse(Use &U);
virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
if (PI == &AliasAnalysis::ID)
return (AliasAnalysis*)this;
return this;
}
private:
FunctionRecord *getFunctionInfo(const Function *F) {
std::map<const Function*, FunctionRecord>::iterator I =
FunctionInfo.find(F);
if (I != FunctionInfo.end())
return &I->second;
return 0;
}
void AnalyzeGlobals(Module &M);
void AnalyzeCallGraph(CallGraph &CG, Module &M);
bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers,
std::vector<Function*> &Writers,
GlobalValue *OkayStoreDest = 0);
bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
};
}
char GlobalsModRef::ID = 0;
INITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis,
"globalsmodref-aa", "Simple mod/ref analysis for globals",
false, true, false)
INITIALIZE_AG_DEPENDENCY(CallGraph)
INITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis,
"globalsmodref-aa", "Simple mod/ref analysis for globals",
false, true, false)
Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
void GlobalsModRef::AnalyzeGlobals(Module &M) {
std::vector<Function*> Readers, Writers;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (I->hasLocalLinkage()) {
if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
NonAddressTakenGlobals.insert(I);
++NumNonAddrTakenFunctions;
}
Readers.clear(); Writers.clear();
}
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
if (I->hasLocalLinkage()) {
if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
NonAddressTakenGlobals.insert(I);
for (unsigned i = 0, e = Readers.size(); i != e; ++i)
FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
if (!I->isConstant()) for (unsigned i = 0, e = Writers.size(); i != e; ++i)
FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
++NumNonAddrTakenGlobalVars;
if (I->getType()->getElementType()->isPointerTy() &&
AnalyzeIndirectGlobalMemory(I))
++NumIndirectGlobalVars;
}
Readers.clear(); Writers.clear();
}
}
bool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
std::vector<Function*> &Readers,
std::vector<Function*> &Writers,
GlobalValue *OkayStoreDest) {
if (!V->getType()->isPointerTy()) return true;
for (Value::use_iterator UI = V->use_begin(), E=V->use_end(); UI != E; ++UI) {
User *U = *UI;
if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Readers.push_back(LI->getParent()->getParent());
} else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (V == SI->getOperand(1)) {
Writers.push_back(SI->getParent()->getParent());
} else if (SI->getOperand(1) != OkayStoreDest) {
return true; }
} else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true;
} else if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest))
return true;
} else if (isFreeCall(U, TLI)) {
Writers.push_back(cast<Instruction>(U)->getParent()->getParent());
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
if (CI->getArgOperand(i) == V) return true;
} else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) {
for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i)
if (II->getArgOperand(i) == V) return true;
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
if (CE->getOpcode() == Instruction::GetElementPtr ||
CE->getOpcode() == Instruction::BitCast) {
if (AnalyzeUsesOfPointer(CE, Readers, Writers))
return true;
} else {
return true;
}
} else if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
return true; } else {
return true;
}
}
return false;
}
bool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
std::vector<Value*> AllocRelatedValues;
for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
User *U = *I;
if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
std::vector<Function*> ReadersWriters;
if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
return false; } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (SI->getOperand(0) == GV) return false;
if (isa<ConstantPointerNull>(SI->getOperand(0)))
continue;
Value *Ptr = GetUnderlyingObject(SI->getOperand(0));
if (!isAllocLikeFn(Ptr, TLI))
return false;
std::vector<Function*> ReadersWriters;
if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
return false;
AllocRelatedValues.push_back(Ptr);
} else {
return false;
}
}
while (!AllocRelatedValues.empty()) {
AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
AllocRelatedValues.pop_back();
}
IndirectGlobals.insert(GV);
return true;
}
void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I != E;
++I) {
std::vector<CallGraphNode *> &SCC = *I;
assert(!SCC.empty() && "SCC with no functions?");
if (!SCC[0]->getFunction()) {
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
FunctionInfo.erase(SCC[i]->getFunction());
continue;
}
FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
bool KnowNothing = false;
unsigned FunctionEffect = 0;
for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
Function *F = SCC[i]->getFunction();
if (!F) {
KnowNothing = true;
break;
}
if (F->isDeclaration()) {
if (F->doesNotAccessMemory()) {
} else if (F->onlyReadsMemory()) {
FunctionEffect |= Ref;
if (!F->isIntrinsic())
FR.MayReadAnyGlobal = true;
} else {
FunctionEffect |= ModRef;
KnowNothing = !F->isIntrinsic();
}
continue;
}
for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
CI != E && !KnowNothing; ++CI)
if (Function *Callee = CI->second->getFunction()) {
if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
FunctionEffect |= CalleeFR->FunctionEffect;
for (std::map<const GlobalValue*, unsigned>::iterator GI =
CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
GI != E; ++GI)
FR.GlobalInfo[GI->first] |= GI->second;
FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
} else {
CallGraphNode *CalleeNode = CG[Callee];
if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
KnowNothing = true;
}
} else {
KnowNothing = true;
}
}
if (KnowNothing) {
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
FunctionInfo.erase(SCC[i]->getFunction());
continue;
}
for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
E = inst_end(SCC[i]->getFunction());
II != E && FunctionEffect != ModRef; ++II)
if (LoadInst *LI = dyn_cast<LoadInst>(&*II)) {
FunctionEffect |= Ref;
if (LI->isVolatile())
FunctionEffect |= Mod;
} else if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
FunctionEffect |= Mod;
if (SI->isVolatile())
FunctionEffect |= Ref;
} else if (isAllocationFn(&*II, TLI) || isFreeCall(&*II, TLI)) {
FunctionEffect |= ModRef;
} else if (IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(&*II)) {
Function *Callee = Intrinsic->getCalledFunction();
ModRefBehavior Behaviour = AliasAnalysis::getModRefBehavior(Callee);
FunctionEffect |= (Behaviour & ModRef);
}
if ((FunctionEffect & Mod) == 0)
++NumReadMemFunctions;
if (FunctionEffect == 0)
++NumNoMemFunctions;
FR.FunctionEffect = FunctionEffect;
for (unsigned i = 1, e = SCC.size(); i != e; ++i)
FunctionInfo[SCC[i]->getFunction()] = FR;
}
}
AliasAnalysis::AliasResult
GlobalsModRef::alias(const Location &LocA,
const Location &LocB) {
const Value *UV1 = GetUnderlyingObject(LocA.Ptr);
const Value *UV2 = GetUnderlyingObject(LocB.Ptr);
const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
if (GV1 || GV2) {
if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
if ((GV1 || GV2) && GV1 != GV2)
return NoAlias;
}
GV1 = GV2 = 0;
if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
if (IndirectGlobals.count(GV))
GV1 = GV;
if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
if (IndirectGlobals.count(GV))
GV2 = GV;
if (AllocsForIndirectGlobals.count(UV1))
GV1 = AllocsForIndirectGlobals[UV1];
if (AllocsForIndirectGlobals.count(UV2))
GV2 = AllocsForIndirectGlobals[UV2];
if ((GV1 || GV2) && GV1 != GV2)
return NoAlias;
return AliasAnalysis::alias(LocA, LocB);
}
AliasAnalysis::ModRefResult
GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
const Location &Loc) {
unsigned Known = ModRef;
if (const GlobalValue *GV =
dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr)))
if (GV->hasLocalLinkage())
if (const Function *F = CS.getCalledFunction())
if (NonAddressTakenGlobals.count(GV))
if (const FunctionRecord *FR = getFunctionInfo(F))
Known = FR->getInfoForGlobal(GV);
if (Known == NoModRef)
return NoModRef; return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
}
void GlobalsModRef::deleteValue(Value *V) {
if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
if (NonAddressTakenGlobals.erase(GV)) {
if (IndirectGlobals.erase(GV)) {
for (std::map<const Value*, const GlobalValue*>::iterator
I = AllocsForIndirectGlobals.begin(),
E = AllocsForIndirectGlobals.end(); I != E; ) {
if (I->second == GV) {
AllocsForIndirectGlobals.erase(I++);
} else {
++I;
}
}
}
}
}
AllocsForIndirectGlobals.erase(V);
AliasAnalysis::deleteValue(V);
}
void GlobalsModRef::copyValue(Value *From, Value *To) {
AliasAnalysis::copyValue(From, To);
}
void GlobalsModRef::addEscapingUse(Use &U) {
deleteValue(U);
AliasAnalysis::addEscapingUse(U);
}