For PR950:
[oota-llvm.git] / lib / Analysis / DataStructure / Steensgaard.cpp
1 //===- Steensgaard.cpp - Context Insensitive Alias Analysis ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
23 #include <iostream>
24 using namespace llvm;
25
26 namespace {
27   class Steens : public ModulePass, public AliasAnalysis {
28     DSGraph *ResultGraph;
29
30     EquivalenceClasses<GlobalValue*> GlobalECs;  // Always empty
31   public:
32     Steens() : ResultGraph(0) {}
33     ~Steens() {
34       releaseMyMemory();
35       assert(ResultGraph == 0 && "releaseMemory not called?");
36     }
37
38     //------------------------------------------------
39     // Implement the Pass API
40     //
41
42     // run - Build up the result graph, representing the pointer graph for the
43     // program.
44     //
45     bool runOnModule(Module &M);
46
47     virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
48
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
53     }
54
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");
59     }
60
61     //------------------------------------------------
62     // Implement the AliasAnalysis API
63     //
64
65     AliasResult alias(const Value *V1, unsigned V1Size,
66                       const Value *V2, unsigned V2Size);
67
68     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
69     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
70
71   private:
72     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
73                              DSNodeHandle &RetVal);
74   };
75
76   // Register the pass...
77   RegisterPass<Steens> X("steens-aa",
78                          "Steensgaard's alias analysis (DSGraph based)");
79
80   // Register as an implementation of AliasAnalysis
81   RegisterAnalysisGroup<AliasAnalysis> Y(X);
82 }
83
84 ModulePass *llvm::createSteensgaardPass() { return new Steens(); }
85
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.
89 ///
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();
94
95   // Handle the return value of the function...
96   if (Call.getRetVal().getNode() && RetVal.getNode())
97     RetVal.mergeWith(Call.getRetVal());
98
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++));
106   }
107 }
108
109
110 /// run - Build up the result graph, representing the pointer graph for the
111 /// program.
112 ///
113 bool Steens::runOnModule(Module &M) {
114   InitializeAliasAnalysis(this);
115   assert(ResultGraph == 0 && "Result graph already allocated!");
116   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
117
118   // Create a new, empty, graph...
119   ResultGraph = new DSGraph(GlobalECs, getTargetData());
120   ResultGraph->spliceFrom(LDS.getGlobalsGraph());
121
122   // Loop over the rest of the module, merging graphs for non-external functions
123   // into this graph.
124   //
125   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
126     if (!I->isExternal())
127       ResultGraph->spliceFrom(LDS.getDSGraph(*I));
128
129   ResultGraph->removeTriviallyDeadNodes();
130
131   // FIXME: Must recalculate and use the Incomplete markers!!
132
133   // Now that we have all of the graphs inlined, we can go about eliminating
134   // call nodes...
135   //
136   std::list<DSCallSite> &Calls = ResultGraph->getAuxFunctionCalls();
137   assert(Calls.empty() && "Aux call list is already in use??");
138
139   // Start with a copy of the original call sites.
140   Calls = ResultGraph->getFunctionCalls();
141
142   for (std::list<DSCallSite>::iterator CI = Calls.begin(), E = Calls.end();
143        CI != E;) {
144     DSCallSite &CurCall = *CI++;
145
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());
150     else
151       CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
152
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();
160       } else
161         ++c;  // Cannot eliminate this call, skip over it...
162     }
163
164     if (CallTargets.empty()) {        // Eliminated all calls?
165       std::list<DSCallSite>::iterator I = CI;
166       Calls.erase(--I);               // Remove entry
167     }
168   }
169
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++);
178     else
179       ++I;
180
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);
186
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);
190
191   DEBUG(print(std::cerr, &M));
192   return false;
193 }
194
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!");
198
199   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
200
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;
207
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
211     // useful.
212     if (I->second.getNode()->isComplete() ||
213         J->second.getNode()->isComplete()) {
214       // If the two pointers point to different data structure graph nodes, they
215       // cannot alias!
216       if (V1H.getNode() != V2H.getNode())
217         return NoAlias;
218
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();
222       if (O1 != O2) {
223         if (O2 < O1) {    // Ensure that O1 <= O2
224           std::swap(V1, V2);
225           std::swap(O1, O2);
226           std::swap(V1Size, V2Size);
227         }
228
229         if (O1+V1Size <= O2)
230           return NoAlias;
231       }
232     }
233   }
234
235   // If we cannot determine alias properties based on our graph, fall back on
236   // some other AA implementation.
237   //
238   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
239 }
240
241 AliasAnalysis::ModRefResult
242 Steens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
243   AliasAnalysis::ModRefResult Result = ModRef;
244
245   // Find the node in question.
246   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
247   DSGraph::ScalarMapTy::iterator I = GSM.find(P);
248
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())
256         if (F->isExternal())
257           return NoModRef;
258
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);
263       if (!N->isRead())
264         Result = (ModRefResult)(Result & ~Ref);
265     }
266   }
267
268   return (ModRefResult)(Result & AliasAnalysis::getModRefInfo(CS, P, Size));
269 }
270
271 AliasAnalysis::ModRefResult 
272 Steens::getModRefInfo(CallSite CS1, CallSite CS2)
273 {
274   return AliasAnalysis::getModRefInfo(CS1,CS2);
275 }