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