Replacing std::iostreams with llvm iostreams. Some of these changes involve
[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 <ostream>
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(llvm_ostream O, const Module *M) const {
57       if (O.stream()) print(*O.stream(), M);
58     }
59     void print(std::ostream &O, const Module *M) const {
60       assert(ResultGraph && "Result graph has not yet been computed!");
61       ResultGraph->writeGraphToFile(O, "steensgaards");
62     }
63
64     //------------------------------------------------
65     // Implement the AliasAnalysis API
66     //
67
68     AliasResult alias(const Value *V1, unsigned V1Size,
69                       const Value *V2, unsigned V2Size);
70
71     virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
72     virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
73
74   private:
75     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
76                              DSNodeHandle &RetVal);
77   };
78
79   // Register the pass...
80   RegisterPass<Steens> X("steens-aa",
81                          "Steensgaard's alias analysis (DSGraph based)");
82
83   // Register as an implementation of AliasAnalysis
84   RegisterAnalysisGroup<AliasAnalysis> Y(X);
85 }
86
87 ModulePass *llvm::createSteensgaardPass() { return new Steens(); }
88
89 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
90 /// with the specified call site descriptor.  This function links the arguments
91 /// and the return value for the call site context-insensitively.
92 ///
93 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
94                                  DSNodeHandle &RetVal) {
95   assert(ResultGraph != 0 && "Result graph not allocated!");
96   DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
97
98   // Handle the return value of the function...
99   if (Call.getRetVal().getNode() && RetVal.getNode())
100     RetVal.mergeWith(Call.getRetVal());
101
102   // Loop over all pointer arguments, resolving them to their provided pointers
103   unsigned PtrArgIdx = 0;
104   for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
105        AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
106     DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
107     if (I != ValMap.end())    // If its a pointer argument...
108       I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
109   }
110 }
111
112
113 /// run - Build up the result graph, representing the pointer graph for the
114 /// program.
115 ///
116 bool Steens::runOnModule(Module &M) {
117   InitializeAliasAnalysis(this);
118   assert(ResultGraph == 0 && "Result graph already allocated!");
119   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
120
121   // Create a new, empty, graph...
122   ResultGraph = new DSGraph(GlobalECs, getTargetData());
123   ResultGraph->spliceFrom(LDS.getGlobalsGraph());
124
125   // Loop over the rest of the module, merging graphs for non-external functions
126   // into this graph.
127   //
128   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
129     if (!I->isExternal())
130       ResultGraph->spliceFrom(LDS.getDSGraph(*I));
131
132   ResultGraph->removeTriviallyDeadNodes();
133
134   // FIXME: Must recalculate and use the Incomplete markers!!
135
136   // Now that we have all of the graphs inlined, we can go about eliminating
137   // call nodes...
138   //
139   std::list<DSCallSite> &Calls = ResultGraph->getAuxFunctionCalls();
140   assert(Calls.empty() && "Aux call list is already in use??");
141
142   // Start with a copy of the original call sites.
143   Calls = ResultGraph->getFunctionCalls();
144
145   for (std::list<DSCallSite>::iterator CI = Calls.begin(), E = Calls.end();
146        CI != E;) {
147     DSCallSite &CurCall = *CI++;
148
149     // Loop over the called functions, eliminating as many as possible...
150     std::vector<Function*> CallTargets;
151     if (CurCall.isDirectCall())
152       CallTargets.push_back(CurCall.getCalleeFunc());
153     else
154       CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
155
156     for (unsigned c = 0; c != CallTargets.size(); ) {
157       // If we can eliminate this function call, do so!
158       Function *F = CallTargets[c];
159       if (!F->isExternal()) {
160         ResolveFunctionCall(F, CurCall, ResultGraph->getReturnNodes()[F]);
161         CallTargets[c] = CallTargets.back();
162         CallTargets.pop_back();
163       } else
164         ++c;  // Cannot eliminate this call, skip over it...
165     }
166
167     if (CallTargets.empty()) {        // Eliminated all calls?
168       std::list<DSCallSite>::iterator I = CI;
169       Calls.erase(--I);               // Remove entry
170     }
171   }
172
173   // Remove our knowledge of what the return values of the functions are, except
174   // for functions that are externally visible from this module (e.g. main).  We
175   // keep these functions so that their arguments are marked incomplete.
176   for (DSGraph::ReturnNodesTy::iterator I =
177          ResultGraph->getReturnNodes().begin(),
178          E = ResultGraph->getReturnNodes().end(); I != E; )
179     if (I->first->hasInternalLinkage())
180       ResultGraph->getReturnNodes().erase(I++);
181     else
182       ++I;
183
184   // Update the "incomplete" markers on the nodes, ignoring unknownness due to
185   // incoming arguments...
186   ResultGraph->maskIncompleteMarkers();
187   ResultGraph->markIncompleteNodes(DSGraph::IgnoreGlobals |
188                                    DSGraph::MarkFormalArgs);
189
190   // Remove any nodes that are dead after all of the merging we have done...
191   // FIXME: We should be able to disable the globals graph for steens!
192   //ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
193
194   print(DOUT, &M);
195   return false;
196 }
197
198 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
199                                          const Value *V2, unsigned V2Size) {
200   assert(ResultGraph && "Result graph has not been computed yet!");
201
202   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
203
204   DSGraph::ScalarMapTy::iterator I = GSM.find(const_cast<Value*>(V1));
205   DSGraph::ScalarMapTy::iterator J = GSM.find(const_cast<Value*>(V2));
206   if (I != GSM.end() && !I->second.isNull() &&
207       J != GSM.end() && !J->second.isNull()) {
208     DSNodeHandle &V1H = I->second;
209     DSNodeHandle &V2H = J->second;
210
211     // If at least one of the nodes is complete, we can say something about
212     // this.  If one is complete and the other isn't, then they are obviously
213     // different nodes.  If they are both complete, we can't say anything
214     // useful.
215     if (I->second.getNode()->isComplete() ||
216         J->second.getNode()->isComplete()) {
217       // If the two pointers point to different data structure graph nodes, they
218       // cannot alias!
219       if (V1H.getNode() != V2H.getNode())
220         return NoAlias;
221
222       // See if they point to different offsets...  if so, we may be able to
223       // determine that they do not alias...
224       unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
225       if (O1 != O2) {
226         if (O2 < O1) {    // Ensure that O1 <= O2
227           std::swap(V1, V2);
228           std::swap(O1, O2);
229           std::swap(V1Size, V2Size);
230         }
231
232         if (O1+V1Size <= O2)
233           return NoAlias;
234       }
235     }
236   }
237
238   // If we cannot determine alias properties based on our graph, fall back on
239   // some other AA implementation.
240   //
241   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
242 }
243
244 AliasAnalysis::ModRefResult
245 Steens::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
246   AliasAnalysis::ModRefResult Result = ModRef;
247
248   // Find the node in question.
249   DSGraph::ScalarMapTy &GSM = ResultGraph->getScalarMap();
250   DSGraph::ScalarMapTy::iterator I = GSM.find(P);
251
252   if (I != GSM.end() && !I->second.isNull()) {
253     DSNode *N = I->second.getNode();
254     if (N->isComplete()) {
255       // If this is a direct call to an external function, and if the pointer
256       // points to a complete node, the external function cannot modify or read
257       // the value (we know it's not passed out of the program!).
258       if (Function *F = CS.getCalledFunction())
259         if (F->isExternal())
260           return NoModRef;
261
262       // Otherwise, if the node is complete, but it is only M or R, return this.
263       // This can be useful for globals that should be marked const but are not.
264       if (!N->isModified())
265         Result = (ModRefResult)(Result & ~Mod);
266       if (!N->isRead())
267         Result = (ModRefResult)(Result & ~Ref);
268     }
269   }
270
271   return (ModRefResult)(Result & AliasAnalysis::getModRefInfo(CS, P, Size));
272 }
273
274 AliasAnalysis::ModRefResult 
275 Steens::getModRefInfo(CallSite CS1, CallSite CS2)
276 {
277   return AliasAnalysis::getModRefInfo(CS1,CS2);
278 }