1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
3 // Compute the local version of the data structure graph for a function. The
4 // external interface to this file is the DSGraph constructor.
6 //===----------------------------------------------------------------------===//
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"
22 // FIXME: This should eventually be a FunctionPass that is automatically
23 // aggregated into a Pass.
25 #include "llvm/Module.h"
30 static RegisterAnalysis<LocalDataStructures>
31 X("datastructure", "Local Data Structure Analysis");
34 // FIXME: Do something smarter with target data!
35 TargetData TD("temp-td");
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))
41 else if (Ty->isPrimitiveType() && Ty->isInteger())
42 return Ty->getPrimitiveSize() >= PointerSize;
50 //===--------------------------------------------------------------------===//
52 //===--------------------------------------------------------------------===//
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.
57 class GraphBuilder : InstVisitor<GraphBuilder> {
59 vector<DSNode*> &Nodes;
60 DSNodeHandle &RetNode; // Node that gets returned...
61 map<Value*, DSNodeHandle> &ScalarMap;
62 vector<DSCallSite> &FunctionCalls;
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) {
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()))
76 visit(G.getFunction()); // Single pass over the function
78 // Not inlining, only eliminate trivially dead nodes.
79 G.removeTriviallyDeadNodes();
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);
89 void visitPHINode(PHINode &PN);
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) {}
102 // Helper functions used to implement the visitation functions...
104 /// createNode - Create a new DSNode, ensuring that it is properly added to
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
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.
117 void setDestTo(Value &V, const DSNodeHandle &NH);
119 /// getValueDest - Return the DSNode that the actual value points to.
121 DSNodeHandle getValueDest(Value &V);
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.
127 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
131 //===----------------------------------------------------------------------===//
132 // DSGraph constructor - Simply use the GraphBuilder to construct the local
134 DSGraph::DSGraph(Function &F, DSGraph *GG) : Func(&F), GlobalsGraph(GG) {
135 // Use the graph builder to construct the local version of the graph
136 GraphBuilder B(*this, Nodes, RetNode, ScalarMap, FunctionCalls);
137 markIncompleteNodes();
141 //===----------------------------------------------------------------------===//
142 // Helper method implementations...
146 /// getValueDest - Return the DSNode that the actual value points to.
148 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
150 if (V == Constant::getNullValue(V->getType()))
151 return 0; // Null doesn't point to anything, don't add to ScalarMap!
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
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);
174 assert(0 && "Unknown constant type!");
177 DSNodeHandle &NH = ScalarMap[V];
179 return NH; // Already have a node? Just return it...
181 // Otherwise we need to create a new node to point to...
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());
188 // Otherwise just create a shadow node
189 N = createNode(DSNode::ShadowNode);
192 NH.setNode(N); // Remember that we are pointing to it...
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.
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);
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.
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
228 //===----------------------------------------------------------------------===//
229 // Specific instruction type handler implementations...
232 /// Alloca & Malloc instruction implementation - Simply create a new memory
233 /// object, pointing the scalar to it.
235 void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
236 setDestTo(AI, createNode(NodeType));
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.
242 void GraphBuilder::visitPHINode(PHINode &PN) {
243 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
245 DSNodeHandle &PNDest = ScalarMap[&PN];
246 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
247 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
250 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
251 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
252 if (Value.getNode() == 0) return;
255 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
256 const Type *CurTy = PTy->getElementType();
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
265 // Handle the pointer index specially...
266 if (GEP.getNumOperands() > 1 &&
267 GEP.getOperand(1) != ConstantSInt::getNullValue(Type::LongTy)) {
269 // If we already know this is an array being accessed, don't do anything...
270 if (!TopTypeRec.isArray) {
271 TopTypeRec.isArray = true;
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
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
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...
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();
298 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
299 Offset += CS->getValue()*TD.getTypeSize(CurTy);
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";
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();
312 // Loop over all of the elements of the array, merging them into the
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);
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);
328 // Add in the offset calculated...
329 Value.setOffset(Value.getOffset()+Offset);
331 // Value is now the pointer we want to GEP to be...
332 setDestTo(GEP, Value);
335 void GraphBuilder::visitLoadInst(LoadInst &LI) {
336 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
337 if (Ptr.getNode() == 0) return;
339 // Make that the node is read from...
340 Ptr.getNode()->NodeType |= DSNode::Read;
342 // Ensure a typerecord exists...
343 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset());
345 if (isPointerType(LI.getType()))
346 setDestTo(LI, getLink(Ptr));
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;
354 // Make that the node is written to...
355 Dest.getNode()->NodeType |= DSNode::Modified;
357 // Ensure a typerecord exists...
358 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
360 // Avoid adding edges from null, or processing non-"pointer" stores
361 if (isPointerType(StoredTy))
362 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
365 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
366 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
367 RetNode.mergeWith(getValueDest(*RI.getOperand(0)));
370 void GraphBuilder::visitCallInst(CallInst &CI) {
371 // Set up the return value...
373 if (isPointerType(CI.getType()))
374 RetVal = getValueDest(CI);
376 DSNodeHandle Callee = getValueDest(*CI.getOperand(0));
378 std::vector<DSNodeHandle> Args;
379 Args.reserve(CI.getNumOperands()-1);
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)));
386 // Add a new function call entry...
387 FunctionCalls.push_back(DSCallSite(CI, RetVal, Callee, Args));
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)));
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.
401 setDestTo(CI, createNode(DSNode::UnknownNode));
408 //===----------------------------------------------------------------------===//
409 // LocalDataStructures Implementation
410 //===----------------------------------------------------------------------===//
412 // releaseMemory - If the pass pipeline is done with this pass, we can release
413 // our memory... here...
415 void LocalDataStructures::releaseMemory() {
416 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
417 E = DSInfo.end(); I != E; ++I)
420 // Empty map so next time memory is released, data structures are not
427 bool LocalDataStructures::run(Module &M) {
428 GlobalsGraph = new DSGraph();
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)));