dbfbea3981d9e961327fbf244db8fdb3645635b9
[oota-llvm.git] / lib / Analysis / DataStructure / Local.cpp
1 //===- Local.cpp - Compute a local data structure graph for a function ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Compute the local version of the data structure graph for a function.  The
11 // external interface to this file is the DSGraph constructor.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
27 #include <iostream>
28
29 // FIXME: This should eventually be a FunctionPass that is automatically
30 // aggregated into a Pass.
31 //
32 #include "llvm/Module.h"
33
34 using namespace llvm;
35
36 static RegisterPass<LocalDataStructures>
37 X("datastructure", "Local Data Structure Analysis");
38
39 static cl::opt<bool>
40 TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
41          cl::desc("If this is set, track integers as potential pointers"));
42
43 static cl::list<std::string>
44 AllocList("dsa-alloc-list",
45           cl::value_desc("list"),
46           cl::desc("List of functions that allocate memory from the heap"),
47           cl::CommaSeparated, cl::Hidden);
48
49 static cl::list<std::string>
50 FreeList("dsa-free-list",
51           cl::value_desc("list"),
52           cl::desc("List of functions that free memory from the heap"),
53           cl::CommaSeparated, cl::Hidden);
54
55 namespace llvm {
56 namespace DS {
57   // isPointerType - Return true if this type is big enough to hold a pointer.
58   bool isPointerType(const Type *Ty) {
59     if (isa<PointerType>(Ty))
60       return true;
61     else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
62       return Ty->getPrimitiveSize() >= PointerSize;
63     return false;
64   }
65 }}
66
67 using namespace DS;
68
69 namespace {
70   cl::opt<bool>
71   DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
72                        cl::desc("Disable direct call optimization in "
73                                 "DSGraph construction"));
74   cl::opt<bool>
75   DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
76                           cl::desc("Disable field sensitivity in DSGraphs"));
77
78   //===--------------------------------------------------------------------===//
79   //  GraphBuilder Class
80   //===--------------------------------------------------------------------===//
81   //
82   /// This class is the builder class that constructs the local data structure
83   /// graph by performing a single pass over the function in question.
84   ///
85   class GraphBuilder : InstVisitor<GraphBuilder> {
86     DSGraph &G;
87     DSNodeHandle *RetNode;               // Node that gets returned...
88     DSScalarMap &ScalarMap;
89     std::list<DSCallSite> *FunctionCalls;
90
91   public:
92     GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
93                  std::list<DSCallSite> &fc)
94       : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
95         FunctionCalls(&fc) {
96
97       // Create scalar nodes for all pointer arguments...
98       for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end();
99            I != E; ++I)
100         if (isPointerType(I->getType()))
101           getValueDest(*I);
102
103       visit(f);  // Single pass over the function
104     }
105
106     // GraphBuilder ctor for working on the globals graph
107     GraphBuilder(DSGraph &g)
108       : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
109     }
110
111     void mergeInGlobalInitializer(GlobalVariable *GV);
112
113   private:
114     // Visitor functions, used to handle each instruction type we encounter...
115     friend class InstVisitor<GraphBuilder>;
116     void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
117     void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
118     void handleAlloc(AllocationInst &AI, bool isHeap);
119
120     void visitPHINode(PHINode &PN);
121     void visitSelectInst(SelectInst &SI);
122
123     void visitGetElementPtrInst(User &GEP);
124     void visitReturnInst(ReturnInst &RI);
125     void visitLoadInst(LoadInst &LI);
126     void visitStoreInst(StoreInst &SI);
127     void visitCallInst(CallInst &CI);
128     void visitInvokeInst(InvokeInst &II);
129     void visitSetCondInst(SetCondInst &SCI);
130     void visitFreeInst(FreeInst &FI);
131     void visitCastInst(CastInst &CI);
132     void visitInstruction(Instruction &I);
133
134     void visitCallSite(CallSite CS);
135     void visitVAArgInst(VAArgInst   &I);
136
137     void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
138   private:
139     // Helper functions used to implement the visitation functions...
140
141     /// createNode - Create a new DSNode, ensuring that it is properly added to
142     /// the graph.
143     ///
144     DSNode *createNode(const Type *Ty = 0) {
145       DSNode *N = new DSNode(Ty, &G);   // Create the node
146       if (DisableFieldSensitivity) {
147         // Create node handle referring to the old node so that it is
148         // immediately removed from the graph when the node handle is destroyed.
149         DSNodeHandle OldNNH = N;
150         N->foldNodeCompletely();
151         if (DSNode *FN = N->getForwardNode())
152           N = FN;
153       }
154       return N;
155     }
156
157     /// setDestTo - Set the ScalarMap entry for the specified value to point to
158     /// the specified destination.  If the Value already points to a node, make
159     /// sure to merge the two destinations together.
160     ///
161     void setDestTo(Value &V, const DSNodeHandle &NH);
162
163     /// getValueDest - Return the DSNode that the actual value points to.
164     ///
165     DSNodeHandle getValueDest(Value &V);
166
167     /// getLink - This method is used to return the specified link in the
168     /// specified node if one exists.  If a link does not already exist (it's
169     /// null), then we create a new node, link it, then return it.
170     ///
171     DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
172   };
173 }
174
175 using namespace DS;
176
177 //===----------------------------------------------------------------------===//
178 // DSGraph constructor - Simply use the GraphBuilder to construct the local
179 // graph.
180 DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
181                  Function &F, DSGraph *GG)
182   : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
183   PrintAuxCalls = false;
184
185   DEBUG(std::cerr << "  [Loc] Calculating graph for: " << F.getName() << "\n");
186
187   // Use the graph builder to construct the local version of the graph
188   GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
189 #ifndef NDEBUG
190   Timer::addPeakMemoryMeasurement();
191 #endif
192
193   // If there are any constant globals referenced in this function, merge their
194   // initializers into the local graph from the globals graph.
195   if (ScalarMap.global_begin() != ScalarMap.global_end()) {
196     ReachabilityCloner RC(*this, *GG, 0);
197
198     for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
199          I != ScalarMap.global_end(); ++I)
200       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
201         if (!GV->isExternal() && GV->isConstant())
202           RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
203   }
204
205   markIncompleteNodes(DSGraph::MarkFormalArgs);
206
207   // Remove any nodes made dead due to merging...
208   removeDeadNodes(DSGraph::KeepUnreachableGlobals);
209 }
210
211
212 //===----------------------------------------------------------------------===//
213 // Helper method implementations...
214 //
215
216 /// getValueDest - Return the DSNode that the actual value points to.
217 ///
218 DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
219   Value *V = &Val;
220   if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
221     return 0;  // Null doesn't point to anything, don't add to ScalarMap!
222
223   DSNodeHandle &NH = ScalarMap[V];
224   if (!NH.isNull())
225     return NH;     // Already have a node?  Just return it...
226
227   // Otherwise we need to create a new node to point to.
228   // Check first for constant expressions that must be traversed to
229   // extract the actual value.
230   DSNode* N;
231   if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
232     // Create a new global node for this global variable.
233     N = createNode(GV->getType()->getElementType());
234     N->addGlobal(GV);
235   } else if (Constant *C = dyn_cast<Constant>(V)) {
236     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
237       if (CE->getOpcode() == Instruction::Cast) {
238         if (isa<PointerType>(CE->getOperand(0)->getType()))
239           NH = getValueDest(*CE->getOperand(0));
240         else
241           NH = createNode()->setUnknownNodeMarker();
242       } else if (CE->getOpcode() == Instruction::GetElementPtr) {
243         visitGetElementPtrInst(*CE);
244         DSScalarMap::iterator I = ScalarMap.find(CE);
245         assert(I != ScalarMap.end() && "GEP didn't get processed right?");
246         NH = I->second;
247       } else {
248         // This returns a conservative unknown node for any unhandled ConstExpr
249         return NH = createNode()->setUnknownNodeMarker();
250       }
251       if (NH.isNull()) {  // (getelementptr null, X) returns null
252         ScalarMap.erase(V);
253         return 0;
254       }
255       return NH;
256     } else if (isa<UndefValue>(C)) {
257       ScalarMap.erase(V);
258       return 0;
259     } else {
260       assert(0 && "Unknown constant type!");
261     }
262     N = createNode(); // just create a shadow node
263   } else {
264     // Otherwise just create a shadow node
265     N = createNode();
266   }
267
268   NH.setTo(N, 0);      // Remember that we are pointing to it...
269   return NH;
270 }
271
272
273 /// getLink - This method is used to return the specified link in the
274 /// specified node if one exists.  If a link does not already exist (it's
275 /// null), then we create a new node, link it, then return it.  We must
276 /// specify the type of the Node field we are accessing so that we know what
277 /// type should be linked to if we need to create a new node.
278 ///
279 DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
280   DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
281   DSNodeHandle &Link = Node.getLink(LinkNo);
282   if (Link.isNull()) {
283     // If the link hasn't been created yet, make and return a new shadow node
284     Link = createNode();
285   }
286   return Link;
287 }
288
289
290 /// setDestTo - Set the ScalarMap entry for the specified value to point to the
291 /// specified destination.  If the Value already points to a node, make sure to
292 /// merge the two destinations together.
293 ///
294 void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
295   ScalarMap[&V].mergeWith(NH);
296 }
297
298
299 //===----------------------------------------------------------------------===//
300 // Specific instruction type handler implementations...
301 //
302
303 /// Alloca & Malloc instruction implementation - Simply create a new memory
304 /// object, pointing the scalar to it.
305 ///
306 void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
307   DSNode *N = createNode();
308   if (isHeap)
309     N->setHeapNodeMarker();
310   else
311     N->setAllocaNodeMarker();
312   setDestTo(AI, N);
313 }
314
315 // PHINode - Make the scalar for the PHI node point to all of the things the
316 // incoming values point to... which effectively causes them to be merged.
317 //
318 void GraphBuilder::visitPHINode(PHINode &PN) {
319   if (!isPointerType(PN.getType())) return; // Only pointer PHIs
320
321   DSNodeHandle &PNDest = ScalarMap[&PN];
322   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
323     PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
324 }
325
326 void GraphBuilder::visitSelectInst(SelectInst &SI) {
327   if (!isPointerType(SI.getType())) return; // Only pointer Selects
328
329   DSNodeHandle &Dest = ScalarMap[&SI];
330   Dest.mergeWith(getValueDest(*SI.getOperand(1)));
331   Dest.mergeWith(getValueDest(*SI.getOperand(2)));
332 }
333
334 void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
335   if (!isPointerType(SCI.getOperand(0)->getType()) ||
336       isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
337   ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
338 }
339
340
341 void GraphBuilder::visitGetElementPtrInst(User &GEP) {
342   DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
343   if (Value.isNull())
344     Value = createNode();
345
346   // As a special case, if all of the index operands of GEP are constant zeros,
347   // handle this just like we handle casts (ie, don't do much).
348   bool AllZeros = true;
349   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
350     if (GEP.getOperand(i) !=
351            Constant::getNullValue(GEP.getOperand(i)->getType())) {
352       AllZeros = false;
353       break;
354     }
355
356   // If all of the indices are zero, the result points to the operand without
357   // applying the type.
358   if (AllZeros || (!Value.isNull() &&
359                    Value.getNode()->isNodeCompletelyFolded())) {
360     setDestTo(GEP, Value);
361     return;
362   }
363
364
365   const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
366   const Type *CurTy = PTy->getElementType();
367
368   if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
369     // If the node had to be folded... exit quickly
370     setDestTo(GEP, Value);  // GEP result points to folded node
371     return;
372   }
373
374   const TargetData &TD = Value.getNode()->getTargetData();
375
376 #if 0
377   // Handle the pointer index specially...
378   if (GEP.getNumOperands() > 1 &&
379       (!isa<Constant>(GEP.getOperand(1)) ||
380        !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
381
382     // If we already know this is an array being accessed, don't do anything...
383     if (!TopTypeRec.isArray) {
384       TopTypeRec.isArray = true;
385
386       // If we are treating some inner field pointer as an array, fold the node
387       // up because we cannot handle it right.  This can come because of
388       // something like this:  &((&Pt->X)[1]) == &Pt->Y
389       //
390       if (Value.getOffset()) {
391         // Value is now the pointer we want to GEP to be...
392         Value.getNode()->foldNodeCompletely();
393         setDestTo(GEP, Value);  // GEP result points to folded node
394         return;
395       } else {
396         // This is a pointer to the first byte of the node.  Make sure that we
397         // are pointing to the outter most type in the node.
398         // FIXME: We need to check one more case here...
399       }
400     }
401   }
402 #endif
403
404   // All of these subscripts are indexing INTO the elements we have...
405   unsigned Offset = 0;
406   for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
407        I != E; ++I)
408     if (const StructType *STy = dyn_cast<StructType>(*I)) {
409       unsigned FieldNo =
410            (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
411       Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
412     } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
413       if (!isa<Constant>(I.getOperand()) ||
414           !cast<Constant>(I.getOperand())->isNullValue())
415         Value.getNode()->setArrayMarker();
416     }
417
418
419 #if 0
420     if (const SequentialType *STy = cast<SequentialType>(*I)) {
421       CurTy = STy->getElementType();
422       if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
423         Offset += CS->getValue()*TD.getTypeSize(CurTy);
424       } else {
425         // Variable index into a node.  We must merge all of the elements of the
426         // sequential type here.
427         if (isa<PointerType>(STy))
428           std::cerr << "Pointer indexing not handled yet!\n";
429         else {
430           const ArrayType *ATy = cast<ArrayType>(STy);
431           unsigned ElSize = TD.getTypeSize(CurTy);
432           DSNode *N = Value.getNode();
433           assert(N && "Value must have a node!");
434           unsigned RawOffset = Offset+Value.getOffset();
435
436           // Loop over all of the elements of the array, merging them into the
437           // zeroth element.
438           for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
439             // Merge all of the byte components of this array element
440             for (unsigned j = 0; j != ElSize; ++j)
441               N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
442         }
443       }
444     }
445 #endif
446
447   // Add in the offset calculated...
448   Value.setOffset(Value.getOffset()+Offset);
449
450   // Check the offset
451   DSNode *N = Value.getNode();
452   if (N &&
453       !N->isNodeCompletelyFolded() &&
454       (N->getSize() != 0 || Offset != 0) &&
455       !N->isForwarding()) {
456     if ((Offset >= N->getSize()) || int(Offset) < 0) {
457       // Accessing offsets out of node size range
458       // This is seen in the "magic" struct in named (from bind), where the
459       // fourth field is an array of length 0, presumably used to create struct
460       // instances of different sizes
461
462       // Collapse the node since its size is now variable
463       N->foldNodeCompletely();
464     }
465   }
466   
467   // Value is now the pointer we want to GEP to be...  
468   setDestTo(GEP, Value);
469 }
470
471 void GraphBuilder::visitLoadInst(LoadInst &LI) {
472   DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
473   if (Ptr.isNull())
474     Ptr = createNode();
475
476   // Make that the node is read from...
477   Ptr.getNode()->setReadMarker();
478
479   // Ensure a typerecord exists...
480   Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
481
482   if (isPointerType(LI.getType()))
483     setDestTo(LI, getLink(Ptr));
484 }
485
486 void GraphBuilder::visitStoreInst(StoreInst &SI) {
487   const Type *StoredTy = SI.getOperand(0)->getType();
488   DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
489   if (Dest.isNull()) return;
490
491   // Mark that the node is written to...
492   Dest.getNode()->setModifiedMarker();
493
494   // Ensure a type-record exists...
495   Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
496
497   // Avoid adding edges from null, or processing non-"pointer" stores
498   if (isPointerType(StoredTy))
499     Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
500 }
501
502 void GraphBuilder::visitReturnInst(ReturnInst &RI) {
503   if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
504     RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
505 }
506
507 void GraphBuilder::visitVAArgInst(VAArgInst &I) {
508   //FIXME: also updates the argument
509   DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
510   if (Ptr.isNull()) return;
511
512   // Make that the node is read from.
513   Ptr.getNode()->setReadMarker();
514
515   // Ensure a type record exists.
516   DSNode *PtrN = Ptr.getNode();
517   PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
518
519   if (isPointerType(I.getType()))
520     setDestTo(I, getLink(Ptr));
521 }
522
523
524 void GraphBuilder::visitCallInst(CallInst &CI) {
525   visitCallSite(&CI);
526 }
527
528 void GraphBuilder::visitInvokeInst(InvokeInst &II) {
529   visitCallSite(&II);
530 }
531
532 void GraphBuilder::visitCallSite(CallSite CS) {
533   Value *Callee = CS.getCalledValue();
534
535   // Special case handling of certain libc allocation functions here.
536   if (Function *F = dyn_cast<Function>(Callee))
537     if (F->isExternal())
538       switch (F->getIntrinsicID()) {
539       case Intrinsic::vastart:
540         getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
541         return;
542       case Intrinsic::vacopy:
543         getValueDest(*CS.getInstruction()).
544           mergeWith(getValueDest(**(CS.arg_begin())));
545         return;
546       case Intrinsic::vaend:
547       case Intrinsic::dbg_func_start:
548       case Intrinsic::dbg_region_end:
549       case Intrinsic::dbg_stoppoint:
550         return;  // noop
551       case Intrinsic::memcpy_i32: 
552       case Intrinsic::memcpy_i64:
553       case Intrinsic::memmove_i32:
554       case Intrinsic::memmove_i64: {
555         // Merge the first & second arguments, and mark the memory read and
556         // modified.
557         DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
558         RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
559         if (DSNode *N = RetNH.getNode())
560           N->setModifiedMarker()->setReadMarker();
561         return;
562       }
563       case Intrinsic::memset_i32:
564       case Intrinsic::memset_i64:
565         // Mark the memory modified.
566         if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
567           N->setModifiedMarker();
568         return;
569       default:
570         // Determine if the called function is one of the specified heap
571         // allocation functions
572         for (cl::list<std::string>::iterator AllocFunc = AllocList.begin(),
573              LastAllocFunc = AllocList.end();
574              AllocFunc != LastAllocFunc;
575              ++AllocFunc) {
576           if (F->getName() == *(AllocFunc)) {
577             setDestTo(*CS.getInstruction(),
578                       createNode()->setHeapNodeMarker()->setModifiedMarker());
579             return;
580           }
581         }
582
583         // Determine if the called function is one of the specified heap
584         // free functions
585         for (cl::list<std::string>::iterator FreeFunc = FreeList.begin(),
586              LastFreeFunc = FreeList.end();
587              FreeFunc != LastFreeFunc;
588              ++FreeFunc) {
589           if (F->getName() == *(FreeFunc)) {
590             // Mark that the node is written to...
591             if (DSNode *N = getValueDest(*(CS.getArgument(0))).getNode())
592               N->setModifiedMarker()->setHeapNodeMarker();
593             return;
594           }
595         }
596
597         //gets select localtime ioctl
598
599         if ((F->isExternal() && F->getName() == "calloc") 
600             || F->getName() == "posix_memalign"
601             || F->getName() == "memalign" || F->getName() == "valloc") {
602           setDestTo(*CS.getInstruction(),
603                     createNode()->setHeapNodeMarker()->setModifiedMarker());
604           return;
605         } else if (F->getName() == "realloc") {
606           DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
607           if (CS.arg_begin() != CS.arg_end())
608             RetNH.mergeWith(getValueDest(**CS.arg_begin()));
609           if (DSNode *N = RetNH.getNode())
610             N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
611           return;
612         } else if (F->getName() == "memmove") {
613           // Merge the first & second arguments, and mark the memory read and
614           // modified.
615           DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
616           RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
617           if (DSNode *N = RetNH.getNode())
618             N->setModifiedMarker()->setReadMarker();
619           return;
620         } else if (F->getName() == "free") {
621           // Mark that the node is written to...
622           if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
623             N->setModifiedMarker()->setHeapNodeMarker();
624         } else if (F->getName() == "atoi" || F->getName() == "atof" ||
625                    F->getName() == "atol" || F->getName() == "atoll" ||
626                    F->getName() == "remove" || F->getName() == "unlink" ||
627                    F->getName() == "rename" || F->getName() == "memcmp" ||
628                    F->getName() == "strcmp" || F->getName() == "strncmp" ||
629                    F->getName() == "execl" || F->getName() == "execlp" ||
630                    F->getName() == "execle" || F->getName() == "execv" ||
631                    F->getName() == "execvp" || F->getName() == "chmod" ||
632                    F->getName() == "puts" || F->getName() == "write" ||
633                    F->getName() == "open" || F->getName() == "create" ||
634                    F->getName() == "truncate" || F->getName() == "chdir" ||
635                    F->getName() == "mkdir" || F->getName() == "rmdir" ||
636                    F->getName() == "strlen") {
637           // These functions read all of their pointer operands.
638           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
639                AI != E; ++AI) {
640             if (isPointerType((*AI)->getType()))
641               if (DSNode *N = getValueDest(**AI).getNode())
642                 N->setReadMarker();
643           }
644           return;
645         } else if (F->getName() == "memchr") {
646           DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
647           DSNodeHandle Result = getValueDest(*CS.getInstruction());
648           RetNH.mergeWith(Result);
649           if (DSNode *N = RetNH.getNode())
650             N->setReadMarker();
651           return;
652         } else if (F->getName() == "read" || F->getName() == "pipe" ||
653                    F->getName() == "wait" || F->getName() == "time" ||
654                    F->getName() == "getrusage") {
655           // These functions write all of their pointer operands.
656           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
657                AI != E; ++AI) {
658             if (isPointerType((*AI)->getType()))
659               if (DSNode *N = getValueDest(**AI).getNode())
660                 N->setModifiedMarker();
661           }
662           return;
663         } else if (F->getName() == "stat" || F->getName() == "fstat" ||
664                    F->getName() == "lstat") {
665           // These functions read their first operand if its a pointer.
666           CallSite::arg_iterator AI = CS.arg_begin();
667           if (isPointerType((*AI)->getType())) {
668             DSNodeHandle Path = getValueDest(**AI);
669             if (DSNode *N = Path.getNode()) N->setReadMarker();
670           }
671
672           // Then they write into the stat buffer.
673           DSNodeHandle StatBuf = getValueDest(**++AI);
674           if (DSNode *N = StatBuf.getNode()) {
675             N->setModifiedMarker();
676             const Type *StatTy = F->getFunctionType()->getParamType(1);
677             if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
678               N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
679           }
680           return;
681         } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
682                    F->getName() == "strtold") {
683           // These functions read the first pointer
684           if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
685             Str->setReadMarker();
686             // If the second parameter is passed, it will point to the first
687             // argument node.
688             const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
689             if (DSNode *End = EndPtrNH.getNode()) {
690               End->mergeTypeInfo(PointerType::get(Type::SByteTy),
691                                  EndPtrNH.getOffset(), false);
692               End->setModifiedMarker();
693               DSNodeHandle &Link = getLink(EndPtrNH);
694               Link.mergeWith(getValueDest(**CS.arg_begin()));
695             }
696           }
697           return;
698         } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
699                    F->getName() == "freopen") {
700           // These functions read all of their pointer operands.
701           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
702                AI != E; ++AI)
703             if (isPointerType((*AI)->getType()))
704               if (DSNode *N = getValueDest(**AI).getNode())
705                 N->setReadMarker();
706
707           // fopen allocates in an unknown way and writes to the file
708           // descriptor.  Also, merge the allocated type into the node.
709           DSNodeHandle Result = getValueDest(*CS.getInstruction());
710           if (DSNode *N = Result.getNode()) {
711             N->setModifiedMarker()->setUnknownNodeMarker();
712             const Type *RetTy = F->getFunctionType()->getReturnType();
713             if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
714               N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
715           }
716
717           // If this is freopen, merge the file descriptor passed in with the
718           // result.
719           if (F->getName() == "freopen") {
720             // ICC doesn't handle getting the iterator, decrementing and
721             // dereferencing it in one operation without error. Do it in 2 steps
722             CallSite::arg_iterator compit = CS.arg_end();
723             Result.mergeWith(getValueDest(**--compit));
724           }
725           return;
726         } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
727           // fclose reads and deallocates the memory in an unknown way for the
728           // file descriptor.  It merges the FILE type into the descriptor.
729           DSNodeHandle H = getValueDest(**CS.arg_begin());
730           if (DSNode *N = H.getNode()) {
731             N->setReadMarker()->setUnknownNodeMarker();
732             const Type *ArgTy = F->getFunctionType()->getParamType(0);
733             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
734               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
735           }
736           return;
737         } else if (CS.arg_end()-CS.arg_begin() == 1 &&
738                    (F->getName() == "fflush" || F->getName() == "feof" ||
739                     F->getName() == "fileno" || F->getName() == "clearerr" ||
740                     F->getName() == "rewind" || F->getName() == "ftell" ||
741                     F->getName() == "ferror" || F->getName() == "fgetc" ||
742                     F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
743           // fflush reads and writes the memory for the file descriptor.  It
744           // merges the FILE type into the descriptor.
745           DSNodeHandle H = getValueDest(**CS.arg_begin());
746           if (DSNode *N = H.getNode()) {
747             N->setReadMarker()->setModifiedMarker();
748
749             const Type *ArgTy = F->getFunctionType()->getParamType(0);
750             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
751               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
752           }
753           return;
754         } else if (CS.arg_end()-CS.arg_begin() == 4 &&
755                    (F->getName() == "fwrite" || F->getName() == "fread")) {
756           // fread writes the first operand, fwrite reads it.  They both
757           // read/write the FILE descriptor, and merges the FILE type.
758           CallSite::arg_iterator compit = CS.arg_end();
759           DSNodeHandle H = getValueDest(**--compit);
760           if (DSNode *N = H.getNode()) {
761             N->setReadMarker()->setModifiedMarker();
762             const Type *ArgTy = F->getFunctionType()->getParamType(3);
763             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
764               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
765           }
766
767           H = getValueDest(**CS.arg_begin());
768           if (DSNode *N = H.getNode())
769             if (F->getName() == "fwrite")
770               N->setReadMarker();
771             else
772               N->setModifiedMarker();
773           return;
774         } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
775           // fgets reads and writes the memory for the file descriptor.  It
776           // merges the FILE type into the descriptor, and writes to the
777           // argument.  It returns the argument as well.
778           CallSite::arg_iterator AI = CS.arg_begin();
779           DSNodeHandle H = getValueDest(**AI);
780           if (DSNode *N = H.getNode())
781             N->setModifiedMarker();                        // Writes buffer
782           H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
783           ++AI; ++AI;
784
785           // Reads and writes file descriptor, merge in FILE type.
786           H = getValueDest(**AI);
787           if (DSNode *N = H.getNode()) {
788             N->setReadMarker()->setModifiedMarker();
789             const Type *ArgTy = F->getFunctionType()->getParamType(2);
790             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
791               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
792           }
793           return;
794         } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
795                    F->getName() == "fputs" || F->getName() == "putc" ||
796                    F->getName() == "ftell" || F->getName() == "rewind" ||
797                    F->getName() == "_IO_putc") {
798           // These functions read and write the memory for the file descriptor,
799           // which is passes as the last argument.
800           CallSite::arg_iterator compit = CS.arg_end();
801           DSNodeHandle H = getValueDest(**--compit);
802           if (DSNode *N = H.getNode()) {
803             N->setReadMarker()->setModifiedMarker();
804             FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
805             const Type *ArgTy = *--compit2;
806             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
807               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
808           }
809
810           // Any pointer arguments are read.
811           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
812                AI != E; ++AI)
813             if (isPointerType((*AI)->getType()))
814               if (DSNode *N = getValueDest(**AI).getNode())
815                 N->setReadMarker();
816           return;
817         } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
818                    F->getName() == "fsetpos") {
819           // These functions read and write the memory for the file descriptor,
820           // and read/write all other arguments.
821           DSNodeHandle H = getValueDest(**CS.arg_begin());
822           if (DSNode *N = H.getNode()) {
823             FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
824             const Type *ArgTy = *--compit2;
825             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
826               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
827           }
828
829           // Any pointer arguments are read.
830           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
831                AI != E; ++AI)
832             if (isPointerType((*AI)->getType()))
833               if (DSNode *N = getValueDest(**AI).getNode())
834                 N->setReadMarker()->setModifiedMarker();
835           return;
836         } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
837                    F->getName() == "sprintf") {
838           CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
839
840           if (F->getName() == "fprintf") {
841             // fprintf reads and writes the FILE argument, and applies the type
842             // to it.
843             DSNodeHandle H = getValueDest(**AI);
844             if (DSNode *N = H.getNode()) {
845               N->setModifiedMarker();
846               const Type *ArgTy = (*AI)->getType();
847               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
848                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
849             }
850           } else if (F->getName() == "sprintf") {
851             // sprintf writes the first string argument.
852             DSNodeHandle H = getValueDest(**AI++);
853             if (DSNode *N = H.getNode()) {
854               N->setModifiedMarker();
855               const Type *ArgTy = (*AI)->getType();
856               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
857                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
858             }
859           }
860
861           for (; AI != E; ++AI) {
862             // printf reads all pointer arguments.
863             if (isPointerType((*AI)->getType()))
864               if (DSNode *N = getValueDest(**AI).getNode())
865                 N->setReadMarker();
866           }
867           return;
868         } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
869                    F->getName() == "vsprintf") {
870           CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
871
872           if (F->getName() == "vfprintf") {
873             // ffprintf reads and writes the FILE argument, and applies the type
874             // to it.
875             DSNodeHandle H = getValueDest(**AI);
876             if (DSNode *N = H.getNode()) {
877               N->setModifiedMarker()->setReadMarker();
878               const Type *ArgTy = (*AI)->getType();
879               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
880                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
881             }
882             ++AI;
883           } else if (F->getName() == "vsprintf") {
884             // vsprintf writes the first string argument.
885             DSNodeHandle H = getValueDest(**AI++);
886             if (DSNode *N = H.getNode()) {
887               N->setModifiedMarker();
888               const Type *ArgTy = (*AI)->getType();
889               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
890                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
891             }
892           }
893
894           // Read the format
895           if (AI != E) {
896             if (isPointerType((*AI)->getType()))
897               if (DSNode *N = getValueDest(**AI).getNode())
898                 N->setReadMarker();
899             ++AI;
900           }
901
902           // Read the valist, and the pointed-to objects.
903           if (AI != E && isPointerType((*AI)->getType())) {
904             const DSNodeHandle &VAList = getValueDest(**AI);
905             if (DSNode *N = VAList.getNode()) {
906               N->setReadMarker();
907               N->mergeTypeInfo(PointerType::get(Type::SByteTy),
908                                VAList.getOffset(), false);
909
910               DSNodeHandle &VAListObjs = getLink(VAList);
911               VAListObjs.getNode()->setReadMarker();
912             }
913           }
914
915           return;
916         } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
917                    F->getName() == "sscanf") {
918           CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
919
920           if (F->getName() == "fscanf") {
921             // fscanf reads and writes the FILE argument, and applies the type
922             // to it.
923             DSNodeHandle H = getValueDest(**AI);
924             if (DSNode *N = H.getNode()) {
925               N->setReadMarker();
926               const Type *ArgTy = (*AI)->getType();
927               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
928                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
929             }
930           } else if (F->getName() == "sscanf") {
931             // sscanf reads the first string argument.
932             DSNodeHandle H = getValueDest(**AI++);
933             if (DSNode *N = H.getNode()) {
934               N->setReadMarker();
935               const Type *ArgTy = (*AI)->getType();
936               if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
937                 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
938             }
939           }
940
941           for (; AI != E; ++AI) {
942             // scanf writes all pointer arguments.
943             if (isPointerType((*AI)->getType()))
944               if (DSNode *N = getValueDest(**AI).getNode())
945                 N->setModifiedMarker();
946           }
947           return;
948         } else if (F->getName() == "strtok") {
949           // strtok reads and writes the first argument, returning it.  It reads
950           // its second arg.  FIXME: strtok also modifies some hidden static
951           // data.  Someday this might matter.
952           CallSite::arg_iterator AI = CS.arg_begin();
953           DSNodeHandle H = getValueDest(**AI++);
954           if (DSNode *N = H.getNode()) {
955             N->setReadMarker()->setModifiedMarker();      // Reads/Writes buffer
956             const Type *ArgTy = F->getFunctionType()->getParamType(0);
957             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
958               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
959           }
960           H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
961
962           H = getValueDest(**AI);       // Reads delimiter
963           if (DSNode *N = H.getNode()) {
964             N->setReadMarker();
965             const Type *ArgTy = F->getFunctionType()->getParamType(1);
966             if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
967               N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
968           }
969           return;
970         } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
971                    F->getName() == "strstr") {
972           // These read their arguments, and return the first one
973           DSNodeHandle H = getValueDest(**CS.arg_begin());
974           H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
975
976           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
977                AI != E; ++AI)
978             if (isPointerType((*AI)->getType()))
979               if (DSNode *N = getValueDest(**AI).getNode())
980                 N->setReadMarker();
981
982           if (DSNode *N = H.getNode())
983             N->setReadMarker();
984           return;
985         } else if (F->getName() == "__assert_fail") {
986           for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
987                AI != E; ++AI)
988             if (isPointerType((*AI)->getType()))
989               if (DSNode *N = getValueDest(**AI).getNode())
990                 N->setReadMarker();
991           return;
992         } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
993           // This writes its second argument, and forces it to double.
994           CallSite::arg_iterator compit = CS.arg_end();
995           DSNodeHandle H = getValueDest(**--compit);
996           if (DSNode *N = H.getNode()) {
997             N->setModifiedMarker();
998             N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
999           }
1000           return;
1001         } else if (F->getName() == "strcat" || F->getName() == "strncat") {
1002           //This might be making unsafe assumptions about usage
1003           //Merge return and first arg
1004           DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
1005           RetNH.mergeWith(getValueDest(**CS.arg_begin()));
1006           if (DSNode *N = RetNH.getNode())
1007             N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
1008           //and read second pointer
1009           if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
1010             N->setReadMarker();
1011           return;
1012         } else if (F->getName() == "strcpy" || F->getName() == "strncpy") {
1013           //This might be making unsafe assumptions about usage
1014           //Merge return and first arg
1015           DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
1016           RetNH.mergeWith(getValueDest(**CS.arg_begin()));
1017           if (DSNode *N = RetNH.getNode())
1018             N->setHeapNodeMarker()->setModifiedMarker();
1019           //and read second pointer
1020           if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
1021             N->setReadMarker();
1022           return;
1023         } else {
1024           // Unknown function, warn if it returns a pointer type or takes a
1025           // pointer argument.
1026           bool Warn = isPointerType(CS.getInstruction()->getType());
1027           if (!Warn)
1028             for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1029                  I != E; ++I)
1030               if (isPointerType((*I)->getType())) {
1031                 Warn = true;
1032                 break;
1033               }
1034           if (Warn) {
1035             DEBUG(std::cerr << "WARNING: Call to unknown external function '"
1036                   << F->getName() << "' will cause pessimistic results!\n");
1037           }
1038         }
1039       }
1040
1041
1042   // Set up the return value...
1043   DSNodeHandle RetVal;
1044   Instruction *I = CS.getInstruction();
1045   if (isPointerType(I->getType()))
1046     RetVal = getValueDest(*I);
1047
1048   DSNode *CalleeNode = 0;
1049   if (DisableDirectCallOpt || !isa<Function>(Callee)) {
1050     CalleeNode = getValueDest(*Callee).getNode();
1051     if (CalleeNode == 0) {
1052       std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
1053       return;  // Calling a null pointer?
1054     }
1055   }
1056
1057   std::vector<DSNodeHandle> Args;
1058   Args.reserve(CS.arg_end()-CS.arg_begin());
1059
1060   // Calculate the arguments vector...
1061   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1062     if (isPointerType((*I)->getType()))
1063       Args.push_back(getValueDest(**I));
1064
1065   // Add a new function call entry...
1066   if (CalleeNode)
1067     FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
1068   else
1069     FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
1070                                         Args));
1071 }
1072
1073 void GraphBuilder::visitFreeInst(FreeInst &FI) {
1074   // Mark that the node is written to...
1075   if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
1076     N->setModifiedMarker()->setHeapNodeMarker();
1077 }
1078
1079 /// Handle casts...
1080 void GraphBuilder::visitCastInst(CastInst &CI) {
1081   if (isPointerType(CI.getType()))
1082     if (isPointerType(CI.getOperand(0)->getType())) {
1083       DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1084       if (Ptr.getNode() == 0) return;
1085
1086       // Cast one pointer to the other, just act like a copy instruction
1087       setDestTo(CI, Ptr);
1088     } else {
1089       // Cast something (floating point, small integer) to a pointer.  We need
1090       // to track the fact that the node points to SOMETHING, just something we
1091       // don't know about.  Make an "Unknown" node.
1092       //
1093       setDestTo(CI, createNode()->setUnknownNodeMarker());
1094     }
1095 }
1096
1097
1098 // visitInstruction - For all other instruction types, if we have any arguments
1099 // that are of pointer type, make them have unknown composition bits, and merge
1100 // the nodes together.
1101 void GraphBuilder::visitInstruction(Instruction &Inst) {
1102   DSNodeHandle CurNode;
1103   if (isPointerType(Inst.getType()))
1104     CurNode = getValueDest(Inst);
1105   for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1106     if (isPointerType((*I)->getType()))
1107       CurNode.mergeWith(getValueDest(**I));
1108
1109   if (DSNode *N = CurNode.getNode())
1110     N->setUnknownNodeMarker();
1111 }
1112
1113
1114
1115 //===----------------------------------------------------------------------===//
1116 // LocalDataStructures Implementation
1117 //===----------------------------------------------------------------------===//
1118
1119 // MergeConstantInitIntoNode - Merge the specified constant into the node
1120 // pointed to by NH.
1121 void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1122   // Ensure a type-record exists...
1123   DSNode *NHN = NH.getNode();
1124   NHN->mergeTypeInfo(C->getType(), NH.getOffset());
1125
1126   if (C->getType()->isFirstClassType()) {
1127     if (isPointerType(C->getType()))
1128       // Avoid adding edges from null, or processing non-"pointer" stores
1129       NH.addEdgeTo(getValueDest(*C));
1130     return;
1131   }
1132
1133   const TargetData &TD = NH.getNode()->getTargetData();
1134
1135   if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1136     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1137       // We don't currently do any indexing for arrays...
1138       MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1139   } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1140     const StructLayout *SL = TD.getStructLayout(CS->getType());
1141     for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1142       DSNode *NHN = NH.getNode();
1143       //Some programmers think ending a structure with a [0 x sbyte] is cute
1144       if (SL->MemberOffsets[i] < SL->StructSize) {
1145         DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1146         MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1147       } else if (SL->MemberOffsets[i] == SL->StructSize) {
1148         DEBUG(std::cerr << "Zero size element at end of struct\n");
1149         NHN->foldNodeCompletely();
1150       } else {
1151         assert(0 && "type was smaller than offsets of of struct layout indicate");
1152       }
1153     }
1154   } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
1155     // Noop
1156   } else {
1157     assert(0 && "Unknown constant type!");
1158   }
1159 }
1160
1161 void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1162   assert(!GV->isExternal() && "Cannot merge in external global!");
1163   // Get a node handle to the global node and merge the initializer into it.
1164   DSNodeHandle NH = getValueDest(*GV);
1165   MergeConstantInitIntoNode(NH, GV->getInitializer());
1166 }
1167
1168
1169 /// BuildGlobalECs - Look at all of the nodes in the globals graph.  If any node
1170 /// contains multiple globals, DSA will never, ever, be able to tell the globals
1171 /// apart.  Instead of maintaining this information in all of the graphs
1172 /// throughout the entire program, store only a single global (the "leader") in
1173 /// the graphs, and build equivalence classes for the rest of the globals.
1174 static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1175   DSScalarMap &SM = GG.getScalarMap();
1176   EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1177   for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1178        I != E; ++I) {
1179     if (I->getGlobalsList().size() <= 1) continue;
1180
1181     // First, build up the equivalence set for this block of globals.
1182     const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1183     GlobalValue *First = GVs[0];
1184     for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1185       GlobalECs.unionSets(First, GVs[i]);
1186
1187     // Next, get the leader element.
1188     assert(First == GlobalECs.getLeaderValue(First) &&
1189            "First did not end up being the leader?");
1190
1191     // Next, remove all globals from the scalar map that are not the leader.
1192     assert(GVs[0] == First && "First had to be at the front!");
1193     for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1194       ECGlobals.insert(GVs[i]);
1195       SM.erase(SM.find(GVs[i]));
1196     }
1197
1198     // Finally, change the global node to only contain the leader.
1199     I->clearGlobals();
1200     I->addGlobal(First);
1201   }
1202
1203   DEBUG(GG.AssertGraphOK());
1204 }
1205
1206 /// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1207 /// really just equivalent to some other globals, remove the globals from the
1208 /// specified DSGraph (if present), and merge any nodes with their leader nodes.
1209 static void EliminateUsesOfECGlobals(DSGraph &G,
1210                                      const std::set<GlobalValue*> &ECGlobals) {
1211   DSScalarMap &SM = G.getScalarMap();
1212   EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1213
1214   bool MadeChange = false;
1215   for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1216        GI != E; ) {
1217     GlobalValue *GV = *GI++;
1218     if (!ECGlobals.count(GV)) continue;
1219
1220     const DSNodeHandle &GVNH = SM[GV];
1221     assert(!GVNH.isNull() && "Global has null NH!?");
1222
1223     // Okay, this global is in some equivalence class.  Start by finding the
1224     // leader of the class.
1225     GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1226
1227     // If the leader isn't already in the graph, insert it into the node
1228     // corresponding to GV.
1229     if (!SM.global_count(Leader)) {
1230       GVNH.getNode()->addGlobal(Leader);
1231       SM[Leader] = GVNH;
1232     } else {
1233       // Otherwise, the leader is in the graph, make sure the nodes are the
1234       // merged in the specified graph.
1235       const DSNodeHandle &LNH = SM[Leader];
1236       if (LNH.getNode() != GVNH.getNode())
1237         LNH.mergeWith(GVNH);
1238     }
1239
1240     // Next step, remove the global from the DSNode.
1241     GVNH.getNode()->removeGlobal(GV);
1242
1243     // Finally, remove the global from the ScalarMap.
1244     SM.erase(GV);
1245     MadeChange = true;
1246   }
1247
1248   DEBUG(if(MadeChange) G.AssertGraphOK());
1249 }
1250
1251 bool LocalDataStructures::runOnModule(Module &M) {
1252   const TargetData &TD = getAnalysis<TargetData>();
1253
1254   // First step, build the globals graph.
1255   GlobalsGraph = new DSGraph(GlobalECs, TD);
1256   {
1257     GraphBuilder GGB(*GlobalsGraph);
1258
1259     // Add initializers for all of the globals to the globals graph.
1260     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1261          I != E; ++I)
1262       if (!I->isExternal())
1263         GGB.mergeInGlobalInitializer(I);
1264   }
1265
1266   // Next step, iterate through the nodes in the globals graph, unioning
1267   // together the globals into equivalence classes.
1268   std::set<GlobalValue*> ECGlobals;
1269   BuildGlobalECs(*GlobalsGraph, ECGlobals);
1270   DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1271   ECGlobals.clear();
1272
1273   // Calculate all of the graphs...
1274   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1275     if (!I->isExternal())
1276       DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1277                                                   GlobalsGraph)));
1278
1279   GlobalsGraph->removeTriviallyDeadNodes();
1280   GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
1281
1282   // Now that we've computed all of the graphs, and merged all of the info into
1283   // the globals graph, see if we have further constrained the globals in the
1284   // program if so, update GlobalECs and remove the extraneous globals from the
1285   // program.
1286   BuildGlobalECs(*GlobalsGraph, ECGlobals);
1287   if (!ECGlobals.empty()) {
1288     DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1289     for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1290            E = DSInfo.end(); I != E; ++I)
1291       EliminateUsesOfECGlobals(*I->second, ECGlobals);
1292   }
1293
1294   return false;
1295 }
1296
1297 // releaseMemory - If the pass pipeline is done with this pass, we can release
1298 // our memory... here...
1299 //
1300 void LocalDataStructures::releaseMemory() {
1301   for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1302          E = DSInfo.end(); I != E; ++I) {
1303     I->second->getReturnNodes().erase(I->first);
1304     if (I->second->getReturnNodes().empty())
1305       delete I->second;
1306   }
1307
1308   // Empty map so next time memory is released, data structures are not
1309   // re-deleted.
1310   DSInfo.clear();
1311   delete GlobalsGraph;
1312   GlobalsGraph = 0;
1313 }
1314