1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Compute the local version of the data structure graph for a function. The
11 // external interface to this file is the DSGraph constructor.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Analysis/DataStructure/DataStructure.h"
16 #include "llvm/Analysis/DataStructure/DSGraph.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Timer.h"
28 // FIXME: This should eventually be a FunctionPass that is automatically
29 // aggregated into a Pass.
31 #include "llvm/Module.h"
35 static RegisterAnalysis<LocalDataStructures>
36 X("datastructure", "Local Data Structure Analysis");
39 TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
40 cl::desc("If this is set, track integers as potential pointers"));
44 // isPointerType - Return true if this type is big enough to hold a pointer.
45 bool isPointerType(const Type *Ty) {
46 if (isa<PointerType>(Ty))
48 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
49 return Ty->getPrimitiveSize() >= PointerSize;
58 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
59 cl::desc("Disable direct call optimization in "
60 "DSGraph construction"));
62 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
63 cl::desc("Disable field sensitivity in DSGraphs"));
65 //===--------------------------------------------------------------------===//
67 //===--------------------------------------------------------------------===//
69 /// This class is the builder class that constructs the local data structure
70 /// graph by performing a single pass over the function in question.
72 class GraphBuilder : InstVisitor<GraphBuilder> {
74 DSNodeHandle *RetNode; // Node that gets returned...
75 DSScalarMap &ScalarMap;
76 std::list<DSCallSite> *FunctionCalls;
79 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
80 std::list<DSCallSite> &fc)
81 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
84 // Create scalar nodes for all pointer arguments...
85 for (Function::aiterator I = f.abegin(), E = f.aend(); I != E; ++I)
86 if (isPointerType(I->getType()))
89 visit(f); // Single pass over the function
92 // GraphBuilder ctor for working on the globals graph
93 GraphBuilder(DSGraph &g)
94 : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
97 void mergeInGlobalInitializer(GlobalVariable *GV);
100 // Visitor functions, used to handle each instruction type we encounter...
101 friend class InstVisitor<GraphBuilder>;
102 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
103 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
104 void handleAlloc(AllocationInst &AI, bool isHeap);
106 void visitPHINode(PHINode &PN);
108 void visitGetElementPtrInst(User &GEP);
109 void visitReturnInst(ReturnInst &RI);
110 void visitLoadInst(LoadInst &LI);
111 void visitStoreInst(StoreInst &SI);
112 void visitCallInst(CallInst &CI);
113 void visitInvokeInst(InvokeInst &II);
114 void visitSetCondInst(SetCondInst &SCI) {} // SetEQ & friends are ignored
115 void visitFreeInst(FreeInst &FI);
116 void visitCastInst(CastInst &CI);
117 void visitInstruction(Instruction &I);
119 void visitCallSite(CallSite CS);
120 void visitVANextInst(VANextInst &I);
121 void visitVAArgInst(VAArgInst &I);
123 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
125 // Helper functions used to implement the visitation functions...
127 /// createNode - Create a new DSNode, ensuring that it is properly added to
130 DSNode *createNode(const Type *Ty = 0) {
131 DSNode *N = new DSNode(Ty, &G); // Create the node
132 if (DisableFieldSensitivity) {
133 // Create node handle referring to the old node so that it is
134 // immediately removed from the graph when the node handle is destroyed.
135 DSNodeHandle OldNNH = N;
136 N->foldNodeCompletely();
137 if (DSNode *FN = N->getForwardNode())
143 /// setDestTo - Set the ScalarMap entry for the specified value to point to
144 /// the specified destination. If the Value already points to a node, make
145 /// sure to merge the two destinations together.
147 void setDestTo(Value &V, const DSNodeHandle &NH);
149 /// getValueDest - Return the DSNode that the actual value points to.
151 DSNodeHandle getValueDest(Value &V);
153 /// getLink - This method is used to return the specified link in the
154 /// specified node if one exists. If a link does not already exist (it's
155 /// null), then we create a new node, link it, then return it.
157 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
163 //===----------------------------------------------------------------------===//
164 // DSGraph constructor - Simply use the GraphBuilder to construct the local
166 DSGraph::DSGraph(const TargetData &td, Function &F, DSGraph *GG)
167 : GlobalsGraph(GG), TD(td) {
168 PrintAuxCalls = false;
170 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
172 // Use the graph builder to construct the local version of the graph
173 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
175 Timer::addPeakMemoryMeasurement();
178 // Remove all integral constants from the scalarmap!
179 for (DSScalarMap::iterator I = ScalarMap.begin(); I != ScalarMap.end();)
180 if (isa<ConstantIntegral>(I->first))
181 ScalarMap.erase(I++);
185 // If there are any constant globals referenced in this function, merge their
186 // initializers into the local graph from the globals graph.
187 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
188 ReachabilityCloner RC(*this, *GG, 0);
190 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
191 I != ScalarMap.global_end(); ++I)
192 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
193 if (!GV->isExternal() && GV->isConstant())
194 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
197 markIncompleteNodes(DSGraph::MarkFormalArgs);
199 // Remove any nodes made dead due to merging...
200 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
204 //===----------------------------------------------------------------------===//
205 // Helper method implementations...
208 /// getValueDest - Return the DSNode that the actual value points to.
210 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
212 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
213 return 0; // Null doesn't point to anything, don't add to ScalarMap!
215 DSNodeHandle &NH = ScalarMap[V];
217 return NH; // Already have a node? Just return it...
219 // Otherwise we need to create a new node to point to.
220 // Check first for constant expressions that must be traversed to
221 // extract the actual value.
223 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
224 // Create a new global node for this global variable...
225 N = createNode(GV->getType()->getElementType());
227 } else if (Constant *C = dyn_cast<Constant>(V)) {
228 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
229 if (CE->getOpcode() == Instruction::Cast)
230 NH = getValueDest(*CE->getOperand(0));
231 else if (CE->getOpcode() == Instruction::GetElementPtr) {
232 visitGetElementPtrInst(*CE);
233 DSScalarMap::iterator I = ScalarMap.find(CE);
234 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
237 // This returns a conservative unknown node for any unhandled ConstExpr
238 return NH = createNode()->setUnknownNodeMarker();
240 if (NH.isNull()) { // (getelementptr null, X) returns null
246 } else if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(C)) {
247 // Random constants are unknown mem
248 return NH = createNode()->setUnknownNodeMarker();
249 } else if (isa<UndefValue>(C)) {
253 assert(0 && "Unknown constant type!");
255 N = createNode(); // just create a shadow node
257 // Otherwise just create a shadow node
261 NH.setTo(N, 0); // Remember that we are pointing to it...
266 /// getLink - This method is used to return the specified link in the
267 /// specified node if one exists. If a link does not already exist (it's
268 /// null), then we create a new node, link it, then return it. We must
269 /// specify the type of the Node field we are accessing so that we know what
270 /// type should be linked to if we need to create a new node.
272 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
273 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
274 DSNodeHandle &Link = Node.getLink(LinkNo);
276 // If the link hasn't been created yet, make and return a new shadow node
283 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
284 /// specified destination. If the Value already points to a node, make sure to
285 /// merge the two destinations together.
287 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
288 ScalarMap[&V].mergeWith(NH);
292 //===----------------------------------------------------------------------===//
293 // Specific instruction type handler implementations...
296 /// Alloca & Malloc instruction implementation - Simply create a new memory
297 /// object, pointing the scalar to it.
299 void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
300 DSNode *N = createNode();
302 N->setHeapNodeMarker();
304 N->setAllocaNodeMarker();
308 // PHINode - Make the scalar for the PHI node point to all of the things the
309 // incoming values point to... which effectively causes them to be merged.
311 void GraphBuilder::visitPHINode(PHINode &PN) {
312 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
314 DSNodeHandle &PNDest = ScalarMap[&PN];
315 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
316 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
319 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
320 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
321 if (Value.isNull()) return;
323 // As a special case, if all of the index operands of GEP are constant zeros,
324 // handle this just like we handle casts (ie, don't do much).
325 bool AllZeros = true;
326 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
327 if (GEP.getOperand(i) !=
328 Constant::getNullValue(GEP.getOperand(i)->getType())) {
333 // If all of the indices are zero, the result points to the operand without
334 // applying the type.
336 setDestTo(GEP, Value);
341 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
342 const Type *CurTy = PTy->getElementType();
344 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
345 // If the node had to be folded... exit quickly
346 setDestTo(GEP, Value); // GEP result points to folded node
350 const TargetData &TD = Value.getNode()->getTargetData();
353 // Handle the pointer index specially...
354 if (GEP.getNumOperands() > 1 &&
355 (!isa<Constant>(GEP.getOperand(1)) ||
356 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
358 // If we already know this is an array being accessed, don't do anything...
359 if (!TopTypeRec.isArray) {
360 TopTypeRec.isArray = true;
362 // If we are treating some inner field pointer as an array, fold the node
363 // up because we cannot handle it right. This can come because of
364 // something like this: &((&Pt->X)[1]) == &Pt->Y
366 if (Value.getOffset()) {
367 // Value is now the pointer we want to GEP to be...
368 Value.getNode()->foldNodeCompletely();
369 setDestTo(GEP, Value); // GEP result points to folded node
372 // This is a pointer to the first byte of the node. Make sure that we
373 // are pointing to the outter most type in the node.
374 // FIXME: We need to check one more case here...
380 // All of these subscripts are indexing INTO the elements we have...
382 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
384 if (const StructType *STy = dyn_cast<StructType>(*I)) {
386 (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
387 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
388 } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
389 if (!isa<Constant>(I.getOperand()) ||
390 !cast<Constant>(I.getOperand())->isNullValue())
391 Value.getNode()->setArrayMarker();
396 if (const SequentialType *STy = cast<SequentialType>(*I)) {
397 CurTy = STy->getElementType();
398 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
399 Offset += CS->getValue()*TD.getTypeSize(CurTy);
401 // Variable index into a node. We must merge all of the elements of the
402 // sequential type here.
403 if (isa<PointerType>(STy))
404 std::cerr << "Pointer indexing not handled yet!\n";
406 const ArrayType *ATy = cast<ArrayType>(STy);
407 unsigned ElSize = TD.getTypeSize(CurTy);
408 DSNode *N = Value.getNode();
409 assert(N && "Value must have a node!");
410 unsigned RawOffset = Offset+Value.getOffset();
412 // Loop over all of the elements of the array, merging them into the
414 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
415 // Merge all of the byte components of this array element
416 for (unsigned j = 0; j != ElSize; ++j)
417 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
423 // Add in the offset calculated...
424 Value.setOffset(Value.getOffset()+Offset);
426 // Value is now the pointer we want to GEP to be...
427 setDestTo(GEP, Value);
430 void GraphBuilder::visitLoadInst(LoadInst &LI) {
431 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
432 if (Ptr.getNode() == 0) return;
434 // Make that the node is read from...
435 Ptr.getNode()->setReadMarker();
437 // Ensure a typerecord exists...
438 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
440 if (isPointerType(LI.getType()))
441 setDestTo(LI, getLink(Ptr));
444 void GraphBuilder::visitStoreInst(StoreInst &SI) {
445 const Type *StoredTy = SI.getOperand(0)->getType();
446 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
447 if (Dest.isNull()) return;
449 // Mark that the node is written to...
450 Dest.getNode()->setModifiedMarker();
452 // Ensure a type-record exists...
453 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
455 // Avoid adding edges from null, or processing non-"pointer" stores
456 if (isPointerType(StoredTy))
457 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
460 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
461 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
462 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
465 void GraphBuilder::visitVANextInst(VANextInst &I) {
466 getValueDest(*I.getOperand(0)).mergeWith(getValueDest(I));
469 void GraphBuilder::visitVAArgInst(VAArgInst &I) {
470 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
471 if (Ptr.isNull()) return;
473 // Make that the node is read from.
474 Ptr.getNode()->setReadMarker();
476 // Ensure a type record exists.
477 DSNode *PtrN = Ptr.getNode();
478 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
480 if (isPointerType(I.getType()))
481 setDestTo(I, getLink(Ptr));
485 void GraphBuilder::visitCallInst(CallInst &CI) {
489 void GraphBuilder::visitInvokeInst(InvokeInst &II) {
493 void GraphBuilder::visitCallSite(CallSite CS) {
494 Value *Callee = CS.getCalledValue();
496 // Special case handling of certain libc allocation functions here.
497 if (Function *F = dyn_cast<Function>(Callee))
499 switch (F->getIntrinsicID()) {
500 case Intrinsic::vastart:
501 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
503 case Intrinsic::vacopy:
504 getValueDest(*CS.getInstruction()).
505 mergeWith(getValueDest(**(CS.arg_begin())));
507 case Intrinsic::vaend:
509 case Intrinsic::memmove:
510 case Intrinsic::memcpy: {
511 // Merge the first & second arguments, and mark the memory read and
513 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
514 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
515 if (DSNode *N = RetNH.getNode())
516 N->setModifiedMarker()->setReadMarker();
519 case Intrinsic::memset:
520 // Mark the memory modified.
521 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
522 N->setModifiedMarker();
525 if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
526 F->getName() == "memalign" || F->getName() == "valloc") {
527 setDestTo(*CS.getInstruction(),
528 createNode()->setHeapNodeMarker()->setModifiedMarker());
530 } else if (F->getName() == "realloc") {
531 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
532 if (CS.arg_begin() != CS.arg_end())
533 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
534 if (DSNode *N = RetNH.getNode())
535 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
537 } else if (F->getName() == "memmove") {
538 // Merge the first & second arguments, and mark the memory read and
540 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
541 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
542 if (DSNode *N = RetNH.getNode())
543 N->setModifiedMarker()->setReadMarker();
546 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
547 F->getName() == "atol" || F->getName() == "atoll" ||
548 F->getName() == "remove" || F->getName() == "unlink" ||
549 F->getName() == "rename" || F->getName() == "memcmp" ||
550 F->getName() == "strcmp" || F->getName() == "strncmp" ||
551 F->getName() == "execl" || F->getName() == "execlp" ||
552 F->getName() == "execle" || F->getName() == "execv" ||
553 F->getName() == "execvp" || F->getName() == "chmod" ||
554 F->getName() == "puts" || F->getName() == "write" ||
555 F->getName() == "open" || F->getName() == "create" ||
556 F->getName() == "truncate" || F->getName() == "chdir" ||
557 F->getName() == "mkdir" || F->getName() == "rmdir") {
558 // These functions read all of their pointer operands.
559 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
561 if (isPointerType((*AI)->getType()))
562 if (DSNode *N = getValueDest(**AI).getNode())
566 } else if (F->getName() == "read" || F->getName() == "pipe" ||
567 F->getName() == "wait" || F->getName() == "time") {
568 // These functions write all of their pointer operands.
569 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
571 if (isPointerType((*AI)->getType()))
572 if (DSNode *N = getValueDest(**AI).getNode())
573 N->setModifiedMarker();
576 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
577 F->getName() == "lstat") {
578 // These functions read their first operand if its a pointer.
579 CallSite::arg_iterator AI = CS.arg_begin();
580 if (isPointerType((*AI)->getType())) {
581 DSNodeHandle Path = getValueDest(**AI);
582 if (DSNode *N = Path.getNode()) N->setReadMarker();
585 // Then they write into the stat buffer.
586 DSNodeHandle StatBuf = getValueDest(**++AI);
587 if (DSNode *N = StatBuf.getNode()) {
588 N->setModifiedMarker();
589 const Type *StatTy = F->getFunctionType()->getParamType(1);
590 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
591 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
594 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
595 F->getName() == "strtold") {
596 // These functions read the first pointer
597 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
598 Str->setReadMarker();
599 // If the second parameter is passed, it will point to the first
601 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
602 if (DSNode *End = EndPtrNH.getNode()) {
603 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
604 EndPtrNH.getOffset(), false);
605 End->setModifiedMarker();
606 DSNodeHandle &Link = getLink(EndPtrNH);
607 Link.mergeWith(getValueDest(**CS.arg_begin()));
612 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
613 F->getName() == "freopen") {
614 // These functions read all of their pointer operands.
615 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
617 if (isPointerType((*AI)->getType()))
618 if (DSNode *N = getValueDest(**AI).getNode())
621 // fopen allocates in an unknown way and writes to the file
622 // descriptor. Also, merge the allocated type into the node.
623 DSNodeHandle Result = getValueDest(*CS.getInstruction());
624 if (DSNode *N = Result.getNode()) {
625 N->setModifiedMarker()->setUnknownNodeMarker();
626 const Type *RetTy = F->getFunctionType()->getReturnType();
627 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
628 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
631 // If this is freopen, merge the file descriptor passed in with the
633 if (F->getName() == "freopen") {
634 // ICC doesn't handle getting the iterator, decrementing and
635 // dereferencing it in one operation without error. Do it in 2 steps
636 CallSite::arg_iterator compit = CS.arg_end();
637 Result.mergeWith(getValueDest(**--compit));
640 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
641 // fclose reads and deallocates the memory in an unknown way for the
642 // file descriptor. It merges the FILE type into the descriptor.
643 DSNodeHandle H = getValueDest(**CS.arg_begin());
644 if (DSNode *N = H.getNode()) {
645 N->setReadMarker()->setUnknownNodeMarker();
646 const Type *ArgTy = F->getFunctionType()->getParamType(0);
647 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
648 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
651 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
652 (F->getName() == "fflush" || F->getName() == "feof" ||
653 F->getName() == "fileno" || F->getName() == "clearerr" ||
654 F->getName() == "rewind" || F->getName() == "ftell" ||
655 F->getName() == "ferror" || F->getName() == "fgetc" ||
656 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
657 // fflush reads and writes the memory for the file descriptor. It
658 // merges the FILE type into the descriptor.
659 DSNodeHandle H = getValueDest(**CS.arg_begin());
660 if (DSNode *N = H.getNode()) {
661 N->setReadMarker()->setModifiedMarker();
663 const Type *ArgTy = F->getFunctionType()->getParamType(0);
664 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
665 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
668 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
669 (F->getName() == "fwrite" || F->getName() == "fread")) {
670 // fread writes the first operand, fwrite reads it. They both
671 // read/write the FILE descriptor, and merges the FILE type.
672 CallSite::arg_iterator compit = CS.arg_end();
673 DSNodeHandle H = getValueDest(**--compit);
674 if (DSNode *N = H.getNode()) {
675 N->setReadMarker()->setModifiedMarker();
676 const Type *ArgTy = F->getFunctionType()->getParamType(3);
677 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
678 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
681 H = getValueDest(**CS.arg_begin());
682 if (DSNode *N = H.getNode())
683 if (F->getName() == "fwrite")
686 N->setModifiedMarker();
688 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
689 // fgets reads and writes the memory for the file descriptor. It
690 // merges the FILE type into the descriptor, and writes to the
691 // argument. It returns the argument as well.
692 CallSite::arg_iterator AI = CS.arg_begin();
693 DSNodeHandle H = getValueDest(**AI);
694 if (DSNode *N = H.getNode())
695 N->setModifiedMarker(); // Writes buffer
696 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
699 // Reads and writes file descriptor, merge in FILE type.
700 H = getValueDest(**AI);
701 if (DSNode *N = H.getNode()) {
702 N->setReadMarker()->setModifiedMarker();
703 const Type *ArgTy = F->getFunctionType()->getParamType(2);
704 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
705 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
708 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
709 F->getName() == "fputs" || F->getName() == "putc" ||
710 F->getName() == "ftell" || F->getName() == "rewind" ||
711 F->getName() == "_IO_putc") {
712 // These functions read and write the memory for the file descriptor,
713 // which is passes as the last argument.
714 CallSite::arg_iterator compit = CS.arg_end();
715 DSNodeHandle H = getValueDest(**--compit);
716 if (DSNode *N = H.getNode()) {
717 N->setReadMarker()->setModifiedMarker();
718 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
719 const Type *ArgTy = *--compit2;
720 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
721 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
724 // Any pointer arguments are read.
725 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
727 if (isPointerType((*AI)->getType()))
728 if (DSNode *N = getValueDest(**AI).getNode())
731 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
732 F->getName() == "fsetpos") {
733 // These functions read and write the memory for the file descriptor,
734 // and read/write all other arguments.
735 DSNodeHandle H = getValueDest(**CS.arg_begin());
736 if (DSNode *N = H.getNode()) {
737 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
738 const Type *ArgTy = *--compit2;
739 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
740 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
743 // Any pointer arguments are read.
744 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
746 if (isPointerType((*AI)->getType()))
747 if (DSNode *N = getValueDest(**AI).getNode())
748 N->setReadMarker()->setModifiedMarker();
750 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
751 F->getName() == "sprintf") {
752 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
754 if (F->getName() == "fprintf") {
755 // fprintf reads and writes the FILE argument, and applies the type
757 DSNodeHandle H = getValueDest(**AI);
758 if (DSNode *N = H.getNode()) {
759 N->setModifiedMarker();
760 const Type *ArgTy = (*AI)->getType();
761 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
762 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
764 } else if (F->getName() == "sprintf") {
765 // sprintf writes the first string argument.
766 DSNodeHandle H = getValueDest(**AI++);
767 if (DSNode *N = H.getNode()) {
768 N->setModifiedMarker();
769 const Type *ArgTy = (*AI)->getType();
770 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
771 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
775 for (; AI != E; ++AI) {
776 // printf reads all pointer arguments.
777 if (isPointerType((*AI)->getType()))
778 if (DSNode *N = getValueDest(**AI).getNode())
782 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
783 F->getName() == "vsprintf") {
784 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
786 if (F->getName() == "vfprintf") {
787 // ffprintf reads and writes the FILE argument, and applies the type
789 DSNodeHandle H = getValueDest(**AI);
790 if (DSNode *N = H.getNode()) {
791 N->setModifiedMarker()->setReadMarker();
792 const Type *ArgTy = (*AI)->getType();
793 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
794 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
797 } else if (F->getName() == "vsprintf") {
798 // vsprintf writes the first string argument.
799 DSNodeHandle H = getValueDest(**AI++);
800 if (DSNode *N = H.getNode()) {
801 N->setModifiedMarker();
802 const Type *ArgTy = (*AI)->getType();
803 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
804 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
810 if (isPointerType((*AI)->getType()))
811 if (DSNode *N = getValueDest(**AI).getNode())
816 // Read the valist, and the pointed-to objects.
817 if (AI != E && isPointerType((*AI)->getType())) {
818 const DSNodeHandle &VAList = getValueDest(**AI);
819 if (DSNode *N = VAList.getNode()) {
821 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
822 VAList.getOffset(), false);
824 DSNodeHandle &VAListObjs = getLink(VAList);
825 VAListObjs.getNode()->setReadMarker();
830 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
831 F->getName() == "sscanf") {
832 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
834 if (F->getName() == "fscanf") {
835 // fscanf reads and writes the FILE argument, and applies the type
837 DSNodeHandle H = getValueDest(**AI);
838 if (DSNode *N = H.getNode()) {
840 const Type *ArgTy = (*AI)->getType();
841 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
842 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
844 } else if (F->getName() == "sscanf") {
845 // sscanf reads the first string argument.
846 DSNodeHandle H = getValueDest(**AI++);
847 if (DSNode *N = H.getNode()) {
849 const Type *ArgTy = (*AI)->getType();
850 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
851 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
855 for (; AI != E; ++AI) {
856 // scanf writes all pointer arguments.
857 if (isPointerType((*AI)->getType()))
858 if (DSNode *N = getValueDest(**AI).getNode())
859 N->setModifiedMarker();
862 } else if (F->getName() == "strtok") {
863 // strtok reads and writes the first argument, returning it. It reads
864 // its second arg. FIXME: strtok also modifies some hidden static
865 // data. Someday this might matter.
866 CallSite::arg_iterator AI = CS.arg_begin();
867 DSNodeHandle H = getValueDest(**AI++);
868 if (DSNode *N = H.getNode()) {
869 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
870 const Type *ArgTy = F->getFunctionType()->getParamType(0);
871 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
872 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
874 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
876 H = getValueDest(**AI); // Reads delimiter
877 if (DSNode *N = H.getNode()) {
879 const Type *ArgTy = F->getFunctionType()->getParamType(1);
880 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
881 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
884 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
885 F->getName() == "strstr") {
886 // These read their arguments, and return the first one
887 DSNodeHandle H = getValueDest(**CS.arg_begin());
888 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
890 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
892 if (isPointerType((*AI)->getType()))
893 if (DSNode *N = getValueDest(**AI).getNode())
896 if (DSNode *N = H.getNode())
899 } else if (F->getName() == "__assert_fail") {
900 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
902 if (isPointerType((*AI)->getType()))
903 if (DSNode *N = getValueDest(**AI).getNode())
906 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
907 // This writes its second argument, and forces it to double.
908 CallSite::arg_iterator compit = CS.arg_end();
909 DSNodeHandle H = getValueDest(**--compit);
910 if (DSNode *N = H.getNode()) {
911 N->setModifiedMarker();
912 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
916 // Unknown function, warn if it returns a pointer type or takes a
918 bool Warn = isPointerType(CS.getInstruction()->getType());
920 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
922 if (isPointerType((*I)->getType())) {
927 std::cerr << "WARNING: Call to unknown external function '"
928 << F->getName() << "' will cause pessimistic results!\n";
933 // Set up the return value...
935 Instruction *I = CS.getInstruction();
936 if (isPointerType(I->getType()))
937 RetVal = getValueDest(*I);
939 DSNode *CalleeNode = 0;
940 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
941 CalleeNode = getValueDest(*Callee).getNode();
942 if (CalleeNode == 0) {
943 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
944 return; // Calling a null pointer?
948 std::vector<DSNodeHandle> Args;
949 Args.reserve(CS.arg_end()-CS.arg_begin());
951 // Calculate the arguments vector...
952 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
953 if (isPointerType((*I)->getType()))
954 Args.push_back(getValueDest(**I));
956 // Add a new function call entry...
958 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
960 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
964 void GraphBuilder::visitFreeInst(FreeInst &FI) {
965 // Mark that the node is written to...
966 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
967 N->setModifiedMarker()->setHeapNodeMarker();
971 void GraphBuilder::visitCastInst(CastInst &CI) {
972 if (isPointerType(CI.getType()))
973 if (isPointerType(CI.getOperand(0)->getType())) {
974 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
975 if (Ptr.getNode() == 0) return;
977 // Cast one pointer to the other, just act like a copy instruction
980 // Cast something (floating point, small integer) to a pointer. We need
981 // to track the fact that the node points to SOMETHING, just something we
982 // don't know about. Make an "Unknown" node.
984 setDestTo(CI, createNode()->setUnknownNodeMarker());
989 // visitInstruction - For all other instruction types, if we have any arguments
990 // that are of pointer type, make them have unknown composition bits, and merge
991 // the nodes together.
992 void GraphBuilder::visitInstruction(Instruction &Inst) {
993 DSNodeHandle CurNode;
994 if (isPointerType(Inst.getType()))
995 CurNode = getValueDest(Inst);
996 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
997 if (isPointerType((*I)->getType()))
998 CurNode.mergeWith(getValueDest(**I));
1000 if (DSNode *N = CurNode.getNode())
1001 N->setUnknownNodeMarker();
1006 //===----------------------------------------------------------------------===//
1007 // LocalDataStructures Implementation
1008 //===----------------------------------------------------------------------===//
1010 // MergeConstantInitIntoNode - Merge the specified constant into the node
1011 // pointed to by NH.
1012 void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1013 // Ensure a type-record exists...
1014 DSNode *NHN = NH.getNode();
1015 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
1017 if (C->getType()->isFirstClassType()) {
1018 if (isPointerType(C->getType()))
1019 // Avoid adding edges from null, or processing non-"pointer" stores
1020 NH.addEdgeTo(getValueDest(*C));
1024 const TargetData &TD = NH.getNode()->getTargetData();
1026 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1027 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1028 // We don't currently do any indexing for arrays...
1029 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1030 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1031 const StructLayout *SL = TD.getStructLayout(CS->getType());
1032 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1033 DSNode *NHN = NH.getNode();
1034 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1035 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1037 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
1040 assert(0 && "Unknown constant type!");
1044 void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1045 assert(!GV->isExternal() && "Cannot merge in external global!");
1046 // Get a node handle to the global node and merge the initializer into it.
1047 DSNodeHandle NH = getValueDest(*GV);
1048 MergeConstantInitIntoNode(NH, GV->getInitializer());
1052 bool LocalDataStructures::runOnModule(Module &M) {
1053 GlobalsGraph = new DSGraph(getAnalysis<TargetData>());
1055 const TargetData &TD = getAnalysis<TargetData>();
1058 GraphBuilder GGB(*GlobalsGraph);
1060 // Add initializers for all of the globals to the globals graph...
1061 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
1062 if (!I->isExternal())
1063 GGB.mergeInGlobalInitializer(I);
1066 // Calculate all of the graphs...
1067 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1068 if (!I->isExternal())
1069 DSInfo.insert(std::make_pair(I, new DSGraph(TD, *I, GlobalsGraph)));
1071 GlobalsGraph->removeTriviallyDeadNodes();
1072 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
1076 // releaseMemory - If the pass pipeline is done with this pass, we can release
1077 // our memory... here...
1079 void LocalDataStructures::releaseMemory() {
1080 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1081 E = DSInfo.end(); I != E; ++I) {
1082 I->second->getReturnNodes().erase(I->first);
1083 if (I->second->getReturnNodes().empty())
1087 // Empty map so next time memory is released, data structures are not
1090 delete GlobalsGraph;