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 DSNodeHandle &NH = ScalarMap[V];
155 return NH; // Already have a node? Just return it...
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];
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);
174 assert(0 && "Unknown constant type!");
177 // Otherwise we need to create a new node to point to...
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());
184 // Otherwise just create a shadow node
185 N = createNode(DSNode::ShadowNode);
188 NH.setNode(N); // Remember that we are pointing to it...
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.
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);
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.
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
224 //===----------------------------------------------------------------------===//
225 // Specific instruction type handler implementations...
228 /// Alloca & Malloc instruction implementation - Simply create a new memory
229 /// object, pointing the scalar to it.
231 void GraphBuilder::handleAlloc(AllocationInst &AI, DSNode::NodeTy NodeType) {
232 setDestTo(AI, createNode(NodeType));
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.
238 void GraphBuilder::visitPHINode(PHINode &PN) {
239 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
241 DSNodeHandle &PNDest = ScalarMap[&PN];
242 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
243 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
246 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
247 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
248 if (Value.getNode() == 0) return;
251 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
252 const Type *CurTy = PTy->getElementType();
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
261 // Handle the pointer index specially...
262 if (GEP.getNumOperands() > 1 &&
263 GEP.getOperand(1) != ConstantSInt::getNullValue(Type::LongTy)) {
265 // If we already know this is an array being accessed, don't do anything...
266 if (!TopTypeRec.isArray) {
267 TopTypeRec.isArray = true;
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
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
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...
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();
294 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
295 Offset += CS->getValue()*TD.getTypeSize(CurTy);
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";
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();
308 // Loop over all of the elements of the array, merging them into the
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);
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);
324 // Add in the offset calculated...
325 Value.setOffset(Value.getOffset()+Offset);
327 // Value is now the pointer we want to GEP to be...
328 setDestTo(GEP, Value);
331 void GraphBuilder::visitLoadInst(LoadInst &LI) {
332 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
333 if (Ptr.getNode() == 0) return;
335 // Make that the node is read from...
336 Ptr.getNode()->NodeType |= DSNode::Read;
338 // Ensure a typerecord exists...
339 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset());
341 if (isPointerType(LI.getType()))
342 setDestTo(LI, getLink(Ptr));
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;
350 // Make that the node is written to...
351 Dest.getNode()->NodeType |= DSNode::Modified;
353 // Ensure a typerecord exists...
354 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
356 // Avoid adding edges from null, or processing non-"pointer" stores
357 if (isPointerType(StoredTy))
358 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
361 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
362 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
363 RetNode.mergeWith(getValueDest(*RI.getOperand(0)));
366 void GraphBuilder::visitCallInst(CallInst &CI) {
367 // Set up the return value...
369 if (isPointerType(CI.getType()))
370 RetVal = getValueDest(CI);
372 DSNodeHandle Callee = getValueDest(*CI.getOperand(0));
374 std::vector<DSNodeHandle> Args;
375 Args.reserve(CI.getNumOperands()-1);
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)));
382 // Add a new function call entry...
383 FunctionCalls.push_back(DSCallSite(CI, RetVal, Callee, Args));
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)));
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.
397 setDestTo(CI, createNode(DSNode::UnknownNode));
404 //===----------------------------------------------------------------------===//
405 // LocalDataStructures Implementation
406 //===----------------------------------------------------------------------===//
408 // releaseMemory - If the pass pipeline is done with this pass, we can release
409 // our memory... here...
411 void LocalDataStructures::releaseMemory() {
412 for (std::map<const Function*, DSGraph*>::iterator I = DSInfo.begin(),
413 E = DSInfo.end(); I != E; ++I)
416 // Empty map so next time memory is released, data structures are not
423 bool LocalDataStructures::run(Module &M) {
424 GlobalsGraph = new DSGraph();
426 // Calculate all of the graphs...
427 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
428 if (!I->isExternal())
429 DSInfo.insert(std::make_pair(I, new DSGraph(*I, GlobalsGraph)));