d6740277815bef66832322352a705ebc93fdccce
[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 using namespace llvm;
24
25 namespace {
26   class Steens : public ModulePass, public AliasAnalysis {
27     DSGraph *ResultGraph;
28     DSGraph *GlobalsGraph;  // FIXME: Eliminate globals graph stuff from DNE
29
30     EquivalenceClasses<GlobalValue*> GlobalECs;  // Always empty
31   public:
32     Steens() : ResultGraph(0), GlobalsGraph(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     // alias - This is the only method here that does anything interesting...
66     AliasResult alias(const Value *V1, unsigned V1Size,
67                       const Value *V2, unsigned V2Size);
68     
69   private:
70     void ResolveFunctionCall(Function *F, const DSCallSite &Call,
71                              DSNodeHandle &RetVal);
72   };
73
74   // Register the pass...
75   RegisterOpt<Steens> X("steens-aa",
76                         "Steensgaard's alias analysis (DSGraph based)");
77
78   // Register as an implementation of AliasAnalysis
79   RegisterAnalysisGroup<AliasAnalysis, Steens> Y;
80 }
81
82 ModulePass *llvm::createSteensgaardPass() { return new Steens(); }
83
84 /// ResolveFunctionCall - Resolve the actual arguments of a call to function F
85 /// with the specified call site descriptor.  This function links the arguments
86 /// and the return value for the call site context-insensitively.
87 ///
88 void Steens::ResolveFunctionCall(Function *F, const DSCallSite &Call,
89                                  DSNodeHandle &RetVal) {
90   assert(ResultGraph != 0 && "Result graph not allocated!");
91   DSGraph::ScalarMapTy &ValMap = ResultGraph->getScalarMap();
92
93   // Handle the return value of the function...
94   if (Call.getRetVal().getNode() && RetVal.getNode())
95     RetVal.mergeWith(Call.getRetVal());
96
97   // Loop over all pointer arguments, resolving them to their provided pointers
98   unsigned PtrArgIdx = 0;
99   for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
100        AI != AE && PtrArgIdx < Call.getNumPtrArgs(); ++AI) {
101     DSGraph::ScalarMapTy::iterator I = ValMap.find(AI);
102     if (I != ValMap.end())    // If its a pointer argument...
103       I->second.mergeWith(Call.getPtrArg(PtrArgIdx++));
104   }
105 }
106
107
108 /// run - Build up the result graph, representing the pointer graph for the
109 /// program.
110 ///
111 bool Steens::runOnModule(Module &M) {
112   InitializeAliasAnalysis(this);
113   assert(ResultGraph == 0 && "Result graph already allocated!");
114   LocalDataStructures &LDS = getAnalysis<LocalDataStructures>();
115
116   // Create a new, empty, graph...
117   ResultGraph = new DSGraph(GlobalECs, getTargetData());
118   GlobalsGraph = new DSGraph(GlobalECs, getTargetData());
119   ResultGraph->setGlobalsGraph(GlobalsGraph);
120   ResultGraph->setPrintAuxCalls();
121
122   // RetValMap - Keep track of the return values for all functions that return
123   // valid pointers.
124   //
125   DSGraph::ReturnNodesTy RetValMap;
126
127   // Loop over the rest of the module, merging graphs for non-external functions
128   // into this graph.
129   //
130   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
131     if (!I->isExternal()) {
132       DSGraph::NodeMapTy NodeMap;
133       ResultGraph->cloneInto(LDS.getDSGraph(*I), ResultGraph->getScalarMap(),
134                              RetValMap, NodeMap, 0);
135     }
136
137   ResultGraph->removeTriviallyDeadNodes();
138
139   // FIXME: Must recalculate and use the Incomplete markers!!
140
141   // Now that we have all of the graphs inlined, we can go about eliminating
142   // call nodes...
143   //
144   std::list<DSCallSite> &Calls = ResultGraph->getAuxFunctionCalls();
145   assert(Calls.empty() && "Aux call list is already in use??");
146
147   // Start with a copy of the original call sites.
148   Calls = ResultGraph->getFunctionCalls();
149
150   for (std::list<DSCallSite>::iterator CI = Calls.begin(), E = Calls.end();
151        CI != E;) {
152     DSCallSite &CurCall = *CI++;
153     
154     // Loop over the called functions, eliminating as many as possible...
155     std::vector<Function*> CallTargets;
156     if (CurCall.isDirectCall())
157       CallTargets.push_back(CurCall.getCalleeFunc());
158     else 
159       CurCall.getCalleeNode()->addFullFunctionList(CallTargets);
160
161     for (unsigned c = 0; c != CallTargets.size(); ) {
162       // If we can eliminate this function call, do so!
163       Function *F = CallTargets[c];
164       if (!F->isExternal()) {
165         ResolveFunctionCall(F, CurCall, RetValMap[F]);
166         CallTargets[c] = CallTargets.back();
167         CallTargets.pop_back();
168       } else
169         ++c;  // Cannot eliminate this call, skip over it...
170     }
171
172     if (CallTargets.empty()) {        // Eliminated all calls?
173       std::list<DSCallSite>::iterator I = CI;
174       Calls.erase(--I);               // Remove entry
175     }
176   }
177
178   RetValMap.clear();
179
180   // Update the "incomplete" markers on the nodes, ignoring unknownness due to
181   // incoming arguments...
182   ResultGraph->maskIncompleteMarkers();
183   ResultGraph->markIncompleteNodes(DSGraph::IgnoreFormalArgs);
184
185   // Remove any nodes that are dead after all of the merging we have done...
186   // FIXME: We should be able to disable the globals graph for steens!
187   ResultGraph->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
188
189   DEBUG(print(std::cerr, &M));
190   return false;
191 }
192
193 // alias - This is the only method here that does anything interesting...
194 AliasAnalysis::AliasResult Steens::alias(const Value *V1, unsigned V1Size,
195                                          const Value *V2, unsigned V2Size) {
196   // FIXME: HANDLE Size argument!
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   if (I != GSM.end() && I->second.getNode()) {
203     DSNodeHandle &V1H = I->second;
204     DSGraph::ScalarMapTy::iterator J=GSM.find(const_cast<Value*>(V2));
205     if (J != GSM.end() && J->second.getNode()) {
206       DSNodeHandle &V2H = J->second;
207       // If the two pointers point to different data structure graph nodes, they
208       // cannot alias!
209       if (V1H.getNode() != V2H.getNode())    // FIXME: Handle incompleteness!
210         return NoAlias;
211
212       // FIXME: If the two pointers point to the same node, and the offsets are
213       // different, and the LinkIndex vector doesn't alias the section, then the
214       // two pointers do not alias.  We need access size information for the two
215       // accesses though!
216       //
217     }
218   }
219
220   // If we cannot determine alias properties based on our graph, fall back on
221   // some other AA implementation.
222   //
223   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
224 }