1 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass uses the data structure graphs to implement a simple context
11 // insensitive alias analysis. It does this by computing the local analysis
12 // graphs for all of the functions, then merging them together into a single big
13 // graph without cloning.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/DataStructure/DataStructure.h"
18 #include "llvm/Analysis/DataStructure/DSGraph.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/Passes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/Debug.h"
27 class Steens : public ModulePass, public AliasAnalysis {
30 EquivalenceClasses<GlobalValue*> GlobalECs; // Always empty
32 Steens() : ResultGraph(0) {}
35 assert(ResultGraph == 0 && "releaseMemory not called?");
38 //------------------------------------------------
39 // Implement the Pass API
42 // run - Build up the result graph, representing the pointer graph for the
45 bool runOnModule(Module &M);
47 virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
49 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50 AliasAnalysis::getAnalysisUsage(AU);
51 AU.setPreservesAll(); // Does not transform code...
52 AU.addRequired<LocalDataStructures>(); // Uses local dsgraph
55 // print - Implement the Pass::print method...
56 void print(std::ostream &O, const Module *M) const {
57 assert(ResultGraph && "Result graph has not yet been computed!");
58 ResultGraph->writeGraphToFile(O, "steensgaards");
61 //------------------------------------------------
62 // Implement the AliasAnalysis API
65 AliasResult alias(const Value *V1, unsigned V1Size,
66 const Value *V2, unsigned V2Size);
68 virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
69 virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
72 void ResolveFunctionCall(Function *F, const DSCallSite &Call,
73 DSNodeHandle &RetVal);
76 // Register the pass...
77 RegisterPass<Steens> X("steens-aa",
78 "Steensgaard's alias analysis (DSGraph based)");
80 // Register as an implementation of AliasAnalysis
81 RegisterAnalysisGroup<AliasAnalysis> Y(X);
84 ModulePass *llvm::createSteensgaardPass() { return new Steens(); }
86 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
87 /// with the specified call site descriptor. This function links the arguments
88 /// and the return value for the call site context-insensitively.
90 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
91 DSNodeHandle &RetVal) {
92 assert(ResultGraph != 0 && "Result graph not allocated!");
93 DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
95 // Handle the return value of the function...
96 if (Call.getRetVal().getNode() && RetVal.getNode())
97 RetVal.mergeWith(Call.getRetVal());
99 // Loop over all pointer arguments, resolving them to their provided pointers
100 unsigned PtrArgIdx = 0;
101 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
102 AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
103 DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
104 if (I != ValMap.end()) // If its a pointer argument...
105 I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
110 /// run - Build up the result graph, representing the pointer graph for the
113 bool Steens::runOnModule(Module &M) {
114 InitializeAliasAnalysis(this);
115 assert(ResultGraph == 0 && "Result graph already allocated!");
116 LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
118 // Create a new, empty, graph...
119 ResultGraph = new DSGraph(GlobalECs, getTargetData());
120 ResultGraph->spliceFrom(LDS.getGlobalsGraph());
122 // Loop over the rest of the module, merging graphs for non-external functions
125 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
126 if (!I->isExternal())
127 ResultGraph->spliceFrom(LDS.getDSGraph(*I));
129 ResultGraph->removeTriviallyDeadNodes();
131 // FIXME: Must recalculate and use the Incomplete markers!!
133 // Now that we have all of the graphs inlined, we can go about eliminating
136 std::list<DSCallSite> &Calls = ResultGraph->getAuxFunctionCalls();
137 assert(Calls.empty() && "Aux call list is already in use??");
139 // Start with a copy of the original call sites.
140 Calls = ResultGraph->getFunctionCalls();
142 for (std::list<DSCallSite>::iterator CI = Calls.begin(), E = Calls.end();
144 DSCallSite &CurCall = *CI++;
146 // Loop over the called functions, eliminating as many as possible...
147 std::vector<Function*> CallTargets;
148 if (CurCall.isDirectCall())
149 CallTargets.push_back(CurCall.getCalleeFunc());
151 CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
153 for (unsigned c = 0; c != CallTargets.size(); ) {
154 // If we can eliminate this function call, do so!
155 Function *F = CallTargets[c];
156 if (!F->isExternal()) {
157 ResolveFunctionCall(F, CurCall, ResultGraph->getReturnNodes()[F]);
158 CallTargets[c] = CallTargets.back();
159 CallTargets.pop_back();
161 ++c; // Cannot eliminate this call, skip over it...
164 if (CallTargets.empty()) { // Eliminated all calls?
165 std::list<DSCallSite>::iterator I = CI;
166 Calls.erase(--I); // Remove entry
170 // Remove our knowledge of what the return values of the functions are, except
171 // for functions that are externally visible from this module (e.g. main). We
172 // keep these functions so that their arguments are marked incomplete.
173 for (DSGraph::ReturnNodesTy::iterator I =
174 ResultGraph->getReturnNodes().begin(),
175 E = ResultGraph->getReturnNodes().end(); I != E; )
176 if (I->first->hasInternalLinkage())
177 ResultGraph->getReturnNodes().erase(I++);
181 // Update the "incomplete" markers on the nodes, ignoring unknownness due to
182 // incoming arguments...
183 ResultGraph->maskIncompleteMarkers();
184 ResultGraph->markIncompleteNodes(DSGraph::IgnoreGlobals |
185 DSGraph::MarkFormalArgs);
187 // Remove any nodes that are dead after all of the merging we have done...
188 // FIXME: We should be able to disable the globals graph for steens!
189 //ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
191 DEBUG(print(std::cerr, &M));
195 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
196 const Value *V2, unsigned V2Size) {
197 assert(ResultGraph && "Result graph has not been computed yet!");
199 DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
201 DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
202 DSGraph::ScalarMapTy::iterator J = GSM.find(const_cast<Value*>(V2));
203 if (I != GSM.end() && !I->second.isNull() &&
204 J != GSM.end() && !J->second.isNull()) {
205 DSNodeHandle &V1H = I->second;
206 DSNodeHandle &V2H = J->second;
208 // If at least one of the nodes is complete, we can say something about
209 // this. If one is complete and the other isn't, then they are obviously
210 // different nodes. If they are both complete, we can't say anything
212 if (I->second.getNode()->isComplete() ||
213 J->second.getNode()->isComplete()) {
214 // If the two pointers point to different data structure graph nodes, they
216 if (V1H.getNode() != V2H.getNode())
219 // See if they point to different offsets... if so, we may be able to
220 // determine that they do not alias...
221 unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
223 if (O2 < O1) { // Ensure that O1 <= O2
226 std::swap(V1Size, V2Size);
235 // If we cannot determine alias properties based on our graph, fall back on
236 // some other AA implementation.
238 return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
241 AliasAnalysis::ModRefResult
242 Steens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
243 AliasAnalysis::ModRefResult Result = ModRef;
245 // Find the node in question.
246 DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
247 DSGraph::ScalarMapTy::iterator I = GSM.find(P);
249 if (I != GSM.end() && !I->second.isNull()) {
250 DSNode *N = I->second.getNode();
251 if (N->isComplete()) {
252 // If this is a direct call to an external function, and if the pointer
253 // points to a complete node, the external function cannot modify or read
254 // the value (we know it's not passed out of the program!).
255 if (Function *F = CS.getCalledFunction())
259 // Otherwise, if the node is complete, but it is only M or R, return this.
260 // This can be useful for globals that should be marked const but are not.
261 if (!N->isModified())
262 Result = (ModRefResult)(Result & ~Mod);
264 Result = (ModRefResult)(Result & ~Ref);
268 return (ModRefResult)(Result & AliasAnalysis::getModRefInfo(CS, P, Size));
271 AliasAnalysis::ModRefResult
272 Steens::getModRefInfo(CallSite CS1, CallSite CS2)
274 return AliasAnalysis::getModRefInfo(CS1,CS2);