//===- Andersens.cpp - Andersen's Interprocedural Alias Analysis ----------===//
-//
+//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
-//
+//
//===----------------------------------------------------------------------===//
//
// This file defines a very simple implementation of Andersen's interprocedural
//
// Future Improvements:
// This implementation of Andersen's algorithm is extremely slow. To make it
-// scale reasonably well, the inclusion constraints could be sorted (easy),
-// offline variable substitution would be a huge win (straight-forward), and
+// scale reasonably well, the inclusion constraints could be sorted (easy),
+// offline variable substitution would be a huge win (straight-forward), and
// online cycle elimination (trickier) might help as well.
//
//===----------------------------------------------------------------------===//
#include <set>
using namespace llvm;
-namespace {
- Statistic<>
- NumIters("anders-aa", "Number of iterations to reach convergence");
- Statistic<>
- NumConstraints("anders-aa", "Number of constraints");
- Statistic<>
- NumNodes("anders-aa", "Number of nodes");
- Statistic<>
- NumEscapingFunctions("anders-aa", "Number of internal functions that escape");
- Statistic<>
- NumIndirectCallees("anders-aa", "Number of indirect callees found");
+STATISTIC(NumIters , "Number of iterations to reach convergence");
+STATISTIC(NumConstraints , "Number of constraints");
+STATISTIC(NumNodes , "Number of nodes");
+STATISTIC(NumEscapingFunctions, "Number of internal functions that escape");
+STATISTIC(NumIndirectCallees , "Number of indirect callees found");
+namespace {
class Andersens : public ModulePass, public AliasAnalysis,
private InstVisitor<Andersens> {
/// Node class - This class is used to represent a memory object in the
}
/// getValue - Return the LLVM value corresponding to this node.
+ ///
Value *getValue() const { return Val; }
typedef std::vector<Node*>::const_iterator iterator;
std::map<Value*, unsigned> ValueNodes;
/// ObjectNodes - This map contains entries for each memory object in the
- /// program: globals, alloca's and mallocs.
+ /// program: globals, alloca's and mallocs.
std::map<Value*, unsigned> ObjectNodes;
/// ReturnNodes - This map contains an entry for each function in the
Constraint(ConstraintType Ty, Node *D, Node *S)
: Type(Ty), Dest(D), Src(S) {}
};
-
+
/// Constraints - This vector contains a list of all of the constraints
/// identified by the program.
std::vector<Constraint> Constraints;
enum {
UniversalSet = 0,
NullPtr = 1,
- NullObject = 2,
+ NullObject = 2
};
-
+
public:
bool runOnModule(Module &M) {
InitializeAliasAnalysis(this);
ReturnNodes.clear();
VarargNodes.clear();
EscapingInternalFunctions.clear();
- std::vector<Constraint>().swap(Constraints);
+ std::vector<Constraint>().swap(Constraints);
return false;
}
//------------------------------------------------
// Implement the AliasAnalysis API
- //
+ //
AliasResult alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size);
+ virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
+ virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
void getMustAliases(Value *P, std::vector<Value*> &RetVals);
bool pointsToConstantMemory(const Value *P);
std::map<Value*, unsigned>::iterator I = ValueNodes.find(V);
if (I == ValueNodes.end()) {
+#ifndef NDEBUG
V->dump();
- assert(I != ValueNodes.end() &&
- "Value does not have a node in the points-to graph!");
+#endif
+ assert(0 && "Value does not have a node in the points-to graph!");
}
return &GraphNodes[I->second];
}
-
+
/// getObject - Return the node corresponding to the memory object for the
/// specified global or allocation instruction.
Node *getObject(Value *V) {
Node *getNodeForConstantPointer(Constant *C);
Node *getNodeForConstantPointerTarget(Constant *C);
void AddGlobalInitializerConstraints(Node *N, Constant *C);
+
void AddConstraintsForNonInternalLinkage(Function *F);
void AddConstraintsForCall(CallSite CS, Function *F);
+ bool AddConstraintsForExternalCall(CallSite CS, Function *F);
void PrintNode(Node *N);
void visitGetElementPtrInst(GetElementPtrInst &GEP);
void visitPHINode(PHINode &PN);
void visitCastInst(CastInst &CI);
+ void visitICmpInst(ICmpInst &ICI) {} // NOOP!
+ void visitFCmpInst(FCmpInst &ICI) {} // NOOP!
void visitSelectInst(SelectInst &SI);
- void visitVANext(VANextInst &I);
void visitVAArg(VAArgInst &I);
void visitInstruction(Instruction &I);
};
- RegisterOpt<Andersens> X("anders-aa",
- "Andersen's Interprocedural Alias Analysis");
- RegisterAnalysisGroup<AliasAnalysis, Andersens> Y;
+ RegisterPass<Andersens> X("anders-aa",
+ "Andersen's Interprocedural Alias Analysis");
+ RegisterAnalysisGroup<AliasAnalysis> Y(X);
}
ModulePass *llvm::createAndersensPass() { return new Andersens(); }
AliasAnalysis::AliasResult Andersens::alias(const Value *V1, unsigned V1Size,
const Value *V2, unsigned V2Size) {
- Node *N1 = getNode((Value*)V1);
- Node *N2 = getNode((Value*)V2);
+ Node *N1 = getNode(const_cast<Value*>(V1));
+ Node *N2 = getNode(const_cast<Value*>(V2));
// Check to see if the two pointers are known to not alias. They don't alias
// if their points-to sets do not intersect.
return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
}
+AliasAnalysis::ModRefResult
+Andersens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
+ // The only thing useful that we can contribute for mod/ref information is
+ // when calling external function calls: if we know that memory never escapes
+ // from the program, it cannot be modified by an external call.
+ //
+ // NOTE: This is not really safe, at least not when the entire program is not
+ // available. The deal is that the external function could call back into the
+ // program and modify stuff. We ignore this technical niggle for now. This
+ // is, after all, a "research quality" implementation of Andersen's analysis.
+ if (Function *F = CS.getCalledFunction())
+ if (F->isExternal()) {
+ Node *N1 = getNode(P);
+
+ if (N1->begin() == N1->end())
+ return NoModRef; // P doesn't point to anything.
+
+ // Get the first pointee.
+ Node *FirstPointee = *N1->begin();
+ if (FirstPointee != &GraphNodes[UniversalSet])
+ return NoModRef; // P doesn't point to the universal set.
+ }
+
+ return AliasAnalysis::getModRefInfo(CS, P, Size);
+}
+
+AliasAnalysis::ModRefResult
+Andersens::getModRefInfo(CallSite CS1, CallSite CS2) {
+ return AliasAnalysis::getModRefInfo(CS1,CS2);
+}
+
/// getMustAlias - We can provide must alias information if we know that a
/// pointer can only point to a specific function or the null pointer.
/// Unfortunately we cannot determine must-alias information for global
}
}
}
-
+
AliasAnalysis::getMustAliases(P, RetVals);
}
switch (CE->getOpcode()) {
case Instruction::GetElementPtr:
return getNodeForConstantPointer(CE->getOperand(0));
- case Instruction::Cast:
- if (isa<PointerType>(CE->getOperand(0)->getType()))
- return getNodeForConstantPointer(CE->getOperand(0));
- else
- return &GraphNodes[UniversalSet];
+ case Instruction::IntToPtr:
+ return &GraphNodes[UniversalSet];
+ case Instruction::BitCast:
+ return getNodeForConstantPointer(CE->getOperand(0));
default:
- std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
+ cerr << "Constant Expr not yet handled: " << *CE << "\n";
assert(0);
}
} else {
switch (CE->getOpcode()) {
case Instruction::GetElementPtr:
return getNodeForConstantPointerTarget(CE->getOperand(0));
- case Instruction::Cast:
- if (isa<PointerType>(CE->getOperand(0)->getType()))
- return getNodeForConstantPointerTarget(CE->getOperand(0));
- else
- return &GraphNodes[UniversalSet];
+ case Instruction::IntToPtr:
+ return &GraphNodes[UniversalSet];
+ case Instruction::BitCast:
+ return getNodeForConstantPointerTarget(CE->getOperand(0));
default:
- std::cerr << "Constant Expr not yet handled: " << *CE << "\n";
+ cerr << "Constant Expr not yet handled: " << *CE << "\n";
assert(0);
}
} else {
void Andersens::AddGlobalInitializerConstraints(Node *N, Constant *C) {
if (C->getType()->isFirstClassType()) {
if (isa<PointerType>(C->getType()))
- N->addPointerTo(getNodeForConstantPointer(C));
+ N->copyFrom(getNodeForConstantPointer(C));
+
} else if (C->isNullValue()) {
N->addPointerTo(&GraphNodes[NullObject]);
return;
- } else {
+ } else if (!isa<UndefValue>(C)) {
// If this is an array or struct, include constraints for each element.
assert(isa<ConstantArray>(C) || isa<ConstantStruct>(C));
for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
}
}
+/// AddConstraintsForNonInternalLinkage - If this function does not have
+/// internal linkage, realize that we can't trust anything passed into or
+/// returned by this function.
void Andersens::AddConstraintsForNonInternalLinkage(Function *F) {
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
if (isa<PointerType>(I->getType()))
&GraphNodes[UniversalSet]));
}
+/// AddConstraintsForCall - If this is a call to a "known" function, add the
+/// constraints and return true. If this is a call to an unknown function,
+/// return false.
+bool Andersens::AddConstraintsForExternalCall(CallSite CS, Function *F) {
+ assert(F->isExternal() && "Not an external function!");
+
+ // These functions don't induce any points-to constraints.
+ if (F->getName() == "atoi" || F->getName() == "atof" ||
+ F->getName() == "atol" || F->getName() == "atoll" ||
+ F->getName() == "remove" || F->getName() == "unlink" ||
+ F->getName() == "rename" || F->getName() == "memcmp" ||
+ F->getName() == "llvm.memset.i32" ||
+ F->getName() == "llvm.memset.i64" ||
+ F->getName() == "strcmp" || F->getName() == "strncmp" ||
+ F->getName() == "execl" || F->getName() == "execlp" ||
+ F->getName() == "execle" || F->getName() == "execv" ||
+ F->getName() == "execvp" || F->getName() == "chmod" ||
+ F->getName() == "puts" || F->getName() == "write" ||
+ F->getName() == "open" || F->getName() == "create" ||
+ F->getName() == "truncate" || F->getName() == "chdir" ||
+ F->getName() == "mkdir" || F->getName() == "rmdir" ||
+ F->getName() == "read" || F->getName() == "pipe" ||
+ F->getName() == "wait" || F->getName() == "time" ||
+ F->getName() == "stat" || F->getName() == "fstat" ||
+ F->getName() == "lstat" || F->getName() == "strtod" ||
+ F->getName() == "strtof" || F->getName() == "strtold" ||
+ F->getName() == "fopen" || F->getName() == "fdopen" ||
+ F->getName() == "freopen" ||
+ F->getName() == "fflush" || F->getName() == "feof" ||
+ F->getName() == "fileno" || F->getName() == "clearerr" ||
+ F->getName() == "rewind" || F->getName() == "ftell" ||
+ F->getName() == "ferror" || F->getName() == "fgetc" ||
+ F->getName() == "fgetc" || F->getName() == "_IO_getc" ||
+ F->getName() == "fwrite" || F->getName() == "fread" ||
+ F->getName() == "fgets" || F->getName() == "ungetc" ||
+ F->getName() == "fputc" ||
+ F->getName() == "fputs" || F->getName() == "putc" ||
+ F->getName() == "ftell" || F->getName() == "rewind" ||
+ F->getName() == "_IO_putc" || F->getName() == "fseek" ||
+ F->getName() == "fgetpos" || F->getName() == "fsetpos" ||
+ F->getName() == "printf" || F->getName() == "fprintf" ||
+ F->getName() == "sprintf" || F->getName() == "vprintf" ||
+ F->getName() == "vfprintf" || F->getName() == "vsprintf" ||
+ F->getName() == "scanf" || F->getName() == "fscanf" ||
+ F->getName() == "sscanf" || F->getName() == "__assert_fail" ||
+ F->getName() == "modf")
+ return true;
+
+
+ // These functions do induce points-to edges.
+ if (F->getName() == "llvm.memcpy.i32" || F->getName() == "llvm.memcpy.i64" ||
+ F->getName() == "llvm.memmove.i32" ||F->getName() == "llvm.memmove.i64" ||
+ F->getName() == "memmove") {
+ // Note: this is a poor approximation, this says Dest = Src, instead of
+ // *Dest = *Src.
+ Constraints.push_back(Constraint(Constraint::Copy,
+ getNode(CS.getArgument(0)),
+ getNode(CS.getArgument(1))));
+ return true;
+ }
+
+ // Result = Arg0
+ if (F->getName() == "realloc" || F->getName() == "strchr" ||
+ F->getName() == "strrchr" || F->getName() == "strstr" ||
+ F->getName() == "strtok") {
+ Constraints.push_back(Constraint(Constraint::Copy,
+ getNode(CS.getInstruction()),
+ getNode(CS.getArgument(0))));
+ return true;
+ }
+
+ return false;
+}
+
+
/// CollectConstraints - This stage scans the program, adding a constraint to
/// the Constraints list for each instruction in the program that induces a
void Andersens::CollectConstraints(Module &M) {
// First, the universal set points to itself.
GraphNodes[UniversalSet].addPointerTo(&GraphNodes[UniversalSet]);
+ //Constraints.push_back(Constraint(Constraint::Load, &GraphNodes[UniversalSet],
+ // &GraphNodes[UniversalSet]));
+ Constraints.push_back(Constraint(Constraint::Store, &GraphNodes[UniversalSet],
+ &GraphNodes[UniversalSet]));
// Next, the null pointer points to the null object.
GraphNodes[NullPtr].addPointerTo(&GraphNodes[NullObject]);
&GraphNodes[UniversalSet]));
}
}
-
+
for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
// Make the function address point to the function object.
getNodeValue(*F)->addPointerTo(getObject(F)->setValue(F));
case Instruction::Unreachable:
case Instruction::Free:
case Instruction::Shl:
- case Instruction::Shr:
+ case Instruction::LShr:
+ case Instruction::AShr:
+ case Instruction::ICmp:
+ case Instruction::FCmp:
return;
default:
// Is this something we aren't handling yet?
- std::cerr << "Unknown instruction: " << I;
+ cerr << "Unknown instruction: " << I;
abort();
}
}
getNode(CI.getOperand(0))));
} else {
// P1 = cast int --> <Copy/P1/Univ>
+#if 0
Constraints.push_back(Constraint(Constraint::Copy, getNodeValue(CI),
&GraphNodes[UniversalSet]));
+#else
+ getNodeValue(CI);
+#endif
}
} else if (isa<PointerType>(Op->getType())) {
// int = cast P1 --> <Copy/Univ/P1>
+#if 0
Constraints.push_back(Constraint(Constraint::Copy,
&GraphNodes[UniversalSet],
getNode(CI.getOperand(0))));
+#else
+ getNode(CI.getOperand(0));
+#endif
}
}
}
}
-void Andersens::visitVANext(VANextInst &I) {
- // FIXME: Implement
- assert(0 && "vanext not handled yet!");
-}
void Andersens::visitVAArg(VAArgInst &I) {
assert(0 && "vaarg not handled yet!");
}
/// the function pointer has been casted. If this is the case, do something
/// reasonable.
void Andersens::AddConstraintsForCall(CallSite CS, Function *F) {
+ // If this is a call to an external function, handle it directly to get some
+ // taste of context sensitivity.
+ if (F->isExternal() && AddConstraintsForExternalCall(CS, F))
+ return;
+
if (isa<PointerType>(CS.getType())) {
Node *CSN = getNode(CS.getInstruction());
if (isa<PointerType>(F->getFunctionType()->getReturnType())) {
&GraphNodes[UniversalSet],
getReturnNode(F)));
}
-
+
Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
CallSite::arg_iterator ArgI = CS.arg_begin(), ArgE = CS.arg_end();
for (; AI != AE && ArgI != ArgE; ++AI, ++ArgI)
&GraphNodes[UniversalSet],
getNode(*ArgI)));
}
-
+
// Copy all pointers passed through the varargs section to the varargs node.
if (F->getFunctionType()->isVarArg())
for (; ArgI != ArgE; ++ArgI)
while (Changed) {
Changed = false;
++NumIters;
- DEBUG(std::cerr << "Starting iteration #" << Iteration++ << "!\n");
+ DOUT << "Starting iteration #" << Iteration++ << "!\n";
// Loop over all of the constraints, applying them in turn.
for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
// We found a function that is just now escaping. Mark it as if it
// didn't have internal linkage.
AddConstraintsForNonInternalLinkage(F);
- DEBUG(std::cerr << "Found escaping internal function: "
- << F->getName() << "\n");
+ DOUT << "Found escaping internal function: " << F->getName() <<"\n";
++NumEscapingFunctions;
}
if (IP == KnownCallees.end() || *IP != F) {
// Add the constraints for the call now.
AddConstraintsForCall(CS, F);
- DEBUG(std::cerr << "Found actual callee '"
- << F->getName() << "' for call: "
- << *CS.getInstruction() << "\n");
+ DOUT << "Found actual callee '"
+ << F->getName() << "' for call: "
+ << *CS.getInstruction() << "\n";
++NumIndirectCallees;
KnownCallees.insert(IP, F);
}
void Andersens::PrintNode(Node *N) {
if (N == &GraphNodes[UniversalSet]) {
- std::cerr << "<universal>";
+ cerr << "<universal>";
return;
} else if (N == &GraphNodes[NullPtr]) {
- std::cerr << "<nullptr>";
+ cerr << "<nullptr>";
return;
} else if (N == &GraphNodes[NullObject]) {
- std::cerr << "<null>";
+ cerr << "<null>";
return;
}
if (Function *F = dyn_cast<Function>(V)) {
if (isa<PointerType>(F->getFunctionType()->getReturnType()) &&
N == getReturnNode(F)) {
- std::cerr << F->getName() << ":retval";
+ cerr << F->getName() << ":retval";
return;
} else if (F->getFunctionType()->isVarArg() && N == getVarargNode(F)) {
- std::cerr << F->getName() << ":vararg";
+ cerr << F->getName() << ":vararg";
return;
}
}
if (Instruction *I = dyn_cast<Instruction>(V))
- std::cerr << I->getParent()->getParent()->getName() << ":";
+ cerr << I->getParent()->getParent()->getName() << ":";
else if (Argument *Arg = dyn_cast<Argument>(V))
- std::cerr << Arg->getParent()->getName() << ":";
+ cerr << Arg->getParent()->getName() << ":";
if (V->hasName())
- std::cerr << V->getName();
+ cerr << V->getName();
else
- std::cerr << "(unnamed)";
+ cerr << "(unnamed)";
if (isa<GlobalValue>(V) || isa<AllocationInst>(V))
if (N == getObject(V))
- std::cerr << "<mem>";
+ cerr << "<mem>";
}
void Andersens::PrintConstraints() {
- std::cerr << "Constraints:\n";
+ cerr << "Constraints:\n";
for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
- std::cerr << " #" << i << ": ";
+ cerr << " #" << i << ": ";
Constraint &C = Constraints[i];
if (C.Type == Constraint::Store)
- std::cerr << "*";
+ cerr << "*";
PrintNode(C.Dest);
- std::cerr << " = ";
+ cerr << " = ";
if (C.Type == Constraint::Load)
- std::cerr << "*";
+ cerr << "*";
PrintNode(C.Src);
- std::cerr << "\n";
+ cerr << "\n";
}
}
void Andersens::PrintPointsToGraph() {
- std::cerr << "Points-to graph:\n";
+ cerr << "Points-to graph:\n";
for (unsigned i = 0, e = GraphNodes.size(); i != e; ++i) {
Node *N = &GraphNodes[i];
- std::cerr << "[" << (N->end() - N->begin()) << "] ";
+ cerr << "[" << (N->end() - N->begin()) << "] ";
PrintNode(N);
- std::cerr << "\t--> ";
+ cerr << "\t--> ";
for (Node::iterator I = N->begin(), E = N->end(); I != E; ++I) {
- if (I != N->begin()) std::cerr << ", ";
+ if (I != N->begin()) cerr << ", ";
PrintNode(*I);
}
- std::cerr << "\n";
+ cerr << "\n";
}
}