blob: 509825172edee38b108291b1160ac23f8c7b966c [file] [log] [blame]
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001//===- Local.cpp - Compute a local data structure graph for a function ----===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00002//
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
Chris Lattner055dc2c2002-07-18 15:54:42 +00008#include "llvm/Analysis/DataStructure.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +00009#include "llvm/iMemory.h"
10#include "llvm/iTerminators.h"
11#include "llvm/iPHINode.h"
12#include "llvm/iOther.h"
13#include "llvm/Constants.h"
14#include "llvm/DerivedTypes.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000015#include "llvm/Function.h"
16#include "llvm/GlobalVariable.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/Support/InstVisitor.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000018#include "llvm/Target/TargetData.h"
19#include "Support/Statistic.h"
20
21// FIXME: This should eventually be a FunctionPass that is automatically
22// aggregated into a Pass.
23//
24#include "llvm/Module.h"
25
Chris Lattnerc68c31b2002-07-10 22:38:08 +000026using std::map;
27using std::vector;
28
Chris Lattner97f51a32002-07-27 01:12:15 +000029static RegisterAnalysis<LocalDataStructures>
30X("datastructure", "Local Data Structure Analysis");
Chris Lattner97f51a32002-07-27 01:12:15 +000031
Chris Lattnerfccd06f2002-10-01 22:33:50 +000032using namespace DataStructureAnalysis;
33
34namespace DataStructureAnalysis {
35 // FIXME: Do something smarter with target data!
36 TargetData TD("temp-td");
37 unsigned PointerSize(TD.getPointerSize());
38
39 // isPointerType - Return true if this type is big enough to hold a pointer.
40 bool isPointerType(const Type *Ty) {
41 if (isa<PointerType>(Ty))
42 return true;
43 else if (Ty->isPrimitiveType() && Ty->isInteger())
44 return Ty->getPrimitiveSize() >= PointerSize;
45 return false;
46 }
47}
48
Chris Lattnerc68c31b2002-07-10 22:38:08 +000049
50namespace {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000051 //===--------------------------------------------------------------------===//
52 // GraphBuilder Class
53 //===--------------------------------------------------------------------===//
54 //
55 /// This class is the builder class that constructs the local data structure
56 /// graph by performing a single pass over the function in question.
57 ///
Chris Lattnerc68c31b2002-07-10 22:38:08 +000058 class GraphBuilder : InstVisitor<GraphBuilder> {
59 DSGraph &G;
60 vector<DSNode*> &Nodes;
61 DSNodeHandle &RetNode; // Node that gets returned...
62 map<Value*, DSNodeHandle> &ValueMap;
63 vector<vector<DSNodeHandle> > &FunctionCalls;
64
65 public:
66 GraphBuilder(DSGraph &g, vector<DSNode*> &nodes, DSNodeHandle &retNode,
67 map<Value*, DSNodeHandle> &vm,
68 vector<vector<DSNodeHandle> > &fc)
69 : G(g), Nodes(nodes), RetNode(retNode), ValueMap(vm), FunctionCalls(fc) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000070
71 // Create scalar nodes for all pointer arguments...
72 for (Function::aiterator I = G.getFunction().abegin(),
73 E = G.getFunction().aend(); I != E; ++I)
Chris Lattnerfccd06f2002-10-01 22:33:50 +000074 if (isPointerType(I->getType()))
75 getValueDest(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +000076
Chris Lattnerc68c31b2002-07-10 22:38:08 +000077 visit(G.getFunction()); // Single pass over the function
Chris Lattner2a2c4902002-07-18 18:19:09 +000078
79 // Not inlining, only eliminate trivially dead nodes.
80 G.removeTriviallyDeadNodes();
Chris Lattnerc68c31b2002-07-10 22:38:08 +000081 }
82
83 private:
84 // Visitor functions, used to handle each instruction type we encounter...
85 friend class InstVisitor<GraphBuilder>;
86 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, DSNode::NewNode); }
87 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, DSNode::AllocaNode);}
88 void handleAlloc(AllocationInst &AI, DSNode::NodeTy NT);
89
90 void visitPHINode(PHINode &PN);
91
92 void visitGetElementPtrInst(GetElementPtrInst &GEP);
93 void visitReturnInst(ReturnInst &RI);
94 void visitLoadInst(LoadInst &LI);
95 void visitStoreInst(StoreInst &SI);
96 void visitCallInst(CallInst &CI);
97 void visitSetCondInst(SetCondInst &SCI) {} // SetEQ & friends are ignored
98 void visitFreeInst(FreeInst &FI) {} // Ignore free instructions
Chris Lattnerfccd06f2002-10-01 22:33:50 +000099 void visitCastInst(CastInst &CI);
100 void visitInstruction(Instruction &I) {}
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000101
102 private:
103 // Helper functions used to implement the visitation functions...
104
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000105 /// createNode - Create a new DSNode, ensuring that it is properly added to
106 /// the graph.
107 ///
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000108 DSNode *createNode(DSNode::NodeTy NodeType, const Type *Ty);
109
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000110 /// getValueNode - Return a DSNode that corresponds the the specified LLVM
111 /// value. This either returns the already existing node, or creates a new
112 /// one and adds it to the graph, if none exists.
113 ///
114 DSNodeHandle getValueNode(Value &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000115
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000116 /// getValueDest - Return the DSNode that the actual value points to. This
117 /// is basically the same thing as: getLink(getValueNode(V), 0)
118 ///
119 DSNodeHandle &getValueDest(Value &V);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000120
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000121 /// getGlobalNode - Just like getValueNode, except the global node itself is
122 /// returned, not a scalar node pointing to a global.
123 ///
124 DSNodeHandle &getGlobalNode(GlobalValue &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000125
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000126 /// getLink - This method is used to return the specified link in the
127 /// specified node if one exists. If a link does not already exist (it's
128 /// null), then we create a new node, link it, then return it. We must
129 /// specify the type of the Node field we are accessing so that we know what
130 /// type should be linked to if we need to create a new node.
131 ///
132 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link,
133 const Type *FieldTy);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000134 };
135}
136
137//===----------------------------------------------------------------------===//
138// DSGraph constructor - Simply use the GraphBuilder to construct the local
139// graph.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000140DSGraph::DSGraph(Function &F) : Func(&F) {
141 // Use the graph builder to construct the local version of the graph
142 GraphBuilder B(*this, Nodes, RetNode, ValueMap, FunctionCalls);
143 markIncompleteNodes();
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000144}
145
146
147//===----------------------------------------------------------------------===//
148// Helper method implementations...
149//
150
151
152// createNode - Create a new DSNode, ensuring that it is properly added to the
153// graph.
154//
155DSNode *GraphBuilder::createNode(DSNode::NodeTy NodeType, const Type *Ty) {
156 DSNode *N = new DSNode(NodeType, Ty);
157 Nodes.push_back(N);
158 return N;
159}
160
161
Chris Lattner0d9bab82002-07-18 00:12:30 +0000162// getGlobalNode - Just like getValueNode, except the global node itself is
163// returned, not a scalar node pointing to a global.
164//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000165DSNodeHandle &GraphBuilder::getGlobalNode(GlobalValue &V) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000166 DSNodeHandle &NH = ValueMap[&V];
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000167 if (NH.getNode()) return NH; // Already have a node? Just return it...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000168
169 // Create a new global node for this global variable...
170 DSNode *G = createNode(DSNode::GlobalNode, V.getType()->getElementType());
171 G->addGlobal(&V);
172
173 // If this node has outgoing edges, make sure to recycle the same node for
174 // each use. For functions and other global variables, this is unneccesary,
175 // so avoid excessive merging by cloning these nodes on demand.
176 //
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000177 NH.setNode(G);
178 return NH;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000179}
180
181
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000182// getValueNode - Return a DSNode that corresponds the the specified LLVM value.
183// This either returns the already existing node, or creates a new one and adds
184// it to the graph, if none exists.
185//
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000186DSNodeHandle GraphBuilder::getValueNode(Value &V) {
187 assert(isPointerType(V.getType()) && "Should only use pointer scalars!");
188 // Do not share the pointer value to globals... this would cause way too much
189 // false merging.
190 //
191 DSNodeHandle &NH = ValueMap[&V];
192 if (!isa<GlobalValue>(V) && NH.getNode())
193 return NH; // Already have a node? Just return it...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000194
195 // Otherwise we need to create a new scalar node...
Chris Lattnerc314ac42002-07-11 20:32:02 +0000196 DSNode *N = createNode(DSNode::ScalarNode, V.getType());
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000197
Chris Lattner0d9bab82002-07-18 00:12:30 +0000198 // If this is a global value, create the global pointed to.
Chris Lattnerc314ac42002-07-11 20:32:02 +0000199 if (GlobalValue *GV = dyn_cast<GlobalValue>(&V)) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000200 N->addEdgeTo(0, getGlobalNode(*GV));
201 return DSNodeHandle(N, 0);
Chris Lattnerc314ac42002-07-11 20:32:02 +0000202 } else {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000203 NH.setOffset(0);
204 NH.setNode(N);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000205 }
206
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000207 return NH;
208}
209
210/// getValueDest - Return the DSNode that the actual value points to. This
211/// is basically the same thing as: getLink(getValueNode(V), 0)
212///
213DSNodeHandle &GraphBuilder::getValueDest(Value &V) {
214 return getLink(getValueNode(V), 0, V.getType());
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000215}
216
Chris Lattner0d9bab82002-07-18 00:12:30 +0000217
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000218
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000219/// getLink - This method is used to return the specified link in the
220/// specified node if one exists. If a link does not already exist (it's
221/// null), then we create a new node, link it, then return it. We must
222/// specify the type of the Node field we are accessing so that we know what
223/// type should be linked to if we need to create a new node.
224///
225DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node,
226 unsigned LinkNo, const Type *FieldTy) {
227 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000228
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000229 DSNodeHandle *Link = Node.getLink(LinkNo);
230 if (Link) return *Link;
231
232 // If the link hasn't been created yet, make and return a new shadow node of
233 // the appropriate type for FieldTy...
234 //
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000235
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000236 // If we are indexing with a typed pointer, then the thing we are pointing
237 // to is of the pointed type. If we are pointing to it with an integer
238 // (because of cast to an integer), we represent it with a void type.
239 //
240 const Type *ReqTy;
241 if (const PointerType *Ptr = dyn_cast<PointerType>(FieldTy))
242 ReqTy = Ptr->getElementType();
243 else
244 ReqTy = Type::VoidTy;
245
246 DSNode *N = createNode(DSNode::ShadowNode, ReqTy);
247 Node.setLink(LinkNo, N);
248 return *Node.getLink(LinkNo);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000249}
250
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000251
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000252//===----------------------------------------------------------------------===//
253// Specific instruction type handler implementations...
254//
255
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000256/// Alloca & Malloc instruction implementation - Simply create a new memory
257/// object, pointing the scalar to it.
258///
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000259void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000260 DSNode *New = createNode(NodeType, AI.getAllocatedType());
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000261
262 // Make the scalar point to the new node...
263 getValueNode(AI).addEdgeTo(New);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000264}
265
266// PHINode - Make the scalar for the PHI node point to all of the things the
267// incoming values point to... which effectively causes them to be merged.
268//
269void GraphBuilder::visitPHINode(PHINode &PN) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000270 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000271
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000272 DSNodeHandle &ScalarDest = getValueDest(PN);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000273 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000274 if (!isa<ConstantPointerNull>(PN.getIncomingValue(i)))
275 ScalarDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000276}
277
278void GraphBuilder::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000279 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
280
281 unsigned Offset = 0;
282 const Type *CurTy = GEP.getOperand(0)->getType();
283
284 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
285 if (GEP.getOperand(i)->getType() == Type::LongTy) {
286 if (GEP.getOperand(i) != Constant::getNullValue(Type::LongTy)) {
287 std::cerr << "Array indexing not handled yet!\n";
288 }
289 CurTy = cast<SequentialType>(CurTy)->getElementType();
290 } else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
291 unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
292 const StructType *STy = cast<StructType>(CurTy);
293 Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
294 CurTy = STy->getContainedType(FieldNo);
295 }
296
297 // Add in the offset calculated...
298 Value.setOffset(Value.getOffset()+Offset);
299
300 // Value is now the pointer we want to GEP to be...
301 getValueNode(GEP).addEdgeTo(Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000302}
303
304void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000305 DSNodeHandle &Ptr = getValueDest(*LI.getOperand(0));
306 if (isPointerType(LI.getType()))
307 getValueNode(LI).addEdgeTo(getLink(Ptr, 0, LI.getType()));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000308}
309
310void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000311 DSNodeHandle &Dest = getValueDest(*SI.getOperand(1));
312
313 // Avoid adding edges from null, or processing non-"pointer" stores
314 if (isPointerType(SI.getOperand(0)->getType()) &&
315 !isa<ConstantPointerNull>(SI.getOperand(0))) {
316 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
317 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000318}
319
320void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000321 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()) &&
322 !isa<ConstantPointerNull>(RI.getOperand(0))) {
323 DSNodeHandle &Value = getValueDest(*RI.getOperand(0));
324 Value.mergeWith(RetNode);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000325 RetNode = Value;
326 }
327}
328
329void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000330 // Add a new function call entry...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000331 FunctionCalls.push_back(vector<DSNodeHandle>());
332 vector<DSNodeHandle> &Args = FunctionCalls.back();
333
Chris Lattnerc314ac42002-07-11 20:32:02 +0000334 // Set up the return value...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000335 if (isPointerType(CI.getType()))
336 Args.push_back(getLink(getValueNode(CI), 0, CI.getType()));
Chris Lattnerc314ac42002-07-11 20:32:02 +0000337 else
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000338 Args.push_back(DSNodeHandle());
Chris Lattnerc314ac42002-07-11 20:32:02 +0000339
Chris Lattner0d9bab82002-07-18 00:12:30 +0000340 unsigned Start = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000341 // Special case for a direct call, avoid creating spurious scalar node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000342 if (GlobalValue *GV = dyn_cast<GlobalValue>(CI.getOperand(0))) {
343 Args.push_back(getGlobalNode(*GV));
344 Start = 1;
345 }
346
Chris Lattnerc314ac42002-07-11 20:32:02 +0000347 // Pass the arguments in...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000348 for (unsigned i = Start, e = CI.getNumOperands(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000349 if (isPointerType(CI.getOperand(i)->getType()))
350 Args.push_back(getLink(getValueNode(*CI.getOperand(i)), 0,
351 CI.getOperand(i)->getType()));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000352}
Chris Lattner055dc2c2002-07-18 15:54:42 +0000353
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000354/// Handle casts...
355void GraphBuilder::visitCastInst(CastInst &CI) {
356 if (isPointerType(CI.getType()) && isPointerType(CI.getOperand(0)->getType()))
357 getValueNode(CI).addEdgeTo(getLink(getValueNode(*CI.getOperand(0)), 0,
358 CI.getOperand(0)->getType()));
359}
Chris Lattner055dc2c2002-07-18 15:54:42 +0000360
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000361
362
363
364//===----------------------------------------------------------------------===//
365// LocalDataStructures Implementation
366//===----------------------------------------------------------------------===//
367
368// releaseMemory - If the pass pipeline is done with this pass, we can release
369// our memory... here...
370//
371void LocalDataStructures::releaseMemory() {
372 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
373 E = DSInfo.end(); I != E; ++I)
374 delete I->second;
375
376 // Empty map so next time memory is released, data structures are not
377 // re-deleted.
378 DSInfo.clear();
379}
380
381bool LocalDataStructures::run(Module &M) {
382 // Calculate all of the graphs...
383 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
384 if (!I->isExternal())
385 DSInfo.insert(std::make_pair(I, new DSGraph(*I)));
386 return false;
Chris Lattner055dc2c2002-07-18 15:54:42 +0000387}
388