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"
29 // FIXME: This should eventually be a FunctionPass that is automatically
30 // aggregated into a Pass.
32 #include "llvm/Module.h"
36 static RegisterPass<LocalDataStructures>
37 X("datastructure", "Local Data Structure Analysis");
40 TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
41 cl::desc("If this is set, track integers as potential pointers"));
44 IgnoreSetCC("dsa-ignore-setcc", cl::Hidden,
45 cl::desc("If this is set, do nothing at pointer comparisons"));
47 static cl::list<std::string>
48 AllocList("dsa-alloc-list",
49 cl::value_desc("list"),
50 cl::desc("List of functions that allocate memory from the heap"),
51 cl::CommaSeparated, cl::Hidden);
53 static cl::list<std::string>
54 FreeList("dsa-free-list",
55 cl::value_desc("list"),
56 cl::desc("List of functions that free memory from the heap"),
57 cl::CommaSeparated, cl::Hidden);
61 // isPointerType - Return true if this type is big enough to hold a pointer.
62 bool isPointerType(const Type *Ty) {
63 if (isa<PointerType>(Ty))
65 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
66 return Ty->getPrimitiveSize() >= PointerSize;
75 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
76 cl::desc("Disable direct call optimization in "
77 "DSGraph construction"));
79 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
80 cl::desc("Disable field sensitivity in DSGraphs"));
82 //===--------------------------------------------------------------------===//
84 //===--------------------------------------------------------------------===//
86 /// This class is the builder class that constructs the local data structure
87 /// graph by performing a single pass over the function in question.
89 class GraphBuilder : InstVisitor<GraphBuilder> {
91 DSNodeHandle *RetNode; // Node that gets returned...
92 DSScalarMap &ScalarMap;
93 std::list<DSCallSite> *FunctionCalls;
96 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
97 std::list<DSCallSite> &fc)
98 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
101 // Create scalar nodes for all pointer arguments...
102 for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end();
104 if (isPointerType(I->getType()))
107 visit(f); // Single pass over the function
110 // GraphBuilder ctor for working on the globals graph
111 GraphBuilder(DSGraph &g)
112 : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
115 void mergeInGlobalInitializer(GlobalVariable *GV);
118 // Visitor functions, used to handle each instruction type we encounter...
119 friend class InstVisitor<GraphBuilder>;
120 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
121 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
122 void handleAlloc(AllocationInst &AI, bool isHeap);
124 void visitPHINode(PHINode &PN);
125 void visitSelectInst(SelectInst &SI);
127 void visitGetElementPtrInst(User &GEP);
128 void visitReturnInst(ReturnInst &RI);
129 void visitLoadInst(LoadInst &LI);
130 void visitStoreInst(StoreInst &SI);
131 void visitCallInst(CallInst &CI);
132 void visitInvokeInst(InvokeInst &II);
133 void visitSetCondInst(SetCondInst &SCI);
134 void visitFreeInst(FreeInst &FI);
135 void visitCastInst(CastInst &CI);
136 void visitInstruction(Instruction &I);
138 bool visitIntrinsic(CallSite CS, Function* F);
139 bool visitExternal(CallSite CS, Function* F);
140 void visitCallSite(CallSite CS);
141 void visitVAArgInst(VAArgInst &I);
143 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
145 // Helper functions used to implement the visitation functions...
147 /// createNode - Create a new DSNode, ensuring that it is properly added to
150 DSNode *createNode(const Type *Ty = 0) {
151 DSNode *N = new DSNode(Ty, &G); // Create the node
152 if (DisableFieldSensitivity) {
153 // Create node handle referring to the old node so that it is
154 // immediately removed from the graph when the node handle is destroyed.
155 DSNodeHandle OldNNH = N;
156 N->foldNodeCompletely();
157 if (DSNode *FN = N->getForwardNode())
163 /// setDestTo - Set the ScalarMap entry for the specified value to point to
164 /// the specified destination. If the Value already points to a node, make
165 /// sure to merge the two destinations together.
167 void setDestTo(Value &V, const DSNodeHandle &NH);
169 /// getValueDest - Return the DSNode that the actual value points to.
171 DSNodeHandle getValueDest(Value &V);
173 /// getLink - This method is used to return the specified link in the
174 /// specified node if one exists. If a link does not already exist (it's
175 /// null), then we create a new node, link it, then return it.
177 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
183 //===----------------------------------------------------------------------===//
184 // DSGraph constructor - Simply use the GraphBuilder to construct the local
186 DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
187 Function &F, DSGraph *GG)
188 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
189 PrintAuxCalls = false;
191 DOUT << " [Loc] Calculating graph for: " << F.getName() << "\n";
193 // Use the graph builder to construct the local version of the graph
194 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
196 Timer::addPeakMemoryMeasurement();
199 // If there are any constant globals referenced in this function, merge their
200 // initializers into the local graph from the globals graph.
201 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
202 ReachabilityCloner RC(*this, *GG, 0);
204 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
205 I != ScalarMap.global_end(); ++I)
206 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
207 if (!GV->isExternal() && GV->isConstant())
208 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
211 markIncompleteNodes(DSGraph::MarkFormalArgs);
213 // Remove any nodes made dead due to merging...
214 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
218 //===----------------------------------------------------------------------===//
219 // Helper method implementations...
222 /// getValueDest - Return the DSNode that the actual value points to.
224 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
226 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
227 return 0; // Null doesn't point to anything, don't add to ScalarMap!
229 DSNodeHandle &NH = ScalarMap[V];
231 return NH; // Already have a node? Just return it...
233 // Otherwise we need to create a new node to point to.
234 // Check first for constant expressions that must be traversed to
235 // extract the actual value.
237 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
238 // Create a new global node for this global variable.
239 N = createNode(GV->getType()->getElementType());
241 } else if (Constant *C = dyn_cast<Constant>(V)) {
242 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
244 if (isa<PointerType>(CE->getOperand(0)->getType()))
245 NH = getValueDest(*CE->getOperand(0));
247 NH = createNode()->setUnknownNodeMarker();
248 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
249 visitGetElementPtrInst(*CE);
250 DSScalarMap::iterator I = ScalarMap.find(CE);
251 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
254 // This returns a conservative unknown node for any unhandled ConstExpr
255 return NH = createNode()->setUnknownNodeMarker();
257 if (NH.isNull()) { // (getelementptr null, X) returns null
262 } else if (isa<UndefValue>(C)) {
266 assert(0 && "Unknown constant type!");
268 N = createNode(); // just create a shadow node
270 // Otherwise just create a shadow node
274 NH.setTo(N, 0); // Remember that we are pointing to it...
279 /// getLink - This method is used to return the specified link in the
280 /// specified node if one exists. If a link does not already exist (it's
281 /// null), then we create a new node, link it, then return it. We must
282 /// specify the type of the Node field we are accessing so that we know what
283 /// type should be linked to if we need to create a new node.
285 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
286 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
287 DSNodeHandle &Link = Node.getLink(LinkNo);
289 // If the link hasn't been created yet, make and return a new shadow node
296 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
297 /// specified destination. If the Value already points to a node, make sure to
298 /// merge the two destinations together.
300 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
301 ScalarMap[&V].mergeWith(NH);
305 //===----------------------------------------------------------------------===//
306 // Specific instruction type handler implementations...
309 /// Alloca & Malloc instruction implementation - Simply create a new memory
310 /// object, pointing the scalar to it.
312 void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
313 DSNode *N = createNode();
315 N->setHeapNodeMarker();
317 N->setAllocaNodeMarker();
321 // PHINode - Make the scalar for the PHI node point to all of the things the
322 // incoming values point to... which effectively causes them to be merged.
324 void GraphBuilder::visitPHINode(PHINode &PN) {
325 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
327 DSNodeHandle &PNDest = ScalarMap[&PN];
328 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
329 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
332 void GraphBuilder::visitSelectInst(SelectInst &SI) {
333 if (!isPointerType(SI.getType())) return; // Only pointer Selects
335 DSNodeHandle &Dest = ScalarMap[&SI];
336 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
337 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
340 void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
341 if (!isPointerType(SCI.getOperand(0)->getType()) ||
342 isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
344 ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
348 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
349 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
351 Value = createNode();
353 // As a special case, if all of the index operands of GEP are constant zeros,
354 // handle this just like we handle casts (ie, don't do much).
355 bool AllZeros = true;
356 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
357 if (GEP.getOperand(i) !=
358 Constant::getNullValue(GEP.getOperand(i)->getType())) {
363 // If all of the indices are zero, the result points to the operand without
364 // applying the type.
365 if (AllZeros || (!Value.isNull() &&
366 Value.getNode()->isNodeCompletelyFolded())) {
367 setDestTo(GEP, Value);
372 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
373 const Type *CurTy = PTy->getElementType();
375 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
376 // If the node had to be folded... exit quickly
377 setDestTo(GEP, Value); // GEP result points to folded node
381 const TargetData &TD = Value.getNode()->getTargetData();
384 // Handle the pointer index specially...
385 if (GEP.getNumOperands() > 1 &&
386 (!isa<Constant>(GEP.getOperand(1)) ||
387 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
389 // If we already know this is an array being accessed, don't do anything...
390 if (!TopTypeRec.isArray) {
391 TopTypeRec.isArray = true;
393 // If we are treating some inner field pointer as an array, fold the node
394 // up because we cannot handle it right. This can come because of
395 // something like this: &((&Pt->X)[1]) == &Pt->Y
397 if (Value.getOffset()) {
398 // Value is now the pointer we want to GEP to be...
399 Value.getNode()->foldNodeCompletely();
400 setDestTo(GEP, Value); // GEP result points to folded node
403 // This is a pointer to the first byte of the node. Make sure that we
404 // are pointing to the outter most type in the node.
405 // FIXME: We need to check one more case here...
411 // All of these subscripts are indexing INTO the elements we have...
413 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
415 if (const StructType *STy = dyn_cast<StructType>(*I)) {
416 const ConstantInt* CUI = cast<ConstantInt>(I.getOperand());
418 CUI->getType()->isSigned() ? CUI->getSExtValue() : CUI->getZExtValue();
419 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
420 } else if (isa<PointerType>(*I)) {
421 if (!isa<Constant>(I.getOperand()) ||
422 !cast<Constant>(I.getOperand())->isNullValue())
423 Value.getNode()->setArrayMarker();
428 if (const SequentialType *STy = cast<SequentialType>(*I)) {
429 CurTy = STy->getElementType();
430 if (ConstantInt *CS = dyn_cast<ConstantInt>(GEP.getOperand(i))) {
432 (CS->getType()->isSigned() ? CS->getSExtValue() : CS->getZExtValue())
433 * TD.getTypeSize(CurTy);
435 // Variable index into a node. We must merge all of the elements of the
436 // sequential type here.
437 if (isa<PointerType>(STy))
438 std::cerr << "Pointer indexing not handled yet!\n";
440 const ArrayType *ATy = cast<ArrayType>(STy);
441 unsigned ElSize = TD.getTypeSize(CurTy);
442 DSNode *N = Value.getNode();
443 assert(N && "Value must have a node!");
444 unsigned RawOffset = Offset+Value.getOffset();
446 // Loop over all of the elements of the array, merging them into the
448 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
449 // Merge all of the byte components of this array element
450 for (unsigned j = 0; j != ElSize; ++j)
451 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
457 // Add in the offset calculated...
458 Value.setOffset(Value.getOffset()+Offset);
461 DSNode *N = Value.getNode();
463 !N->isNodeCompletelyFolded() &&
464 (N->getSize() != 0 || Offset != 0) &&
465 !N->isForwarding()) {
466 if ((Offset >= N->getSize()) || int(Offset) < 0) {
467 // Accessing offsets out of node size range
468 // This is seen in the "magic" struct in named (from bind), where the
469 // fourth field is an array of length 0, presumably used to create struct
470 // instances of different sizes
472 // Collapse the node since its size is now variable
473 N->foldNodeCompletely();
477 // Value is now the pointer we want to GEP to be...
478 setDestTo(GEP, Value);
481 void GraphBuilder::visitLoadInst(LoadInst &LI) {
482 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
486 // Make that the node is read from...
487 Ptr.getNode()->setReadMarker();
489 // Ensure a typerecord exists...
490 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
492 if (isPointerType(LI.getType()))
493 setDestTo(LI, getLink(Ptr));
496 void GraphBuilder::visitStoreInst(StoreInst &SI) {
497 const Type *StoredTy = SI.getOperand(0)->getType();
498 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
499 if (Dest.isNull()) return;
501 // Mark that the node is written to...
502 Dest.getNode()->setModifiedMarker();
504 // Ensure a type-record exists...
505 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
507 // Avoid adding edges from null, or processing non-"pointer" stores
508 if (isPointerType(StoredTy))
509 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
512 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
513 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
514 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
517 void GraphBuilder::visitVAArgInst(VAArgInst &I) {
518 //FIXME: also updates the argument
519 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
520 if (Ptr.isNull()) return;
522 // Make that the node is read from.
523 Ptr.getNode()->setReadMarker();
525 // Ensure a type record exists.
526 DSNode *PtrN = Ptr.getNode();
527 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
529 if (isPointerType(I.getType()))
530 setDestTo(I, getLink(Ptr));
534 void GraphBuilder::visitCallInst(CallInst &CI) {
538 void GraphBuilder::visitInvokeInst(InvokeInst &II) {
542 /// returns true if the intrinsic is handled
543 bool GraphBuilder::visitIntrinsic(CallSite CS, Function *F) {
544 switch (F->getIntrinsicID()) {
545 case Intrinsic::vastart:
546 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
548 case Intrinsic::vacopy:
549 getValueDest(*CS.getInstruction()).
550 mergeWith(getValueDest(**(CS.arg_begin())));
552 case Intrinsic::vaend:
553 case Intrinsic::dbg_func_start:
554 case Intrinsic::dbg_region_end:
555 case Intrinsic::dbg_stoppoint:
557 case Intrinsic::memcpy_i32:
558 case Intrinsic::memcpy_i64:
559 case Intrinsic::memmove_i32:
560 case Intrinsic::memmove_i64: {
561 // Merge the first & second arguments, and mark the memory read and
563 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
564 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
565 if (DSNode *N = RetNH.getNode())
566 N->setModifiedMarker()->setReadMarker();
569 case Intrinsic::memset_i32:
570 case Intrinsic::memset_i64:
571 // Mark the memory modified.
572 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
573 N->setModifiedMarker();
576 DOUT << "[dsa:local] Unhandled intrinsic: " << F->getName() << "\n";
581 /// returns true if the external is a recognized libc function with a
582 /// known (and generated) graph
583 bool GraphBuilder::visitExternal(CallSite CS, Function *F) {
584 if (F->getName() == "calloc"
585 || F->getName() == "posix_memalign"
586 || F->getName() == "memalign" || F->getName() == "valloc") {
587 setDestTo(*CS.getInstruction(),
588 createNode()->setHeapNodeMarker()->setModifiedMarker());
590 } else if (F->getName() == "realloc") {
591 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
592 if (CS.arg_begin() != CS.arg_end())
593 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
594 if (DSNode *N = RetNH.getNode())
595 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
597 } else if (F->getName() == "memmove") {
598 // Merge the first & second arguments, and mark the memory read and
600 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
601 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
602 if (DSNode *N = RetNH.getNode())
603 N->setModifiedMarker()->setReadMarker();
605 } else if (F->getName() == "free") {
606 // Mark that the node is written to...
607 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
608 N->setModifiedMarker()->setHeapNodeMarker();
609 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
610 F->getName() == "atol" || F->getName() == "atoll" ||
611 F->getName() == "remove" || F->getName() == "unlink" ||
612 F->getName() == "rename" || F->getName() == "memcmp" ||
613 F->getName() == "strcmp" || F->getName() == "strncmp" ||
614 F->getName() == "execl" || F->getName() == "execlp" ||
615 F->getName() == "execle" || F->getName() == "execv" ||
616 F->getName() == "execvp" || F->getName() == "chmod" ||
617 F->getName() == "puts" || F->getName() == "write" ||
618 F->getName() == "open" || F->getName() == "create" ||
619 F->getName() == "truncate" || F->getName() == "chdir" ||
620 F->getName() == "mkdir" || F->getName() == "rmdir" ||
621 F->getName() == "strlen") {
622 // These functions read all of their pointer operands.
623 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
625 if (isPointerType((*AI)->getType()))
626 if (DSNode *N = getValueDest(**AI).getNode())
630 } else if (F->getName() == "memchr") {
631 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
632 DSNodeHandle Result = getValueDest(*CS.getInstruction());
633 RetNH.mergeWith(Result);
634 if (DSNode *N = RetNH.getNode())
637 } else if (F->getName() == "read" || F->getName() == "pipe" ||
638 F->getName() == "wait" || F->getName() == "time" ||
639 F->getName() == "getrusage") {
640 // These functions write all of their pointer operands.
641 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
643 if (isPointerType((*AI)->getType()))
644 if (DSNode *N = getValueDest(**AI).getNode())
645 N->setModifiedMarker();
648 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
649 F->getName() == "lstat") {
650 // These functions read their first operand if its a pointer.
651 CallSite::arg_iterator AI = CS.arg_begin();
652 if (isPointerType((*AI)->getType())) {
653 DSNodeHandle Path = getValueDest(**AI);
654 if (DSNode *N = Path.getNode()) N->setReadMarker();
657 // Then they write into the stat buffer.
658 DSNodeHandle StatBuf = getValueDest(**++AI);
659 if (DSNode *N = StatBuf.getNode()) {
660 N->setModifiedMarker();
661 const Type *StatTy = F->getFunctionType()->getParamType(1);
662 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
663 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
666 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
667 F->getName() == "strtold") {
668 // These functions read the first pointer
669 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
670 Str->setReadMarker();
671 // If the second parameter is passed, it will point to the first
673 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
674 if (DSNode *End = EndPtrNH.getNode()) {
675 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
676 EndPtrNH.getOffset(), false);
677 End->setModifiedMarker();
678 DSNodeHandle &Link = getLink(EndPtrNH);
679 Link.mergeWith(getValueDest(**CS.arg_begin()));
683 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
684 F->getName() == "freopen") {
685 // These functions read all of their pointer operands.
686 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
688 if (isPointerType((*AI)->getType()))
689 if (DSNode *N = getValueDest(**AI).getNode())
692 // fopen allocates in an unknown way and writes to the file
693 // descriptor. Also, merge the allocated type into the node.
694 DSNodeHandle Result = getValueDest(*CS.getInstruction());
695 if (DSNode *N = Result.getNode()) {
696 N->setModifiedMarker()->setUnknownNodeMarker();
697 const Type *RetTy = F->getFunctionType()->getReturnType();
698 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
699 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
702 // If this is freopen, merge the file descriptor passed in with the
704 if (F->getName() == "freopen") {
705 // ICC doesn't handle getting the iterator, decrementing and
706 // dereferencing it in one operation without error. Do it in 2 steps
707 CallSite::arg_iterator compit = CS.arg_end();
708 Result.mergeWith(getValueDest(**--compit));
711 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
712 // fclose reads and deallocates the memory in an unknown way for the
713 // file descriptor. It merges the FILE type into the descriptor.
714 DSNodeHandle H = getValueDest(**CS.arg_begin());
715 if (DSNode *N = H.getNode()) {
716 N->setReadMarker()->setUnknownNodeMarker();
717 const Type *ArgTy = F->getFunctionType()->getParamType(0);
718 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
719 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
722 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
723 (F->getName() == "fflush" || F->getName() == "feof" ||
724 F->getName() == "fileno" || F->getName() == "clearerr" ||
725 F->getName() == "rewind" || F->getName() == "ftell" ||
726 F->getName() == "ferror" || F->getName() == "fgetc" ||
727 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
728 // fflush reads and writes the memory for the file descriptor. It
729 // merges the FILE type into the descriptor.
730 DSNodeHandle H = getValueDest(**CS.arg_begin());
731 if (DSNode *N = H.getNode()) {
732 N->setReadMarker()->setModifiedMarker();
734 const Type *ArgTy = F->getFunctionType()->getParamType(0);
735 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
736 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
739 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
740 (F->getName() == "fwrite" || F->getName() == "fread")) {
741 // fread writes the first operand, fwrite reads it. They both
742 // read/write the FILE descriptor, and merges the FILE type.
743 CallSite::arg_iterator compit = CS.arg_end();
744 DSNodeHandle H = getValueDest(**--compit);
745 if (DSNode *N = H.getNode()) {
746 N->setReadMarker()->setModifiedMarker();
747 const Type *ArgTy = F->getFunctionType()->getParamType(3);
748 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
749 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
752 H = getValueDest(**CS.arg_begin());
753 if (DSNode *N = H.getNode())
754 if (F->getName() == "fwrite")
757 N->setModifiedMarker();
759 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
760 // fgets reads and writes the memory for the file descriptor. It
761 // merges the FILE type into the descriptor, and writes to the
762 // argument. It returns the argument as well.
763 CallSite::arg_iterator AI = CS.arg_begin();
764 DSNodeHandle H = getValueDest(**AI);
765 if (DSNode *N = H.getNode())
766 N->setModifiedMarker(); // Writes buffer
767 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
770 // Reads and writes file descriptor, merge in FILE type.
771 H = getValueDest(**AI);
772 if (DSNode *N = H.getNode()) {
773 N->setReadMarker()->setModifiedMarker();
774 const Type *ArgTy = F->getFunctionType()->getParamType(2);
775 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
776 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
779 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
780 F->getName() == "fputs" || F->getName() == "putc" ||
781 F->getName() == "ftell" || F->getName() == "rewind" ||
782 F->getName() == "_IO_putc") {
783 // These functions read and write the memory for the file descriptor,
784 // which is passes as the last argument.
785 CallSite::arg_iterator compit = CS.arg_end();
786 DSNodeHandle H = getValueDest(**--compit);
787 if (DSNode *N = H.getNode()) {
788 N->setReadMarker()->setModifiedMarker();
789 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
790 const Type *ArgTy = *--compit2;
791 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
792 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
795 // Any pointer arguments are read.
796 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
798 if (isPointerType((*AI)->getType()))
799 if (DSNode *N = getValueDest(**AI).getNode())
802 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
803 F->getName() == "fsetpos") {
804 // These functions read and write the memory for the file descriptor,
805 // and read/write all other arguments.
806 DSNodeHandle H = getValueDest(**CS.arg_begin());
807 if (DSNode *N = H.getNode()) {
808 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
809 const Type *ArgTy = *--compit2;
810 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
811 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
814 // Any pointer arguments are read.
815 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
817 if (isPointerType((*AI)->getType()))
818 if (DSNode *N = getValueDest(**AI).getNode())
819 N->setReadMarker()->setModifiedMarker();
821 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
822 F->getName() == "sprintf") {
823 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
825 if (F->getName() == "fprintf") {
826 // fprintf reads and writes the FILE argument, and applies the type
828 DSNodeHandle H = getValueDest(**AI);
829 if (DSNode *N = H.getNode()) {
830 N->setModifiedMarker();
831 const Type *ArgTy = (*AI)->getType();
832 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
833 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
835 } else if (F->getName() == "sprintf") {
836 // sprintf writes the first string argument.
837 DSNodeHandle H = getValueDest(**AI++);
838 if (DSNode *N = H.getNode()) {
839 N->setModifiedMarker();
840 const Type *ArgTy = (*AI)->getType();
841 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
842 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
846 for (; AI != E; ++AI) {
847 // printf reads all pointer arguments.
848 if (isPointerType((*AI)->getType()))
849 if (DSNode *N = getValueDest(**AI).getNode())
853 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
854 F->getName() == "vsprintf") {
855 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
857 if (F->getName() == "vfprintf") {
858 // ffprintf reads and writes the FILE argument, and applies the type
860 DSNodeHandle H = getValueDest(**AI);
861 if (DSNode *N = H.getNode()) {
862 N->setModifiedMarker()->setReadMarker();
863 const Type *ArgTy = (*AI)->getType();
864 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
865 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
868 } else if (F->getName() == "vsprintf") {
869 // vsprintf writes the first string argument.
870 DSNodeHandle H = getValueDest(**AI++);
871 if (DSNode *N = H.getNode()) {
872 N->setModifiedMarker();
873 const Type *ArgTy = (*AI)->getType();
874 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
875 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
881 if (isPointerType((*AI)->getType()))
882 if (DSNode *N = getValueDest(**AI).getNode())
887 // Read the valist, and the pointed-to objects.
888 if (AI != E && isPointerType((*AI)->getType())) {
889 const DSNodeHandle &VAList = getValueDest(**AI);
890 if (DSNode *N = VAList.getNode()) {
892 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
893 VAList.getOffset(), false);
895 DSNodeHandle &VAListObjs = getLink(VAList);
896 VAListObjs.getNode()->setReadMarker();
901 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
902 F->getName() == "sscanf") {
903 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
905 if (F->getName() == "fscanf") {
906 // fscanf reads and writes the FILE argument, and applies the type
908 DSNodeHandle H = getValueDest(**AI);
909 if (DSNode *N = H.getNode()) {
911 const Type *ArgTy = (*AI)->getType();
912 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
913 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
915 } else if (F->getName() == "sscanf") {
916 // sscanf reads the first string argument.
917 DSNodeHandle H = getValueDest(**AI++);
918 if (DSNode *N = H.getNode()) {
920 const Type *ArgTy = (*AI)->getType();
921 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
922 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
926 for (; AI != E; ++AI) {
927 // scanf writes all pointer arguments.
928 if (isPointerType((*AI)->getType()))
929 if (DSNode *N = getValueDest(**AI).getNode())
930 N->setModifiedMarker();
933 } else if (F->getName() == "strtok") {
934 // strtok reads and writes the first argument, returning it. It reads
935 // its second arg. FIXME: strtok also modifies some hidden static
936 // data. Someday this might matter.
937 CallSite::arg_iterator AI = CS.arg_begin();
938 DSNodeHandle H = getValueDest(**AI++);
939 if (DSNode *N = H.getNode()) {
940 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
941 const Type *ArgTy = F->getFunctionType()->getParamType(0);
942 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
943 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
945 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
947 H = getValueDest(**AI); // Reads delimiter
948 if (DSNode *N = H.getNode()) {
950 const Type *ArgTy = F->getFunctionType()->getParamType(1);
951 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
952 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
955 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
956 F->getName() == "strstr") {
957 // These read their arguments, and return the first one
958 DSNodeHandle H = getValueDest(**CS.arg_begin());
959 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
961 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
963 if (isPointerType((*AI)->getType()))
964 if (DSNode *N = getValueDest(**AI).getNode())
967 if (DSNode *N = H.getNode())
970 } else if (F->getName() == "__assert_fail") {
971 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
973 if (isPointerType((*AI)->getType()))
974 if (DSNode *N = getValueDest(**AI).getNode())
977 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
978 // This writes its second argument, and forces it to double.
979 CallSite::arg_iterator compit = CS.arg_end();
980 DSNodeHandle H = getValueDest(**--compit);
981 if (DSNode *N = H.getNode()) {
982 N->setModifiedMarker();
983 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
986 } else if (F->getName() == "strcat" || F->getName() == "strncat") {
987 //This might be making unsafe assumptions about usage
988 //Merge return and first arg
989 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
990 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
991 if (DSNode *N = RetNH.getNode())
992 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
993 //and read second pointer
994 if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
997 } else if (F->getName() == "strcpy" || F->getName() == "strncpy") {
998 //This might be making unsafe assumptions about usage
999 //Merge return and first arg
1000 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
1001 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
1002 if (DSNode *N = RetNH.getNode())
1003 N->setHeapNodeMarker()->setModifiedMarker();
1004 //and read second pointer
1005 if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
1012 void GraphBuilder::visitCallSite(CallSite CS) {
1013 Value *Callee = CS.getCalledValue();
1015 // Special case handling of certain libc allocation functions here.
1016 if (Function *F = dyn_cast<Function>(Callee))
1017 if (F->isExternal())
1018 if (F->isIntrinsic() && visitIntrinsic(CS, F))
1021 // Determine if the called function is one of the specified heap
1022 // allocation functions
1023 if (AllocList.end() != std::find(AllocList.begin(), AllocList.end(), F->getName())) {
1024 setDestTo(*CS.getInstruction(),
1025 createNode()->setHeapNodeMarker()->setModifiedMarker());
1029 // Determine if the called function is one of the specified heap
1031 if (FreeList.end() != std::find(FreeList.begin(), FreeList.end(), F->getName())) {
1032 // Mark that the node is written to...
1033 if (DSNode *N = getValueDest(*(CS.getArgument(0))).getNode())
1034 N->setModifiedMarker()->setHeapNodeMarker();
1037 if (visitExternal(CS,F))
1039 // Unknown function, warn if it returns a pointer type or takes a
1040 // pointer argument.
1041 bool Warn = isPointerType(CS.getInstruction()->getType());
1043 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1045 if (isPointerType((*I)->getType())) {
1050 DOUT << "WARNING: Call to unknown external function '"
1051 << F->getName() << "' will cause pessimistic results!\n";
1055 // Set up the return value...
1056 DSNodeHandle RetVal;
1057 Instruction *I = CS.getInstruction();
1058 if (isPointerType(I->getType()))
1059 RetVal = getValueDest(*I);
1061 DSNode *CalleeNode = 0;
1062 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
1063 CalleeNode = getValueDest(*Callee).getNode();
1064 if (CalleeNode == 0) {
1065 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
1066 return; // Calling a null pointer?
1070 std::vector<DSNodeHandle> Args;
1071 Args.reserve(CS.arg_end()-CS.arg_begin());
1073 // Calculate the arguments vector...
1074 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1075 if (isPointerType((*I)->getType()))
1076 Args.push_back(getValueDest(**I));
1078 // Add a new function call entry...
1080 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
1082 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
1086 void GraphBuilder::visitFreeInst(FreeInst &FI) {
1087 // Mark that the node is written to...
1088 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
1089 N->setModifiedMarker()->setHeapNodeMarker();
1093 void GraphBuilder::visitCastInst(CastInst &CI) {
1094 // Pointers can only be cast with BitCast so check that the instruction
1095 // is a BitConvert. If not, its guaranteed not to involve any pointers so
1096 // we don't do anything.
1097 switch (CI.getOpcode()) {
1099 case Instruction::BitCast:
1100 case Instruction::IntToPtr:
1101 if (isPointerType(CI.getType()))
1102 if (isPointerType(CI.getOperand(0)->getType())) {
1103 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1104 if (Ptr.getNode() == 0) return;
1105 // Cast one pointer to the other, just act like a copy instruction
1108 // Cast something (floating point, small integer) to a pointer. We
1109 // need to track the fact that the node points to SOMETHING, just
1110 // something we don't know about. Make an "Unknown" node.
1111 setDestTo(CI, createNode()->setUnknownNodeMarker());
1118 // visitInstruction - For all other instruction types, if we have any arguments
1119 // that are of pointer type, make them have unknown composition bits, and merge
1120 // the nodes together.
1121 void GraphBuilder::visitInstruction(Instruction &Inst) {
1122 DSNodeHandle CurNode;
1123 if (isPointerType(Inst.getType()))
1124 CurNode = getValueDest(Inst);
1125 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1126 if (isPointerType((*I)->getType()))
1127 CurNode.mergeWith(getValueDest(**I));
1129 if (DSNode *N = CurNode.getNode())
1130 N->setUnknownNodeMarker();
1135 //===----------------------------------------------------------------------===//
1136 // LocalDataStructures Implementation
1137 //===----------------------------------------------------------------------===//
1139 // MergeConstantInitIntoNode - Merge the specified constant into the node
1140 // pointed to by NH.
1141 void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1142 // Ensure a type-record exists...
1143 DSNode *NHN = NH.getNode();
1144 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
1146 if (C->getType()->isFirstClassType()) {
1147 if (isPointerType(C->getType()))
1148 // Avoid adding edges from null, or processing non-"pointer" stores
1149 NH.addEdgeTo(getValueDest(*C));
1153 const TargetData &TD = NH.getNode()->getTargetData();
1155 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1156 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1157 // We don't currently do any indexing for arrays...
1158 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1159 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1160 const StructLayout *SL = TD.getStructLayout(CS->getType());
1161 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1162 DSNode *NHN = NH.getNode();
1163 //Some programmers think ending a structure with a [0 x sbyte] is cute
1164 if (SL->MemberOffsets[i] < SL->StructSize) {
1165 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1166 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1167 } else if (SL->MemberOffsets[i] == SL->StructSize) {
1168 DOUT << "Zero size element at end of struct\n";
1169 NHN->foldNodeCompletely();
1171 assert(0 && "type was smaller than offsets of of struct layout indicate");
1174 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
1177 assert(0 && "Unknown constant type!");
1181 void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1182 assert(!GV->isExternal() && "Cannot merge in external global!");
1183 // Get a node handle to the global node and merge the initializer into it.
1184 DSNodeHandle NH = getValueDest(*GV);
1185 MergeConstantInitIntoNode(NH, GV->getInitializer());
1189 /// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1190 /// contains multiple globals, DSA will never, ever, be able to tell the globals
1191 /// apart. Instead of maintaining this information in all of the graphs
1192 /// throughout the entire program, store only a single global (the "leader") in
1193 /// the graphs, and build equivalence classes for the rest of the globals.
1194 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1195 DSScalarMap &SM = GG.getScalarMap();
1196 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1197 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1199 if (I->getGlobalsList().size() <= 1) continue;
1201 // First, build up the equivalence set for this block of globals.
1202 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1203 GlobalValue *First = GVs[0];
1204 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1205 GlobalECs.unionSets(First, GVs[i]);
1207 // Next, get the leader element.
1208 assert(First == GlobalECs.getLeaderValue(First) &&
1209 "First did not end up being the leader?");
1211 // Next, remove all globals from the scalar map that are not the leader.
1212 assert(GVs[0] == First && "First had to be at the front!");
1213 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1214 ECGlobals.insert(GVs[i]);
1215 SM.erase(SM.find(GVs[i]));
1218 // Finally, change the global node to only contain the leader.
1220 I->addGlobal(First);
1223 DEBUG(GG.AssertGraphOK());
1226 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1227 /// really just equivalent to some other globals, remove the globals from the
1228 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
1229 static void EliminateUsesOfECGlobals(DSGraph &G,
1230 const std::set<GlobalValue*> &ECGlobals) {
1231 DSScalarMap &SM = G.getScalarMap();
1232 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1234 bool MadeChange = false;
1235 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1237 GlobalValue *GV = *GI++;
1238 if (!ECGlobals.count(GV)) continue;
1240 const DSNodeHandle &GVNH = SM[GV];
1241 assert(!GVNH.isNull() && "Global has null NH!?");
1243 // Okay, this global is in some equivalence class. Start by finding the
1244 // leader of the class.
1245 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1247 // If the leader isn't already in the graph, insert it into the node
1248 // corresponding to GV.
1249 if (!SM.global_count(Leader)) {
1250 GVNH.getNode()->addGlobal(Leader);
1253 // Otherwise, the leader is in the graph, make sure the nodes are the
1254 // merged in the specified graph.
1255 const DSNodeHandle &LNH = SM[Leader];
1256 if (LNH.getNode() != GVNH.getNode())
1257 LNH.mergeWith(GVNH);
1260 // Next step, remove the global from the DSNode.
1261 GVNH.getNode()->removeGlobal(GV);
1263 // Finally, remove the global from the ScalarMap.
1268 DEBUG(if(MadeChange) G.AssertGraphOK());
1271 bool LocalDataStructures::runOnModule(Module &M) {
1272 const TargetData &TD = getAnalysis<TargetData>();
1274 // First step, build the globals graph.
1275 GlobalsGraph = new DSGraph(GlobalECs, TD);
1277 GraphBuilder GGB(*GlobalsGraph);
1279 // Add initializers for all of the globals to the globals graph.
1280 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1282 if (!I->isExternal())
1283 GGB.mergeInGlobalInitializer(I);
1286 // Next step, iterate through the nodes in the globals graph, unioning
1287 // together the globals into equivalence classes.
1288 std::set<GlobalValue*> ECGlobals;
1289 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1290 DOUT << "Eliminating " << ECGlobals.size() << " EC Globals!\n";
1293 // Calculate all of the graphs...
1294 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1295 if (!I->isExternal())
1296 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1299 GlobalsGraph->removeTriviallyDeadNodes();
1300 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
1302 // Now that we've computed all of the graphs, and merged all of the info into
1303 // the globals graph, see if we have further constrained the globals in the
1304 // program if so, update GlobalECs and remove the extraneous globals from the
1306 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1307 if (!ECGlobals.empty()) {
1308 DOUT << "Eliminating " << ECGlobals.size() << " EC Globals!\n";
1309 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1310 E = DSInfo.end(); I != E; ++I)
1311 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1317 // releaseMemory - If the pass pipeline is done with this pass, we can release
1318 // our memory... here...
1320 void LocalDataStructures::releaseMemory() {
1321 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1322 E = DSInfo.end(); I != E; ++I) {
1323 I->second->getReturnNodes().erase(I->first);
1324 if (I->second->getReturnNodes().empty())
1328 // Empty map so next time memory is released, data structures are not
1331 delete GlobalsGraph;