blob: d1c24a699e2a61f1571f6ae1bde54cd26f194ff7 [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) {
Chris Lattnere03f32b2002-10-02 06:24:36 +0000286 // Get the type indexing into...
287 const SequentialType *STy = cast<SequentialType>(CurTy);
288 CurTy = STy->getElementType();
289 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
290 if (isa<PointerType>(STy))
291 std::cerr << "Pointer indexing not handled yet!\n";
292 else
293 Offset += CS->getValue()*TD.getTypeSize(CurTy);
294 } else {
295 // Variable index into a node. We must merge all of the elements of the
296 // sequential type here.
297 if (isa<PointerType>(STy))
298 std::cerr << "Pointer indexing not handled yet!\n";
299 else {
300 const ArrayType *ATy = cast<ArrayType>(STy);
301 unsigned ElSize = TD.getTypeSize(CurTy);
302 DSNode *N = Value.getNode();
303 assert(N && "Value must have a node!");
304 unsigned RawOffset = Offset+Value.getOffset();
305
306 // Loop over all of the elements of the array, merging them into the
307 // zero'th element.
308 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
309 // Merge all of the byte components of this array element
310 for (unsigned j = 0; j != ElSize; ++j)
311 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
312 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000313 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000314 } else if (GEP.getOperand(i)->getType() == Type::UByteTy) {
315 unsigned FieldNo = cast<ConstantUInt>(GEP.getOperand(i))->getValue();
316 const StructType *STy = cast<StructType>(CurTy);
317 Offset += TD.getStructLayout(STy)->MemberOffsets[FieldNo];
318 CurTy = STy->getContainedType(FieldNo);
319 }
320
321 // Add in the offset calculated...
322 Value.setOffset(Value.getOffset()+Offset);
323
324 // Value is now the pointer we want to GEP to be...
325 getValueNode(GEP).addEdgeTo(Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000326}
327
328void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000329 DSNodeHandle &Ptr = getValueDest(*LI.getOperand(0));
330 if (isPointerType(LI.getType()))
331 getValueNode(LI).addEdgeTo(getLink(Ptr, 0, LI.getType()));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000332}
333
334void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000335 DSNodeHandle &Dest = getValueDest(*SI.getOperand(1));
336
337 // Avoid adding edges from null, or processing non-"pointer" stores
338 if (isPointerType(SI.getOperand(0)->getType()) &&
339 !isa<ConstantPointerNull>(SI.getOperand(0))) {
340 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
341 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000342}
343
344void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000345 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()) &&
346 !isa<ConstantPointerNull>(RI.getOperand(0))) {
347 DSNodeHandle &Value = getValueDest(*RI.getOperand(0));
348 Value.mergeWith(RetNode);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000349 RetNode = Value;
350 }
351}
352
353void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner0d9bab82002-07-18 00:12:30 +0000354 // Add a new function call entry...
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000355 FunctionCalls.push_back(vector<DSNodeHandle>());
356 vector<DSNodeHandle> &Args = FunctionCalls.back();
357
Chris Lattnerc314ac42002-07-11 20:32:02 +0000358 // Set up the return value...
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000359 if (isPointerType(CI.getType()))
360 Args.push_back(getLink(getValueNode(CI), 0, CI.getType()));
Chris Lattnerc314ac42002-07-11 20:32:02 +0000361 else
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000362 Args.push_back(DSNodeHandle());
Chris Lattnerc314ac42002-07-11 20:32:02 +0000363
Chris Lattner0d9bab82002-07-18 00:12:30 +0000364 unsigned Start = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000365 // Special case for a direct call, avoid creating spurious scalar node...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000366 if (GlobalValue *GV = dyn_cast<GlobalValue>(CI.getOperand(0))) {
367 Args.push_back(getGlobalNode(*GV));
368 Start = 1;
369 }
370
Chris Lattnerc314ac42002-07-11 20:32:02 +0000371 // Pass the arguments in...
Chris Lattner0d9bab82002-07-18 00:12:30 +0000372 for (unsigned i = Start, e = CI.getNumOperands(); i != e; ++i)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000373 if (isPointerType(CI.getOperand(i)->getType()))
374 Args.push_back(getLink(getValueNode(*CI.getOperand(i)), 0,
375 CI.getOperand(i)->getType()));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000376}
Chris Lattner055dc2c2002-07-18 15:54:42 +0000377
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000378/// Handle casts...
379void GraphBuilder::visitCastInst(CastInst &CI) {
380 if (isPointerType(CI.getType()) && isPointerType(CI.getOperand(0)->getType()))
381 getValueNode(CI).addEdgeTo(getLink(getValueNode(*CI.getOperand(0)), 0,
382 CI.getOperand(0)->getType()));
383}
Chris Lattner055dc2c2002-07-18 15:54:42 +0000384
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000385
386
387
388//===----------------------------------------------------------------------===//
389// LocalDataStructures Implementation
390//===----------------------------------------------------------------------===//
391
392// releaseMemory - If the pass pipeline is done with this pass, we can release
393// our memory... here...
394//
395void LocalDataStructures::releaseMemory() {
396 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
397 E = DSInfo.end(); I != E; ++I)
398 delete I->second;
399
400 // Empty map so next time memory is released, data structures are not
401 // re-deleted.
402 DSInfo.clear();
403}
404
405bool LocalDataStructures::run(Module &M) {
406 // Calculate all of the graphs...
407 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
408 if (!I->isExternal())
409 DSInfo.insert(std::make_pair(I, new DSGraph(*I)));
410 return false;
Chris Lattner055dc2c2002-07-18 15:54:42 +0000411}
412