Added LLVM project notice to the top of every C++ source file.
[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.h"
18 #include "llvm/Analysis/DSGraph.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Module.h"
21 #include "Support/Debug.h"
22
23 namespace {
24   class Steens : public Pass, public AliasAnalysis {
25     DSGraph *ResultGraph;
26     DSGraph *GlobalsGraph;  // FIXME: Eliminate globals graph stuff from DNE
27   public:
28     Steens() : ResultGraph(0), GlobalsGraph(0) {}
29     ~Steens() {
30       releaseMyMemory();
31       assert(ResultGraph == 0 && "releaseMemory not called?");
32     }
33
34     //------------------------------------------------
35     // Implement the Pass API
36     //
37
38     // run - Build up the result graph, representing the pointer graph for the
39     // program.
40     //
41     bool run(Module &M);
42
43     virtual void releaseMyMemory() { delete ResultGraph; ResultGraph = 0; }
44
45     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46       AliasAnalysis::getAnalysisUsage(AU);
47       AU.setPreservesAll();                    // Does not transform code...
48       AU.addRequired<LocalDataStructures>();   // Uses local dsgraph
49       AU.addRequired<AliasAnalysis>();         // Chains to another AA impl...
50     }
51
52     // print - Implement the Pass::print method...
53     void print(std::ostream &O, const Module *M) const {
54       assert(ResultGraph && "Result graph has not yet been computed!");
55       ResultGraph->writeGraphToFile(O, "steensgaards");
56     }
57
58     //------------------------------------------------
59     // Implement the AliasAnalysis API
60     //  
61
62     // alias - This is the only method here that does anything interesting...
63     AliasResult alias(const Value *V1, unsigned V1Size,
64                       const Value *V2, unsigned V2Size);
65     
66   private:
67     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
68                              DSNodeHandle &RetVal);
69   };
70
71   // Register the pass...
72   RegisterOpt<Steens> X("steens-aa",
73                         "Steensgaard's alias analysis (DSGraph based)");
74
75   // Register as an implementation of AliasAnalysis
76   RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
77 }
78
79
80 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
81 /// with the specified call site descriptor.  This function links the arguments
82 /// and the return value for the call site context-insensitively.
83 ///
84 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
85                                  DSNodeHandle &RetVal) {
86   assert(ResultGraph != 0 && "Result graph not allocated!");
87   DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
88
89   // Handle the return value of the function...
90   if (Call.getRetVal().getNode() && RetVal.getNode())
91     RetVal.mergeWith(Call.getRetVal());
92
93   // Loop over all pointer arguments, resolving them to their provided pointers
94   unsigned PtrArgIdx = 0;
95   for (Function::aiterator AI = F->abegin(), AE = F->aend();
96        AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
97     DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
98     if (I != ValMap.end())    // If its a pointer argument...
99       I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
100   }
101 }
102
103
104 /// run - Build up the result graph, representing the pointer graph for the
105 /// program.
106 ///
107 bool Steens::run(Module &M) {
108   InitializeAliasAnalysis(this);
109   assert(ResultGraph == 0 && "Result graph already allocated!");
110   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
111
112   // Create a new, empty, graph...
113   ResultGraph = new DSGraph();
114   GlobalsGraph = new DSGraph();
115   ResultGraph->setGlobalsGraph(GlobalsGraph);
116   ResultGraph->setPrintAuxCalls();
117
118   // RetValMap - Keep track of the return values for all functions that return
119   // valid pointers.
120   //
121   DSGraph::ReturnNodesTy RetValMap;
122
123   // Loop over the rest of the module, merging graphs for non-external functions
124   // into this graph.
125   //
126   unsigned Count = 0;
127   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
128     if (!I->isExternal()) {
129       DSGraph::ScalarMapTy ValMap;
130       {  // Scope to free NodeMap memory ASAP
131         DSGraph::NodeMapTy NodeMap;
132         const DSGraph &FDSG = LDS.getDSGraph(*I);
133         ResultGraph->cloneInto(FDSG, ValMap, RetValMap, NodeMap);
134       }
135
136       // Incorporate the inlined Function's ScalarMap into the global
137       // ScalarMap...
138       DSGraph::ScalarMapTy &GVM = ResultGraph->getScalarMap();
139       for (DSGraph::ScalarMapTy::iterator I = ValMap.begin(),
140              E = ValMap.end(); I != E; ++I)
141         GVM[I->first].mergeWith(I->second);
142
143       if ((++Count & 1) == 0)   // Prune nodes out every other time...
144         ResultGraph->removeTriviallyDeadNodes();
145     }
146
147   // FIXME: Must recalculate and use the Incomplete markers!!
148
149   // Now that we have all of the graphs inlined, we can go about eliminating
150   // call nodes...
151   //
152   std::vector<DSCallSite> &Calls =
153     ResultGraph->getAuxFunctionCalls();
154   assert(Calls.empty() && "Aux call list is already in use??");
155
156   // Start with a copy of the original call sites...
157   Calls = ResultGraph->getFunctionCalls();
158
159   for (unsigned i = 0; i != Calls.size(); ) {
160     DSCallSite &CurCall = Calls[i];
161     
162     // Loop over the called functions, eliminating as many as possible...
163     std::vector<GlobalValue*> CallTargets;
164     if (CurCall.isDirectCall())
165       CallTargets.push_back(CurCall.getCalleeFunc());
166     else 
167       CallTargets = CurCall.getCalleeNode()->getGlobals();
168
169     for (unsigned c = 0; c != CallTargets.size(); ) {
170       // If we can eliminate this function call, do so!
171       bool Eliminated = false;
172       if (Function *F = dyn_cast<Function>(CallTargets[c]))
173         if (!F->isExternal()) {
174           ResolveFunctionCall(F, CurCall, RetValMap[F]);
175           Eliminated = true;
176         }
177       if (Eliminated) {
178         CallTargets[c] = CallTargets.back();
179         CallTargets.pop_back();
180       } else
181         ++c;  // Cannot eliminate this call, skip over it...
182     }
183
184     if (CallTargets.empty()) {        // Eliminated all calls?
185       CurCall = Calls.back();         // Remove entry
186       Calls.pop_back();
187     } else
188       ++i;                            // Skip this call site...
189   }
190
191   RetValMap.clear();
192
193   // Update the "incomplete" markers on the nodes, ignoring unknownness due to
194   // incoming arguments...
195   ResultGraph->maskIncompleteMarkers();
196   ResultGraph->markIncompleteNodes(DSGraph::IgnoreFormalArgs);
197
198   // Remove any nodes that are dead after all of the merging we have done...
199   // FIXME: We should be able to disable the globals graph for steens!
200   ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
201
202   DEBUG(print(std::cerr, &M));
203   return false;
204 }
205
206 // alias - This is the only method here that does anything interesting...
207 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
208                                          const Value *V2, unsigned V2Size) {
209   // FIXME: HANDLE Size argument!
210   assert(ResultGraph && "Result graph has not been computed yet!");
211
212   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
213
214   DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
215   if (I != GSM.end() && I->second.getNode()) {
216     DSNodeHandle &V1H = I->second;
217     DSGraph::ScalarMapTy::iterator J=GSM.find(const_cast<Value*>(V2));
218     if (J != GSM.end() && J->second.getNode()) {
219       DSNodeHandle &V2H = J->second;
220       // If the two pointers point to different data structure graph nodes, they
221       // cannot alias!
222       if (V1H.getNode() != V2H.getNode())    // FIXME: Handle incompleteness!
223         return NoAlias;
224
225       // FIXME: If the two pointers point to the same node, and the offsets are
226       // different, and the LinkIndex vector doesn't alias the section, then the
227       // two pointers do not alias.  We need access size information for the two
228       // accesses though!
229       //
230     }
231   }
232
233   // If we cannot determine alias properties based on our graph, fall back on
234   // some other AA implementation.
235   //
236   return getAnalysis<AliasAnalysis>().alias(V1, V1Size, V2, V2Size);
237 }