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