Clean up DSGraph::removeDeadNodes interface
[oota-llvm.git] / lib / Analysis / DataStructure / Local.cpp
1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
2 //
3 // Compute the local version of the data structure graph for a function.  The
4 // external interface to this file is the DSGraph constructor.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Analysis/DataStructure.h"
9 #include "llvm/Analysis/DSGraph.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Function.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "llvm/Target/TargetData.h"
20 #include "Support/Statistic.h"
21
22 // FIXME: This should eventually be a FunctionPass that is automatically
23 // aggregated into a Pass.
24 //
25 #include "llvm/Module.h"
26
27 using std::map;
28 using std::vector;
29
30 static RegisterAnalysis<LocalDataStructures>
31 X("datastructure", "Local Data Structure Analysis");
32
33 namespace DS {
34   // FIXME: Do something smarter with target data!
35   TargetData TD("temp-td");
36
37   // isPointerType - Return true if this type is big enough to hold a pointer.
38   bool isPointerType(const Type *Ty) {
39     if (isa<PointerType>(Ty))
40       return true;
41     else if (Ty->isPrimitiveType() && Ty->isInteger())
42       return Ty->getPrimitiveSize() >= PointerSize;
43     return false;
44   }
45 }
46 using namespace DS;
47
48
49 namespace {
50   //===--------------------------------------------------------------------===//
51   //  GraphBuilder Class
52   //===--------------------------------------------------------------------===//
53   //
54   /// This class is the builder class that constructs the local data structure
55   /// graph by performing a single pass over the function in question.
56   ///
57   class GraphBuilder : InstVisitor<GraphBuilder> {
58     DSGraph &G;
59     vector<DSNode*> &Nodes;
60     DSNodeHandle &RetNode;               // Node that gets returned...
61     map<Value*, DSNodeHandle> &ScalarMap;
62     vector<DSCallSite> &FunctionCalls;
63
64   public:
65     GraphBuilder(DSGraph &g, vector<DSNode*> &nodes, DSNodeHandle &retNode,
66                  map<Value*, DSNodeHandle> &SM,
67                  vector<DSCallSite> &fc)
68       : G(g), Nodes(nodes), RetNode(retNode), ScalarMap(SM), FunctionCalls(fc) {
69
70       // Create scalar nodes for all pointer arguments...
71       for (Function::aiterator I = G.getFunction().abegin(),
72              E = G.getFunction().aend(); I != E; ++I)
73         if (isPointerType(I->getType()))
74           getValueDest(*I);
75
76       visit(G.getFunction());  // Single pass over the function
77     }
78
79   private:
80     // Visitor functions, used to handle each instruction type we encounter...
81     friend class InstVisitor<GraphBuilder>;
82     void visitMallocInst(MallocInst &MI) { handleAlloc(MI, DSNode::HeapNode); }
83     void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, DSNode::AllocaNode);}
84     void handleAlloc(AllocationInst &AI, DSNode::NodeTy NT);
85
86     void visitPHINode(PHINode &PN);
87
88     void visitGetElementPtrInst(User &GEP);
89     void visitReturnInst(ReturnInst &RI);
90     void visitLoadInst(LoadInst &LI);
91     void visitStoreInst(StoreInst &SI);
92     void visitCallInst(CallInst &CI);
93     void visitSetCondInst(SetCondInst &SCI) {}  // SetEQ & friends are ignored
94     void visitFreeInst(FreeInst &FI) {}         // Ignore free instructions
95     void visitCastInst(CastInst &CI);
96     void visitInstruction(Instruction &I) {}
97
98   private:
99     // Helper functions used to implement the visitation functions...
100
101     /// createNode - Create a new DSNode, ensuring that it is properly added to
102     /// the graph.
103     ///
104     DSNode *createNode(DSNode::NodeTy NodeType, const Type *Ty = 0) {
105       DSNode *N = new DSNode(NodeType, Ty);   // Create the node
106       Nodes.push_back(N);                     // Add node to nodes list
107       return N;
108     }
109
110     /// setDestTo - Set the ScalarMap entry for the specified value to point to
111     /// the specified destination.  If the Value already points to a node, make
112     /// sure to merge the two destinations together.
113     ///
114     void setDestTo(Value &V, const DSNodeHandle &NH);
115
116     /// getValueDest - Return the DSNode that the actual value points to. 
117     ///
118     DSNodeHandle getValueDest(Value &V);
119
120     /// getLink - This method is used to return the specified link in the
121     /// specified node if one exists.  If a link does not already exist (it's
122     /// null), then we create a new node, link it, then return it.
123     ///
124     DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
125   };
126 }
127
128 //===----------------------------------------------------------------------===//
129 // DSGraph constructor - Simply use the GraphBuilder to construct the local
130 // graph.
131 DSGraph::DSGraph(Function &F, DSGraph *GG) : Func(&F), GlobalsGraph(GG) {
132   // Use the graph builder to construct the local version of the graph
133   GraphBuilder B(*this, Nodes, RetNode, ScalarMap, FunctionCalls);
134   markIncompleteNodes();
135
136   // Remove any nodes made dead due to merging...
137   removeDeadNodes(true);
138 }
139
140
141 //===----------------------------------------------------------------------===//
142 // Helper method implementations...
143 //
144
145
146 /// getValueDest - Return the DSNode that the actual value points to.
147 ///
148 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
149   Value *V = &Val;
150   if (V == Constant::getNullValue(V->getType()))
151     return 0;  // Null doesn't point to anything, don't add to ScalarMap!
152
153   if (Constant *C = dyn_cast<Constant>(V))
154     if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
155       return getValueDest(*CPR->getValue());
156     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
157       if (CE->getOpcode() == Instruction::Cast)
158         return getValueDest(*CE->getOperand(0));
159       if (CE->getOpcode() == Instruction::GetElementPtr) {
160         visitGetElementPtrInst(*CE);
161         std::map<Value*, DSNodeHandle>::iterator I = ScalarMap.find(CE);
162         assert(I != ScalarMap.end() && "GEP didn't get processed right?");
163         DSNodeHandle NH = I->second;
164         ScalarMap.erase(I);           // Remove constant from scalarmap
165         return NH;
166       }
167
168       // This returns a conservative unknown node for any unhandled ConstExpr
169       return createNode(DSNode::UnknownNode);
170     } else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(C)) {
171       // Random constants are unknown mem
172       return createNode(DSNode::UnknownNode);
173     } else {
174       assert(0 && "Unknown constant type!");
175     }
176
177   DSNodeHandle &NH = ScalarMap[V];
178   if (NH.getNode())
179     return NH;     // Already have a node?  Just return it...
180
181   // Otherwise we need to create a new node to point to...
182   DSNode *N;
183   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
184     // Create a new global node for this global variable...
185     N = createNode(DSNode::GlobalNode, GV->getType()->getElementType());
186     N->addGlobal(GV);
187   } else {
188     // Otherwise just create a shadow node
189     N = createNode(DSNode::ShadowNode);
190   }
191
192   NH.setNode(N);      // Remember that we are pointing to it...
193   NH.setOffset(0);
194   return NH;
195 }
196
197
198 /// getLink - This method is used to return the specified link in the
199 /// specified node if one exists.  If a link does not already exist (it's
200 /// null), then we create a new node, link it, then return it.  We must
201 /// specify the type of the Node field we are accessing so that we know what
202 /// type should be linked to if we need to create a new node.
203 ///
204 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
205   DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
206   DSNodeHandle &Link = Node.getLink(LinkNo);
207   if (!Link.getNode()) {
208     // If the link hasn't been created yet, make and return a new shadow node
209     Link = createNode(DSNode::ShadowNode);
210   }
211   return Link;
212 }
213
214
215 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
216 /// specified destination.  If the Value already points to a node, make sure to
217 /// merge the two destinations together.
218 ///
219 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
220   DSNodeHandle &AINH = ScalarMap[&V];
221   if (AINH.getNode() == 0)   // Not pointing to anything yet?
222     AINH = NH;               // Just point directly to NH
223   else
224     AINH.mergeWith(NH);
225 }
226
227
228 //===----------------------------------------------------------------------===//
229 // Specific instruction type handler implementations...
230 //
231
232 /// Alloca & Malloc instruction implementation - Simply create a new memory
233 /// object, pointing the scalar to it.
234 ///
235 void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
236   setDestTo(AI, createNode(NodeType));
237 }
238
239 // PHINode - Make the scalar for the PHI node point to all of the things the
240 // incoming values point to... which effectively causes them to be merged.
241 //
242 void GraphBuilder::visitPHINode(PHINode &PN) {
243   if (!isPointerType(PN.getType())) return; // Only pointer PHIs
244
245   DSNodeHandle &PNDest = ScalarMap[&PN];
246   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
247     PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
248 }
249
250 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
251   DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
252   if (Value.getNode() == 0) return;
253
254   unsigned Offset = 0;
255   const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
256   const Type *CurTy = PTy->getElementType();
257
258   if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
259     // If the node had to be folded... exit quickly
260     setDestTo(GEP, Value);  // GEP result points to folded node
261     return;
262   }
263
264 #if 0
265   // Handle the pointer index specially...
266   if (GEP.getNumOperands() > 1 &&
267       GEP.getOperand(1) != ConstantSInt::getNullValue(Type::LongTy)) {
268
269     // If we already know this is an array being accessed, don't do anything...
270     if (!TopTypeRec.isArray) {
271       TopTypeRec.isArray = true;
272
273       // If we are treating some inner field pointer as an array, fold the node
274       // up because we cannot handle it right.  This can come because of
275       // something like this:  &((&Pt->X)[1]) == &Pt->Y
276       //
277       if (Value.getOffset()) {
278         // Value is now the pointer we want to GEP to be...
279         Value.getNode()->foldNodeCompletely();
280         setDestTo(GEP, Value);  // GEP result points to folded node
281         return;
282       } else {
283         // This is a pointer to the first byte of the node.  Make sure that we
284         // are pointing to the outter most type in the node.
285         // FIXME: We need to check one more case here...
286       }
287     }
288   }
289 #endif
290
291   // All of these subscripts are indexing INTO the elements we have...
292   for (unsigned i = 2, e = GEP.getNumOperands(); i < e; ++i)
293     if (GEP.getOperand(i)->getType() == Type::LongTy) {
294       // Get the type indexing into...
295       const SequentialType *STy = cast<SequentialType>(CurTy);
296       CurTy = STy->getElementType();
297 #if 0
298       if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
299         Offset += CS->getValue()*TD.getTypeSize(CurTy);
300       } else {
301         // Variable index into a node.  We must merge all of the elements of the
302         // sequential type here.
303         if (isa<PointerType>(STy))
304           std::cerr << "Pointer indexing not handled yet!\n";
305         else {
306           const ArrayType *ATy = cast<ArrayType>(STy);
307           unsigned ElSize = TD.getTypeSize(CurTy);
308           DSNode *N = Value.getNode();
309           assert(N && "Value must have a node!");
310           unsigned RawOffset = Offset+Value.getOffset();
311
312           // Loop over all of the elements of the array, merging them into the
313           // zero'th element.
314           for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
315             // Merge all of the byte components of this array element
316             for (unsigned j = 0; j != ElSize; ++j)
317               N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
318         }
319       }
320 #endif
321     } else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
322       unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
323       const StructType *STy = cast<StructType>(CurTy);
324       Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
325       CurTy = STy->getContainedType(FieldNo);
326     }
327
328   // Add in the offset calculated...
329   Value.setOffset(Value.getOffset()+Offset);
330
331   // Value is now the pointer we want to GEP to be...
332   setDestTo(GEP, Value);
333 }
334
335 void GraphBuilder::visitLoadInst(LoadInst &LI) {
336   DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
337   if (Ptr.getNode() == 0) return;
338
339   // Make that the node is read from...
340   Ptr.getNode()->NodeType |= DSNode::Read;
341
342   // Ensure a typerecord exists...
343   Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset());
344
345   if (isPointerType(LI.getType()))
346     setDestTo(LI, getLink(Ptr));
347 }
348
349 void GraphBuilder::visitStoreInst(StoreInst &SI) {
350   const Type *StoredTy = SI.getOperand(0)->getType();
351   DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
352   if (Dest.getNode() == 0) return;
353
354   // Make that the node is written to...
355   Dest.getNode()->NodeType |= DSNode::Modified;
356
357   // Ensure a typerecord exists...
358   Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
359
360   // Avoid adding edges from null, or processing non-"pointer" stores
361   if (isPointerType(StoredTy))
362     Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
363 }
364
365 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
366   if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
367     RetNode.mergeWith(getValueDest(*RI.getOperand(0)));
368 }
369
370 void GraphBuilder::visitCallInst(CallInst &CI) {
371   // Set up the return value...
372   DSNodeHandle RetVal;
373   if (isPointerType(CI.getType()))
374     RetVal = getValueDest(CI);
375
376   DSNodeHandle Callee = getValueDest(*CI.getOperand(0));
377
378   std::vector<DSNodeHandle> Args;
379   Args.reserve(CI.getNumOperands()-1);
380
381   // Calculate the arguments vector...
382   for (unsigned i = 1, e = CI.getNumOperands(); i != e; ++i)
383     if (isPointerType(CI.getOperand(i)->getType()))
384       Args.push_back(getValueDest(*CI.getOperand(i)));
385
386   // Add a new function call entry...
387   FunctionCalls.push_back(DSCallSite(CI, RetVal, Callee, Args));
388 }
389
390 /// Handle casts...
391 void GraphBuilder::visitCastInst(CastInst &CI) {
392   if (isPointerType(CI.getType()))
393     if (isPointerType(CI.getOperand(0)->getType())) {
394       // Cast one pointer to the other, just act like a copy instruction
395       setDestTo(CI, getValueDest(*CI.getOperand(0)));
396     } else {
397       // Cast something (floating point, small integer) to a pointer.  We need
398       // to track the fact that the node points to SOMETHING, just something we
399       // don't know about.  Make an "Unknown" node.
400       //
401       setDestTo(CI, createNode(DSNode::UnknownNode));
402     }
403 }
404
405
406
407
408 //===----------------------------------------------------------------------===//
409 // LocalDataStructures Implementation
410 //===----------------------------------------------------------------------===//
411
412 // releaseMemory - If the pass pipeline is done with this pass, we can release
413 // our memory... here...
414 //
415 void LocalDataStructures::releaseMemory() {
416   for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
417          E = DSInfo.end(); I != E; ++I)
418     delete I->second;
419
420   // Empty map so next time memory is released, data structures are not
421   // re-deleted.
422   DSInfo.clear();
423   delete GlobalsGraph;
424   GlobalsGraph = 0;
425 }
426
427 bool LocalDataStructures::run(Module &M) {
428   GlobalsGraph = new DSGraph();
429
430   // Calculate all of the graphs...
431   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
432     if (!I->isExternal())
433       DSInfo.insert(std::make_pair(I, new DSGraph(*I, GlobalsGraph)));
434   return false;
435 }