blob: 9afc9661a6351d043973992c082005d23dfbdd81 [file] [log] [blame]
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001//===- Local.cpp - Compute a local data structure graph for a function ----===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerc68c31b2002-07-10 22:38:08 +00009//
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
Chris Lattner4dabb2c2004-07-07 06:32:21 +000015#include "llvm/Analysis/DataStructure/DataStructure.h"
16#include "llvm/Analysis/DataStructure/DSGraph.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner808a7ae2003-09-20 16:34:13 +000019#include "llvm/Instructions.h"
Chris Lattnera07b72f2004-02-13 16:09:54 +000020#include "llvm/Intrinsics.h"
Chris Lattnerfa3711a2003-11-25 20:19:55 +000021#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerc68c31b2002-07-10 22:38:08 +000022#include "llvm/Support/InstVisitor.h"
Chris Lattnerfccd06f2002-10-01 22:33:50 +000023#include "llvm/Target/TargetData.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Timer.h"
Chris Lattner86a54842006-01-22 22:53:01 +000027#include <iostream>
Chris Lattnerfccd06f2002-10-01 22:33:50 +000028
29// FIXME: This should eventually be a FunctionPass that is automatically
30// aggregated into a Pass.
31//
32#include "llvm/Module.h"
33
Chris Lattner9a927292003-11-12 23:11:14 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Chris Lattner97f51a32002-07-27 01:12:15 +000036static RegisterAnalysis<LocalDataStructures>
37X("datastructure", "Local Data Structure Analysis");
Chris Lattner97f51a32002-07-27 01:12:15 +000038
Chris Lattnera1907662003-11-13 03:10:49 +000039static cl::opt<bool>
Chris Lattnerf0431b02004-08-02 20:16:21 +000040TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
Chris Lattnera1907662003-11-13 03:10:49 +000041 cl::desc("If this is set, track integers as potential pointers"));
Chris Lattnera1907662003-11-13 03:10:49 +000042
John Criswellfa700522005-12-19 17:38:39 +000043static cl::list<std::string>
John Criswell61af9132005-12-19 20:14:38 +000044AllocList("dsa-alloc-list",
John Criswellfa700522005-12-19 17:38:39 +000045 cl::value_desc("list"),
46 cl::desc("List of functions that allocate memory from the heap"),
John Criswell61af9132005-12-19 20:14:38 +000047 cl::CommaSeparated, cl::Hidden);
John Criswellfa700522005-12-19 17:38:39 +000048
John Criswell30751602005-12-19 19:54:23 +000049static cl::list<std::string>
John Criswell61af9132005-12-19 20:14:38 +000050FreeList("dsa-free-list",
John Criswell30751602005-12-19 19:54:23 +000051 cl::value_desc("list"),
52 cl::desc("List of functions that free memory from the heap"),
John Criswell61af9132005-12-19 20:14:38 +000053 cl::CommaSeparated, cl::Hidden);
John Criswell30751602005-12-19 19:54:23 +000054
Chris Lattner9a927292003-11-12 23:11:14 +000055namespace llvm {
Chris Lattnerb1060432002-11-07 05:20:53 +000056namespace DS {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000057 // 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;
Chris Lattnera1907662003-11-13 03:10:49 +000061 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
Chris Lattnerfccd06f2002-10-01 22:33:50 +000062 return Ty->getPrimitiveSize() >= PointerSize;
63 return false;
64 }
Chris Lattner9a927292003-11-12 23:11:14 +000065}}
Chris Lattnerfccd06f2002-10-01 22:33:50 +000066
Brian Gaeked0fde302003-11-11 22:41:34 +000067using namespace DS;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000068
69namespace {
Chris Lattner923fc052003-02-05 21:59:58 +000070 cl::opt<bool>
71 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
72 cl::desc("Disable direct call optimization in "
73 "DSGraph construction"));
Chris Lattnerca3f7902003-02-08 20:18:39 +000074 cl::opt<bool>
75 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
76 cl::desc("Disable field sensitivity in DSGraphs"));
Chris Lattner923fc052003-02-05 21:59:58 +000077
Chris Lattnerfccd06f2002-10-01 22:33:50 +000078 //===--------------------------------------------------------------------===//
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 ///
Chris Lattnerc68c31b2002-07-10 22:38:08 +000085 class GraphBuilder : InstVisitor<GraphBuilder> {
86 DSGraph &G;
Chris Lattner26c4fc32003-09-20 21:48:16 +000087 DSNodeHandle *RetNode; // Node that gets returned...
Chris Lattner62482e52004-01-28 09:15:42 +000088 DSScalarMap &ScalarMap;
Chris Lattnera9548d92005-01-30 23:51:02 +000089 std::list<DSCallSite> *FunctionCalls;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000090
91 public:
Misha Brukman2b37d7c2005-04-21 21:13:18 +000092 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
Chris Lattnera9548d92005-01-30 23:51:02 +000093 std::list<DSCallSite> &fc)
Chris Lattner26c4fc32003-09-20 21:48:16 +000094 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
95 FunctionCalls(&fc) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000096
97 // Create scalar nodes for all pointer arguments...
Chris Lattnera513fb12005-03-22 02:45:13 +000098 for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end();
99 I != E; ++I)
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000100 if (isPointerType(I->getType()))
101 getValueDest(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000102
Chris Lattner26c4fc32003-09-20 21:48:16 +0000103 visit(f); // Single pass over the function
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000104 }
105
Chris Lattner26c4fc32003-09-20 21:48:16 +0000106 // 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
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000113 private:
114 // Visitor functions, used to handle each instruction type we encounter...
115 friend class InstVisitor<GraphBuilder>;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000116 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
117 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
118 void handleAlloc(AllocationInst &AI, bool isHeap);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000119
120 void visitPHINode(PHINode &PN);
Chris Lattner6e84bd72005-02-25 01:27:48 +0000121 void visitSelectInst(SelectInst &SI);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000122
Chris Lattner51340062002-11-08 05:00:44 +0000123 void visitGetElementPtrInst(User &GEP);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000124 void visitReturnInst(ReturnInst &RI);
125 void visitLoadInst(LoadInst &LI);
126 void visitStoreInst(StoreInst &SI);
127 void visitCallInst(CallInst &CI);
Chris Lattner808a7ae2003-09-20 16:34:13 +0000128 void visitInvokeInst(InvokeInst &II);
Chris Lattner32672652005-03-05 19:04:31 +0000129 void visitSetCondInst(SetCondInst &SCI);
Vikram S. Advebac06222002-12-06 21:17:10 +0000130 void visitFreeInst(FreeInst &FI);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000131 void visitCastInst(CastInst &CI);
Chris Lattner878e5212003-02-04 00:59:50 +0000132 void visitInstruction(Instruction &I);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000133
Chris Lattner808a7ae2003-09-20 16:34:13 +0000134 void visitCallSite(CallSite CS);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000135 void visitVAArgInst(VAArgInst &I);
Chris Lattner26c4fc32003-09-20 21:48:16 +0000136
137 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000138 private:
139 // Helper functions used to implement the visitation functions...
140
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000141 /// createNode - Create a new DSNode, ensuring that it is properly added to
142 /// the graph.
143 ///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000144 DSNode *createNode(const Type *Ty = 0) {
145 DSNode *N = new DSNode(Ty, &G); // Create the node
Chris Lattnere158b192003-06-16 12:08:18 +0000146 if (DisableFieldSensitivity) {
Chris Lattner2412a052004-05-23 21:14:09 +0000147 // 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;
Chris Lattnerca3f7902003-02-08 20:18:39 +0000150 N->foldNodeCompletely();
Chris Lattnere158b192003-06-16 12:08:18 +0000151 if (DSNode *FN = N->getForwardNode())
152 N = FN;
153 }
Chris Lattner92673292002-11-02 00:13:20 +0000154 return N;
155 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000156
Chris Lattnerc875f022002-11-03 21:27:48 +0000157 /// setDestTo - Set the ScalarMap entry for the specified value to point to
Chris Lattner92673292002-11-02 00:13:20 +0000158 /// the specified destination. If the Value already points to a node, make
159 /// sure to merge the two destinations together.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000160 ///
Chris Lattner92673292002-11-02 00:13:20 +0000161 void setDestTo(Value &V, const DSNodeHandle &NH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000162
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000163 /// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000164 ///
Chris Lattner92673292002-11-02 00:13:20 +0000165 DSNodeHandle getValueDest(Value &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000166
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000167 /// 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
Chris Lattner7e51c872002-10-31 06:52:26 +0000169 /// null), then we create a new node, link it, then return it.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000170 ///
Chris Lattner7e51c872002-10-31 06:52:26 +0000171 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000172 };
173}
174
Brian Gaeked0fde302003-11-11 22:41:34 +0000175using namespace DS;
176
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000177//===----------------------------------------------------------------------===//
178// DSGraph constructor - Simply use the GraphBuilder to construct the local
179// graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000180DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
181 Function &F, DSGraph *GG)
182 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
Chris Lattner2a068862002-11-10 06:53:38 +0000183 PrintAuxCalls = false;
Chris Lattner30514192003-07-02 04:37:26 +0000184
185 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
186
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000187 // Use the graph builder to construct the local version of the graph
Chris Lattner26c4fc32003-09-20 21:48:16 +0000188 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
Chris Lattner4fe34612002-11-18 21:44:19 +0000189#ifndef NDEBUG
190 Timer::addPeakMemoryMeasurement();
191#endif
Chris Lattner1a1a85d2003-02-14 04:55:58 +0000192
Chris Lattnerc420ab62004-02-25 23:31:02 +0000193 // 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);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000197
Chris Lattnerc420ab62004-02-25 23:31:02 +0000198 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
199 I != ScalarMap.global_end(); ++I)
200 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattner76a9eb32004-03-03 23:00:19 +0000201 if (!GV->isExternal() && GV->isConstant())
Chris Lattnerc420ab62004-02-25 23:31:02 +0000202 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
203 }
204
Chris Lattner394471f2003-01-23 22:05:33 +0000205 markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner96517252002-11-09 20:55:24 +0000206
207 // Remove any nodes made dead due to merging...
Chris Lattner394471f2003-01-23 22:05:33 +0000208 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000209}
210
211
212//===----------------------------------------------------------------------===//
213// Helper method implementations...
214//
215
Chris Lattner92673292002-11-02 00:13:20 +0000216/// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000217///
Chris Lattner51340062002-11-08 05:00:44 +0000218DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
219 Value *V = &Val;
Chris Lattner82962de2004-11-03 18:51:26 +0000220 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
Chris Lattner51340062002-11-08 05:00:44 +0000221 return 0; // Null doesn't point to anything, don't add to ScalarMap!
Chris Lattner92673292002-11-02 00:13:20 +0000222
Vikram S. Advebac06222002-12-06 21:17:10 +0000223 DSNodeHandle &NH = ScalarMap[V];
Chris Lattner62c3a952004-10-30 04:22:45 +0000224 if (!NH.isNull())
Vikram S. Advebac06222002-12-06 21:17:10 +0000225 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.
Reid Spencere8404342004-07-18 00:18:30 +0000230 DSNode* N;
231 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
Chris Lattner48427b52005-03-20 01:18:00 +0000232 // Create a new global node for this global variable.
Reid Spencere8404342004-07-18 00:18:30 +0000233 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)) {
Chris Lattnera513fb12005-03-22 02:45:13 +0000237 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) {
Chris Lattner51340062002-11-08 05:00:44 +0000243 visitGetElementPtrInst(*CE);
Chris Lattner62482e52004-01-28 09:15:42 +0000244 DSScalarMap::iterator I = ScalarMap.find(CE);
Chris Lattner2cfbaaf2002-11-09 20:14:03 +0000245 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
Chris Lattner1e56c542003-02-09 23:04:12 +0000246 NH = I->second;
247 } else {
248 // This returns a conservative unknown node for any unhandled ConstExpr
Chris Lattnerbd92b732003-06-19 21:15:11 +0000249 return NH = createNode()->setUnknownNodeMarker();
Chris Lattner51340062002-11-08 05:00:44 +0000250 }
Chris Lattner62c3a952004-10-30 04:22:45 +0000251 if (NH.isNull()) { // (getelementptr null, X) returns null
Chris Lattner1e56c542003-02-09 23:04:12 +0000252 ScalarMap.erase(V);
253 return 0;
254 }
255 return NH;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000256 } else if (isa<UndefValue>(C)) {
257 ScalarMap.erase(V);
258 return 0;
Chris Lattner51340062002-11-08 05:00:44 +0000259 } else {
260 assert(0 && "Unknown constant type!");
261 }
Reid Spencere8404342004-07-18 00:18:30 +0000262 N = createNode(); // just create a shadow node
Chris Lattner92673292002-11-02 00:13:20 +0000263 } else {
264 // Otherwise just create a shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000265 N = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000266 }
267
Chris Lattnerefffdc92004-07-07 06:12:52 +0000268 NH.setTo(N, 0); // Remember that we are pointing to it...
Chris Lattner92673292002-11-02 00:13:20 +0000269 return NH;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000270}
271
Chris Lattner0d9bab82002-07-18 00:12:30 +0000272
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000273/// 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///
Chris Lattner7e51c872002-10-31 06:52:26 +0000279DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000280 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
Chris Lattner08db7192002-11-06 06:20:27 +0000281 DSNodeHandle &Link = Node.getLink(LinkNo);
Chris Lattner62c3a952004-10-30 04:22:45 +0000282 if (Link.isNull()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000283 // If the link hasn't been created yet, make and return a new shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000284 Link = createNode();
Chris Lattner08db7192002-11-06 06:20:27 +0000285 }
286 return Link;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000287}
288
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000289
Chris Lattnerc875f022002-11-03 21:27:48 +0000290/// setDestTo - Set the ScalarMap entry for the specified value to point to the
Chris Lattner92673292002-11-02 00:13:20 +0000291/// specified destination. If the Value already points to a node, make sure to
292/// merge the two destinations together.
293///
294void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000295 ScalarMap[&V].mergeWith(NH);
Chris Lattner92673292002-11-02 00:13:20 +0000296}
297
298
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000299//===----------------------------------------------------------------------===//
300// Specific instruction type handler implementations...
301//
302
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000303/// Alloca & Malloc instruction implementation - Simply create a new memory
304/// object, pointing the scalar to it.
305///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000306void 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);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000313}
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//
318void GraphBuilder::visitPHINode(PHINode &PN) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000319 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000320
Chris Lattnerc875f022002-11-03 21:27:48 +0000321 DSNodeHandle &PNDest = ScalarMap[&PN];
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000322 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
Chris Lattner92673292002-11-02 00:13:20 +0000323 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000324}
325
Chris Lattner6e84bd72005-02-25 01:27:48 +0000326void GraphBuilder::visitSelectInst(SelectInst &SI) {
327 if (!isPointerType(SI.getType())) return; // Only pointer Selects
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000328
Chris Lattner6e84bd72005-02-25 01:27:48 +0000329 DSNodeHandle &Dest = ScalarMap[&SI];
330 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
331 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
332}
333
Chris Lattner32672652005-03-05 19:04:31 +0000334void 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
Chris Lattner51340062002-11-08 05:00:44 +0000341void GraphBuilder::visitGetElementPtrInst(User &GEP) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000342 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
Chris Lattner753b1132005-02-24 19:55:31 +0000343 if (Value.isNull())
344 Value = createNode();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000345
Chris Lattner179bc7d2003-11-14 17:09:46 +0000346 // 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.
Chris Lattner0c9707a2005-03-18 23:18:20 +0000358 if (AllZeros || (!Value.isNull() &&
359 Value.getNode()->isNodeCompletelyFolded())) {
Chris Lattner179bc7d2003-11-14 17:09:46 +0000360 setDestTo(GEP, Value);
361 return;
362 }
363
364
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000365 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
366 const Type *CurTy = PTy->getElementType();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000367
Chris Lattner08db7192002-11-06 06:20:27 +0000368 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
369 // If the node had to be folded... exit quickly
Chris Lattner92673292002-11-02 00:13:20 +0000370 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000371 return;
372 }
373
Chris Lattner15869aa2003-11-02 22:27:28 +0000374 const TargetData &TD = Value.getNode()->getTargetData();
375
Chris Lattner08db7192002-11-06 06:20:27 +0000376#if 0
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000377 // Handle the pointer index specially...
378 if (GEP.getNumOperands() > 1 &&
Chris Lattner28977af2004-04-05 01:30:19 +0000379 (!isa<Constant>(GEP.getOperand(1)) ||
380 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000381
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();
Chris Lattner92673292002-11-02 00:13:20 +0000393 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000394 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 }
Chris Lattner08db7192002-11-06 06:20:27 +0000402#endif
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000403
404 // All of these subscripts are indexing INTO the elements we have...
Chris Lattner26c4fc32003-09-20 21:48:16 +0000405 unsigned Offset = 0;
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000406 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)) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000409 unsigned FieldNo =
410 (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
411 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
Chris Lattner82e9d722004-03-01 19:02:54 +0000412 } 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();
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000416 }
417
418
Chris Lattner08db7192002-11-06 06:20:27 +0000419#if 0
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000420 if (const SequentialType *STy = cast<SequentialType>(*I)) {
421 CurTy = STy->getElementType();
Chris Lattnere03f32b2002-10-02 06:24:36 +0000422 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000423 Offset += CS->getValue()*TD.getTypeSize(CurTy);
Chris Lattnere03f32b2002-10-02 06:24:36 +0000424 } 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
Misha Brukman2f2d0652003-09-11 18:14:24 +0000437 // zeroth element.
Chris Lattnere03f32b2002-10-02 06:24:36 +0000438 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 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000443 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000444 }
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000445#endif
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000446
447 // Add in the offset calculated...
448 Value.setOffset(Value.getOffset()+Offset);
449
Sumant Kowshik8a3802d2005-12-06 18:04:30 +0000450 // 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...
Chris Lattner92673292002-11-02 00:13:20 +0000468 setDestTo(GEP, Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000469}
470
471void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattner92673292002-11-02 00:13:20 +0000472 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
Chris Lattner6e84bd72005-02-25 01:27:48 +0000473 if (Ptr.isNull())
474 Ptr = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000475
476 // Make that the node is read from...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000477 Ptr.getNode()->setReadMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000478
479 // Ensure a typerecord exists...
Chris Lattner088b6392003-03-03 17:13:31 +0000480 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
Chris Lattner92673292002-11-02 00:13:20 +0000481
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000482 if (isPointerType(LI.getType()))
Chris Lattner92673292002-11-02 00:13:20 +0000483 setDestTo(LI, getLink(Ptr));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000484}
485
486void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000487 const Type *StoredTy = SI.getOperand(0)->getType();
Chris Lattner92673292002-11-02 00:13:20 +0000488 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000489 if (Dest.isNull()) return;
Chris Lattner92673292002-11-02 00:13:20 +0000490
Vikram S. Advebac06222002-12-06 21:17:10 +0000491 // Mark that the node is written to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000492 Dest.getNode()->setModifiedMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000493
Chris Lattner26c4fc32003-09-20 21:48:16 +0000494 // Ensure a type-record exists...
Chris Lattner08db7192002-11-06 06:20:27 +0000495 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000496
497 // Avoid adding edges from null, or processing non-"pointer" stores
Chris Lattner92673292002-11-02 00:13:20 +0000498 if (isPointerType(StoredTy))
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000499 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000500}
501
502void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattner92673292002-11-02 00:13:20 +0000503 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
Chris Lattner26c4fc32003-09-20 21:48:16 +0000504 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000505}
506
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000507void GraphBuilder::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +0000508 //FIXME: also updates the argument
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000509 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
Chris Lattner62c3a952004-10-30 04:22:45 +0000515 // Ensure a type record exists.
516 DSNode *PtrN = Ptr.getNode();
517 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000518
519 if (isPointerType(I.getType()))
520 setDestTo(I, getLink(Ptr));
521}
522
523
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000524void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000525 visitCallSite(&CI);
526}
527
528void GraphBuilder::visitInvokeInst(InvokeInst &II) {
529 visitCallSite(&II);
530}
531
532void GraphBuilder::visitCallSite(CallSite CS) {
Chris Lattnercb582402004-02-26 22:07:22 +0000533 Value *Callee = CS.getCalledValue();
Chris Lattnercb582402004-02-26 22:07:22 +0000534
Chris Lattner894263b2003-09-20 16:50:46 +0000535 // Special case handling of certain libc allocation functions here.
Chris Lattnercb582402004-02-26 22:07:22 +0000536 if (Function *F = dyn_cast<Function>(Callee))
Chris Lattner894263b2003-09-20 16:50:46 +0000537 if (F->isExternal())
Chris Lattnera07b72f2004-02-13 16:09:54 +0000538 switch (F->getIntrinsicID()) {
Chris Lattner317201d2004-03-13 00:24:00 +0000539 case Intrinsic::vastart:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000540 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
541 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000542 case Intrinsic::vacopy:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000543 getValueDest(*CS.getInstruction()).
544 mergeWith(getValueDest(**(CS.arg_begin())));
545 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000546 case Intrinsic::vaend:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000547 return; // noop
Chris Lattner03dd4652006-03-03 00:00:25 +0000548 case Intrinsic::memcpy_i32:
Andrew Lenharthaed967d2006-04-05 02:42:36 +0000549 case Intrinsic::memcpy_i64:
Andrew Lenharth24b1ea12006-03-15 03:43:59 +0000550 case Intrinsic::memmove_i32:
551 case Intrinsic::memmove_i64: {
Andrew Lenharthaed967d2006-04-05 02:42:36 +0000552 //This is over aggressive. What these functions do is not make the
553 // targets pointers alias, but rather merge the out edges of the graphs
554 // for the pointers according to the type merging of the graphs.
555 //Simply merging the two graphs is a crude approximation to this.
Andrew Lenharth2dbf23a2006-04-18 19:54:11 +0000556 //Instead, copy the src pointer graph, then merge the copy with the
557 //dest pointer, thus avoiding contaminating the src with info from the dest
Andrew Lenharthaed967d2006-04-05 02:42:36 +0000558 //I might be wrong though.
559
Chris Lattnera07b72f2004-02-13 16:09:54 +0000560 // Merge the first & second arguments, and mark the memory read and
Andrew Lenharth2dbf23a2006-04-18 19:54:11 +0000561 // modified. Preserve second graph
562 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
563 DSNodeHandle SrcNH = getValueDest(**(CS.arg_begin()+1));
564 DSNodeHandle Copy( new DSNode(*SrcNH.getNode(), SrcNH.getNode()->getParentGraph()),
565 SrcNH.getOffset());
566 RetNH.mergeWith(Copy);
Chris Lattner67ce57a2003-11-09 03:32:52 +0000567 if (DSNode *N = RetNH.getNode())
Andrew Lenharth2dbf23a2006-04-18 19:54:11 +0000568 N->setModifiedMarker();
569 if (DSNode *N = SrcNH.getNode())
570 N->setReadMarker();
Chris Lattner67ce57a2003-11-09 03:32:52 +0000571 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000572 }
Chris Lattner03dd4652006-03-03 00:00:25 +0000573 case Intrinsic::memset_i32:
574 case Intrinsic::memset_i64:
Chris Lattnereee33b22004-02-16 18:37:40 +0000575 // Mark the memory modified.
576 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
577 N->setModifiedMarker();
578 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000579 default:
John Criswellfa700522005-12-19 17:38:39 +0000580 // Determine if the called function is one of the specified heap
581 // allocation functions
582 for (cl::list<std::string>::iterator AllocFunc = AllocList.begin(),
583 LastAllocFunc = AllocList.end();
584 AllocFunc != LastAllocFunc;
585 ++AllocFunc) {
586 if (F->getName() == *(AllocFunc)) {
587 setDestTo(*CS.getInstruction(),
588 createNode()->setHeapNodeMarker()->setModifiedMarker());
589 return;
590 }
591 }
592
John Criswell30751602005-12-19 19:54:23 +0000593 // Determine if the called function is one of the specified heap
594 // free functions
595 for (cl::list<std::string>::iterator FreeFunc = FreeList.begin(),
596 LastFreeFunc = FreeList.end();
597 FreeFunc != LastFreeFunc;
598 ++FreeFunc) {
599 if (F->getName() == *(FreeFunc)) {
600 // Mark that the node is written to...
601 if (DSNode *N = getValueDest(*(CS.getArgument(0))).getNode())
602 N->setModifiedMarker()->setHeapNodeMarker();
603 return;
604 }
605 }
606
Vikram S. Advee4e97ef2004-05-25 08:14:52 +0000607 if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
608 F->getName() == "memalign" || F->getName() == "valloc") {
Chris Lattnera07b72f2004-02-13 16:09:54 +0000609 setDestTo(*CS.getInstruction(),
610 createNode()->setHeapNodeMarker()->setModifiedMarker());
611 return;
612 } else if (F->getName() == "realloc") {
613 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
Chris Lattner82962de2004-11-03 18:51:26 +0000614 if (CS.arg_begin() != CS.arg_end())
615 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
Chris Lattnera07b72f2004-02-13 16:09:54 +0000616 if (DSNode *N = RetNH.getNode())
617 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
618 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000619 } else if (F->getName() == "memmove") {
620 // Merge the first & second arguments, and mark the memory read and
621 // modified.
622 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
623 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
624 if (DSNode *N = RetNH.getNode())
625 N->setModifiedMarker()->setReadMarker();
626 return;
627
Chris Lattnerd5612092004-02-24 22:02:48 +0000628 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000629 F->getName() == "atol" || F->getName() == "atoll" ||
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000630 F->getName() == "remove" || F->getName() == "unlink" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000631 F->getName() == "rename" || F->getName() == "memcmp" ||
632 F->getName() == "strcmp" || F->getName() == "strncmp" ||
633 F->getName() == "execl" || F->getName() == "execlp" ||
634 F->getName() == "execle" || F->getName() == "execv" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000635 F->getName() == "execvp" || F->getName() == "chmod" ||
636 F->getName() == "puts" || F->getName() == "write" ||
637 F->getName() == "open" || F->getName() == "create" ||
638 F->getName() == "truncate" || F->getName() == "chdir" ||
639 F->getName() == "mkdir" || F->getName() == "rmdir") {
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000640 // These functions read all of their pointer operands.
641 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
642 AI != E; ++AI) {
643 if (isPointerType((*AI)->getType()))
644 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000645 N->setReadMarker();
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000646 }
Chris Lattner304e1432004-02-16 22:57:19 +0000647 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000648 } else if (F->getName() == "read" || F->getName() == "pipe" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000649 F->getName() == "wait" || F->getName() == "time") {
Chris Lattner52fc8d72004-02-25 23:06:40 +0000650 // These functions write all of their pointer operands.
651 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
652 AI != E; ++AI) {
653 if (isPointerType((*AI)->getType()))
654 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000655 N->setModifiedMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000656 }
657 return;
Chris Lattneradc1efe2004-02-25 17:43:20 +0000658 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
659 F->getName() == "lstat") {
660 // These functions read their first operand if its a pointer.
661 CallSite::arg_iterator AI = CS.arg_begin();
662 if (isPointerType((*AI)->getType())) {
663 DSNodeHandle Path = getValueDest(**AI);
664 if (DSNode *N = Path.getNode()) N->setReadMarker();
665 }
Chris Lattner304e1432004-02-16 22:57:19 +0000666
Chris Lattneradc1efe2004-02-25 17:43:20 +0000667 // Then they write into the stat buffer.
668 DSNodeHandle StatBuf = getValueDest(**++AI);
669 if (DSNode *N = StatBuf.getNode()) {
670 N->setModifiedMarker();
671 const Type *StatTy = F->getFunctionType()->getParamType(1);
672 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
673 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
674 }
Chris Lattneradc1efe2004-02-25 17:43:20 +0000675 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000676 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
677 F->getName() == "strtold") {
678 // These functions read the first pointer
679 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
680 Str->setReadMarker();
681 // If the second parameter is passed, it will point to the first
682 // argument node.
683 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
684 if (DSNode *End = EndPtrNH.getNode()) {
685 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
686 EndPtrNH.getOffset(), false);
687 End->setModifiedMarker();
688 DSNodeHandle &Link = getLink(EndPtrNH);
689 Link.mergeWith(getValueDest(**CS.arg_begin()));
690 }
691 }
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000692 return;
Chris Lattner6b586df2004-02-27 20:04:48 +0000693 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
694 F->getName() == "freopen") {
695 // These functions read all of their pointer operands.
696 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
697 AI != E; ++AI)
698 if (isPointerType((*AI)->getType()))
699 if (DSNode *N = getValueDest(**AI).getNode())
700 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000701
Chris Lattner68300db2004-02-13 20:05:32 +0000702 // fopen allocates in an unknown way and writes to the file
703 // descriptor. Also, merge the allocated type into the node.
704 DSNodeHandle Result = getValueDest(*CS.getInstruction());
Chris Lattnerd5612092004-02-24 22:02:48 +0000705 if (DSNode *N = Result.getNode()) {
706 N->setModifiedMarker()->setUnknownNodeMarker();
707 const Type *RetTy = F->getFunctionType()->getReturnType();
708 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
709 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
710 }
Chris Lattner6b586df2004-02-27 20:04:48 +0000711
712 // If this is freopen, merge the file descriptor passed in with the
713 // result.
Chris Lattnerfe781652004-12-08 16:22:26 +0000714 if (F->getName() == "freopen") {
715 // ICC doesn't handle getting the iterator, decrementing and
716 // dereferencing it in one operation without error. Do it in 2 steps
717 CallSite::arg_iterator compit = CS.arg_end();
718 Result.mergeWith(getValueDest(**--compit));
719 }
Chris Lattnerd5612092004-02-24 22:02:48 +0000720 return;
Chris Lattner68300db2004-02-13 20:05:32 +0000721 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
722 // fclose reads and deallocates the memory in an unknown way for the
723 // file descriptor. It merges the FILE type into the descriptor.
724 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000725 if (DSNode *N = H.getNode()) {
726 N->setReadMarker()->setUnknownNodeMarker();
727 const Type *ArgTy = F->getFunctionType()->getParamType(0);
728 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
729 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
730 }
Chris Lattner68300db2004-02-13 20:05:32 +0000731 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000732 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
Chris Lattner304e1432004-02-16 22:57:19 +0000733 (F->getName() == "fflush" || F->getName() == "feof" ||
734 F->getName() == "fileno" || F->getName() == "clearerr" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000735 F->getName() == "rewind" || F->getName() == "ftell" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000736 F->getName() == "ferror" || F->getName() == "fgetc" ||
737 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
Chris Lattner304e1432004-02-16 22:57:19 +0000738 // fflush reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000739 // merges the FILE type into the descriptor.
740 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000741 if (DSNode *N = H.getNode()) {
742 N->setReadMarker()->setModifiedMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000743
Chris Lattnerd5612092004-02-24 22:02:48 +0000744 const Type *ArgTy = F->getFunctionType()->getParamType(0);
745 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
746 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
747 }
748 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000749 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
Chris Lattnerd5612092004-02-24 22:02:48 +0000750 (F->getName() == "fwrite" || F->getName() == "fread")) {
751 // fread writes the first operand, fwrite reads it. They both
752 // read/write the FILE descriptor, and merges the FILE type.
Chris Lattnerfe781652004-12-08 16:22:26 +0000753 CallSite::arg_iterator compit = CS.arg_end();
754 DSNodeHandle H = getValueDest(**--compit);
Chris Lattnerd5612092004-02-24 22:02:48 +0000755 if (DSNode *N = H.getNode()) {
756 N->setReadMarker()->setModifiedMarker();
757 const Type *ArgTy = F->getFunctionType()->getParamType(3);
758 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
759 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
760 }
761
762 H = getValueDest(**CS.arg_begin());
763 if (DSNode *N = H.getNode())
764 if (F->getName() == "fwrite")
765 N->setReadMarker();
766 else
767 N->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000768 return;
769 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
Chris Lattner304e1432004-02-16 22:57:19 +0000770 // fgets reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000771 // merges the FILE type into the descriptor, and writes to the
772 // argument. It returns the argument as well.
773 CallSite::arg_iterator AI = CS.arg_begin();
774 DSNodeHandle H = getValueDest(**AI);
775 if (DSNode *N = H.getNode())
776 N->setModifiedMarker(); // Writes buffer
777 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
778 ++AI; ++AI;
779
780 // Reads and writes file descriptor, merge in FILE type.
Chris Lattneradc1efe2004-02-25 17:43:20 +0000781 H = getValueDest(**AI);
Chris Lattnerd5612092004-02-24 22:02:48 +0000782 if (DSNode *N = H.getNode()) {
Chris Lattner339d8df2004-02-13 21:21:48 +0000783 N->setReadMarker()->setModifiedMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000784 const Type *ArgTy = F->getFunctionType()->getParamType(2);
785 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
786 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
787 }
788 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000789 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
790 F->getName() == "fputs" || F->getName() == "putc" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000791 F->getName() == "ftell" || F->getName() == "rewind" ||
792 F->getName() == "_IO_putc") {
793 // These functions read and write the memory for the file descriptor,
794 // which is passes as the last argument.
Chris Lattnerfe781652004-12-08 16:22:26 +0000795 CallSite::arg_iterator compit = CS.arg_end();
796 DSNodeHandle H = getValueDest(**--compit);
Chris Lattneradc1efe2004-02-25 17:43:20 +0000797 if (DSNode *N = H.getNode()) {
798 N->setReadMarker()->setModifiedMarker();
Chris Lattnerfe781652004-12-08 16:22:26 +0000799 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
800 const Type *ArgTy = *--compit2;
Chris Lattnerd5612092004-02-24 22:02:48 +0000801 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
802 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
803 }
Chris Lattner52fc8d72004-02-25 23:06:40 +0000804
805 // Any pointer arguments are read.
806 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
807 AI != E; ++AI)
808 if (isPointerType((*AI)->getType()))
809 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000810 N->setReadMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000811 return;
812 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
813 F->getName() == "fsetpos") {
814 // These functions read and write the memory for the file descriptor,
815 // and read/write all other arguments.
816 DSNodeHandle H = getValueDest(**CS.arg_begin());
817 if (DSNode *N = H.getNode()) {
Chris Lattnerfe781652004-12-08 16:22:26 +0000818 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
819 const Type *ArgTy = *--compit2;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000820 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
821 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
822 }
823
824 // Any pointer arguments are read.
825 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
826 AI != E; ++AI)
827 if (isPointerType((*AI)->getType()))
828 if (DSNode *N = getValueDest(**AI).getNode())
829 N->setReadMarker()->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000830 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000831 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
832 F->getName() == "sprintf") {
Chris Lattner339d8df2004-02-13 21:21:48 +0000833 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
834
835 if (F->getName() == "fprintf") {
836 // fprintf reads and writes the FILE argument, and applies the type
837 // to it.
838 DSNodeHandle H = getValueDest(**AI);
839 if (DSNode *N = H.getNode()) {
840 N->setModifiedMarker();
841 const Type *ArgTy = (*AI)->getType();
842 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
843 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
844 }
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000845 } else if (F->getName() == "sprintf") {
846 // sprintf writes the first string argument.
847 DSNodeHandle H = getValueDest(**AI++);
848 if (DSNode *N = H.getNode()) {
849 N->setModifiedMarker();
850 const Type *ArgTy = (*AI)->getType();
851 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
852 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
853 }
Chris Lattner339d8df2004-02-13 21:21:48 +0000854 }
855
856 for (; AI != E; ++AI) {
857 // printf reads all pointer arguments.
858 if (isPointerType((*AI)->getType()))
859 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000860 N->setReadMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000861 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000862 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000863 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
864 F->getName() == "vsprintf") {
865 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
866
867 if (F->getName() == "vfprintf") {
868 // ffprintf reads and writes the FILE argument, and applies the type
869 // to it.
870 DSNodeHandle H = getValueDest(**AI);
871 if (DSNode *N = H.getNode()) {
872 N->setModifiedMarker()->setReadMarker();
873 const Type *ArgTy = (*AI)->getType();
874 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
875 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
876 }
877 ++AI;
878 } else if (F->getName() == "vsprintf") {
879 // vsprintf writes the first string argument.
880 DSNodeHandle H = getValueDest(**AI++);
881 if (DSNode *N = H.getNode()) {
882 N->setModifiedMarker();
883 const Type *ArgTy = (*AI)->getType();
884 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
885 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
886 }
887 }
888
889 // Read the format
890 if (AI != E) {
891 if (isPointerType((*AI)->getType()))
892 if (DSNode *N = getValueDest(**AI).getNode())
893 N->setReadMarker();
894 ++AI;
895 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000896
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000897 // Read the valist, and the pointed-to objects.
898 if (AI != E && isPointerType((*AI)->getType())) {
899 const DSNodeHandle &VAList = getValueDest(**AI);
900 if (DSNode *N = VAList.getNode()) {
901 N->setReadMarker();
902 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
903 VAList.getOffset(), false);
904
905 DSNodeHandle &VAListObjs = getLink(VAList);
906 VAListObjs.getNode()->setReadMarker();
907 }
908 }
909
910 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000911 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
912 F->getName() == "sscanf") {
913 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
Chris Lattner339d8df2004-02-13 21:21:48 +0000914
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000915 if (F->getName() == "fscanf") {
916 // fscanf reads and writes the FILE argument, and applies the type
917 // to it.
918 DSNodeHandle H = getValueDest(**AI);
919 if (DSNode *N = H.getNode()) {
920 N->setReadMarker();
921 const Type *ArgTy = (*AI)->getType();
922 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
923 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
924 }
925 } else if (F->getName() == "sscanf") {
926 // sscanf reads the first string argument.
927 DSNodeHandle H = getValueDest(**AI++);
928 if (DSNode *N = H.getNode()) {
929 N->setReadMarker();
930 const Type *ArgTy = (*AI)->getType();
931 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
932 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
933 }
934 }
935
936 for (; AI != E; ++AI) {
937 // scanf writes all pointer arguments.
938 if (isPointerType((*AI)->getType()))
939 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000940 N->setModifiedMarker();
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000941 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000942 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000943 } else if (F->getName() == "strtok") {
944 // strtok reads and writes the first argument, returning it. It reads
945 // its second arg. FIXME: strtok also modifies some hidden static
946 // data. Someday this might matter.
947 CallSite::arg_iterator AI = CS.arg_begin();
948 DSNodeHandle H = getValueDest(**AI++);
949 if (DSNode *N = H.getNode()) {
950 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
951 const Type *ArgTy = F->getFunctionType()->getParamType(0);
952 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
953 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
954 }
955 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
956
957 H = getValueDest(**AI); // Reads delimiter
958 if (DSNode *N = H.getNode()) {
959 N->setReadMarker();
960 const Type *ArgTy = F->getFunctionType()->getParamType(1);
961 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
962 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
963 }
964 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000965 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
966 F->getName() == "strstr") {
967 // These read their arguments, and return the first one
Chris Lattneradc1efe2004-02-25 17:43:20 +0000968 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattner1fe98742004-02-26 03:43:08 +0000969 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
970
971 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
972 AI != E; ++AI)
973 if (isPointerType((*AI)->getType()))
974 if (DSNode *N = getValueDest(**AI).getNode())
975 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000976
Chris Lattneradc1efe2004-02-25 17:43:20 +0000977 if (DSNode *N = H.getNode())
978 N->setReadMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000979 return;
Chris Lattnerbeacefa2004-11-08 21:08:28 +0000980 } else if (F->getName() == "__assert_fail") {
981 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
982 AI != E; ++AI)
983 if (isPointerType((*AI)->getType()))
984 if (DSNode *N = getValueDest(**AI).getNode())
985 N->setReadMarker();
986 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000987 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
988 // This writes its second argument, and forces it to double.
Chris Lattnerfe781652004-12-08 16:22:26 +0000989 CallSite::arg_iterator compit = CS.arg_end();
990 DSNodeHandle H = getValueDest(**--compit);
Chris Lattner52fc8d72004-02-25 23:06:40 +0000991 if (DSNode *N = H.getNode()) {
992 N->setModifiedMarker();
993 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
994 }
995 return;
Andrew Lenharth24b1ea12006-03-15 03:43:59 +0000996 } else if (F->getName() == "strcat" || F->getName() == "strncat") {
997 //This might be making unsafe assumptions about usage
998 //Merge return and first arg
999 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
1000 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
1001 if (DSNode *N = RetNH.getNode())
1002 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
1003 //and read second pointer
1004 if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
1005 N->setReadMarker();
1006 return;
Chris Lattner339d8df2004-02-13 21:21:48 +00001007 } else {
Chris Lattner304e1432004-02-16 22:57:19 +00001008 // Unknown function, warn if it returns a pointer type or takes a
1009 // pointer argument.
1010 bool Warn = isPointerType(CS.getInstruction()->getType());
1011 if (!Warn)
1012 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1013 I != E; ++I)
1014 if (isPointerType((*I)->getType())) {
1015 Warn = true;
1016 break;
1017 }
1018 if (Warn)
1019 std::cerr << "WARNING: Call to unknown external function '"
1020 << F->getName() << "' will cause pessimistic results!\n";
Chris Lattnera07b72f2004-02-13 16:09:54 +00001021 }
Chris Lattner894263b2003-09-20 16:50:46 +00001022 }
1023
1024
Chris Lattnerc314ac42002-07-11 20:32:02 +00001025 // Set up the return value...
Chris Lattner0969c502002-10-21 02:08:03 +00001026 DSNodeHandle RetVal;
Chris Lattner808a7ae2003-09-20 16:34:13 +00001027 Instruction *I = CS.getInstruction();
1028 if (isPointerType(I->getType()))
1029 RetVal = getValueDest(*I);
Chris Lattnerc314ac42002-07-11 20:32:02 +00001030
Chris Lattnercb582402004-02-26 22:07:22 +00001031 DSNode *CalleeNode = 0;
1032 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
1033 CalleeNode = getValueDest(*Callee).getNode();
1034 if (CalleeNode == 0) {
1035 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
Chris Lattnerfbc2d842003-09-24 23:42:58 +00001036 return; // Calling a null pointer?
1037 }
1038 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001039
Chris Lattner0969c502002-10-21 02:08:03 +00001040 std::vector<DSNodeHandle> Args;
Chris Lattner808a7ae2003-09-20 16:34:13 +00001041 Args.reserve(CS.arg_end()-CS.arg_begin());
Chris Lattner0969c502002-10-21 02:08:03 +00001042
1043 // Calculate the arguments vector...
Chris Lattner808a7ae2003-09-20 16:34:13 +00001044 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1045 if (isPointerType((*I)->getType()))
1046 Args.push_back(getValueDest(**I));
Chris Lattner0969c502002-10-21 02:08:03 +00001047
1048 // Add a new function call entry...
Chris Lattnercb582402004-02-26 22:07:22 +00001049 if (CalleeNode)
1050 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
Chris Lattner923fc052003-02-05 21:59:58 +00001051 else
Chris Lattnercb582402004-02-26 22:07:22 +00001052 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
Chris Lattner26c4fc32003-09-20 21:48:16 +00001053 Args));
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001054}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001055
Vikram S. Advebac06222002-12-06 21:17:10 +00001056void GraphBuilder::visitFreeInst(FreeInst &FI) {
Vikram S. Advebac06222002-12-06 21:17:10 +00001057 // Mark that the node is written to...
Chris Lattnerd5612092004-02-24 22:02:48 +00001058 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
1059 N->setModifiedMarker()->setHeapNodeMarker();
Vikram S. Advebac06222002-12-06 21:17:10 +00001060}
1061
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001062/// Handle casts...
1063void GraphBuilder::visitCastInst(CastInst &CI) {
Chris Lattner5af344d2002-11-02 00:36:03 +00001064 if (isPointerType(CI.getType()))
1065 if (isPointerType(CI.getOperand(0)->getType())) {
Chris Lattner157b2522004-10-06 19:29:13 +00001066 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1067 if (Ptr.getNode() == 0) return;
1068
Chris Lattner5af344d2002-11-02 00:36:03 +00001069 // Cast one pointer to the other, just act like a copy instruction
Chris Lattner157b2522004-10-06 19:29:13 +00001070 setDestTo(CI, Ptr);
Chris Lattner5af344d2002-11-02 00:36:03 +00001071 } else {
1072 // Cast something (floating point, small integer) to a pointer. We need
1073 // to track the fact that the node points to SOMETHING, just something we
1074 // don't know about. Make an "Unknown" node.
1075 //
Chris Lattnerbd92b732003-06-19 21:15:11 +00001076 setDestTo(CI, createNode()->setUnknownNodeMarker());
Chris Lattner5af344d2002-11-02 00:36:03 +00001077 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001078}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001079
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001080
Chris Lattner878e5212003-02-04 00:59:50 +00001081// visitInstruction - For all other instruction types, if we have any arguments
1082// that are of pointer type, make them have unknown composition bits, and merge
1083// the nodes together.
1084void GraphBuilder::visitInstruction(Instruction &Inst) {
1085 DSNodeHandle CurNode;
1086 if (isPointerType(Inst.getType()))
1087 CurNode = getValueDest(Inst);
1088 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1089 if (isPointerType((*I)->getType()))
1090 CurNode.mergeWith(getValueDest(**I));
1091
Chris Lattner62c3a952004-10-30 04:22:45 +00001092 if (DSNode *N = CurNode.getNode())
1093 N->setUnknownNodeMarker();
Chris Lattner878e5212003-02-04 00:59:50 +00001094}
1095
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001096
1097
1098//===----------------------------------------------------------------------===//
1099// LocalDataStructures Implementation
1100//===----------------------------------------------------------------------===//
1101
Chris Lattner26c4fc32003-09-20 21:48:16 +00001102// MergeConstantInitIntoNode - Merge the specified constant into the node
1103// pointed to by NH.
1104void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1105 // Ensure a type-record exists...
Chris Lattner62c3a952004-10-30 04:22:45 +00001106 DSNode *NHN = NH.getNode();
1107 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
Chris Lattner26c4fc32003-09-20 21:48:16 +00001108
1109 if (C->getType()->isFirstClassType()) {
1110 if (isPointerType(C->getType()))
1111 // Avoid adding edges from null, or processing non-"pointer" stores
1112 NH.addEdgeTo(getValueDest(*C));
1113 return;
1114 }
Chris Lattner15869aa2003-11-02 22:27:28 +00001115
1116 const TargetData &TD = NH.getNode()->getTargetData();
1117
Chris Lattner26c4fc32003-09-20 21:48:16 +00001118 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1119 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1120 // We don't currently do any indexing for arrays...
1121 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1122 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1123 const StructLayout *SL = TD.getStructLayout(CS->getType());
1124 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattner62c3a952004-10-30 04:22:45 +00001125 DSNode *NHN = NH.getNode();
Andrew Lenharth99c19422006-04-13 19:31:49 +00001126 //Some programmers think ending a structure with a [0 x sbyte] is cute
1127 //This should be ok as the allocation type should grow this type when
1128 //it is merged in if it is bigger.
1129 if (SL->MemberOffsets[i] < SL->StructSize) {
1130 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1131 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1132 } else if (SL->MemberOffsets[i] == SL->StructSize) {
1133 DEBUG(std::cerr << "Zero size element at end of struct\n");
1134 } else {
1135 assert(0 && "type was smaller than offsets of of struct layout indicate");
1136 }
Chris Lattner26c4fc32003-09-20 21:48:16 +00001137 }
Chris Lattner48b2f6b2004-10-26 16:23:03 +00001138 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
Chris Lattner896481e2004-02-15 05:53:42 +00001139 // Noop
Chris Lattner26c4fc32003-09-20 21:48:16 +00001140 } else {
1141 assert(0 && "Unknown constant type!");
1142 }
1143}
1144
1145void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1146 assert(!GV->isExternal() && "Cannot merge in external global!");
1147 // Get a node handle to the global node and merge the initializer into it.
1148 DSNodeHandle NH = getValueDest(*GV);
1149 MergeConstantInitIntoNode(NH, GV->getInitializer());
1150}
1151
1152
Chris Lattner9b426bd2005-03-20 03:32:35 +00001153/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1154/// contains multiple globals, DSA will never, ever, be able to tell the globals
1155/// apart. Instead of maintaining this information in all of the graphs
1156/// throughout the entire program, store only a single global (the "leader") in
1157/// the graphs, and build equivalence classes for the rest of the globals.
1158static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1159 DSScalarMap &SM = GG.getScalarMap();
1160 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1161 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1162 I != E; ++I) {
1163 if (I->getGlobalsList().size() <= 1) continue;
1164
1165 // First, build up the equivalence set for this block of globals.
1166 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1167 GlobalValue *First = GVs[0];
1168 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1169 GlobalECs.unionSets(First, GVs[i]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001170
Chris Lattner9b426bd2005-03-20 03:32:35 +00001171 // Next, get the leader element.
1172 assert(First == GlobalECs.getLeaderValue(First) &&
1173 "First did not end up being the leader?");
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001174
Chris Lattner9b426bd2005-03-20 03:32:35 +00001175 // Next, remove all globals from the scalar map that are not the leader.
1176 assert(GVs[0] == First && "First had to be at the front!");
1177 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1178 ECGlobals.insert(GVs[i]);
1179 SM.erase(SM.find(GVs[i]));
1180 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001181
Chris Lattner9b426bd2005-03-20 03:32:35 +00001182 // Finally, change the global node to only contain the leader.
1183 I->clearGlobals();
1184 I->addGlobal(First);
1185 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001186
Chris Lattner9b426bd2005-03-20 03:32:35 +00001187 DEBUG(GG.AssertGraphOK());
1188}
1189
1190/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1191/// really just equivalent to some other globals, remove the globals from the
1192/// specified DSGraph (if present), and merge any nodes with their leader nodes.
1193static void EliminateUsesOfECGlobals(DSGraph &G,
1194 const std::set<GlobalValue*> &ECGlobals) {
1195 DSScalarMap &SM = G.getScalarMap();
1196 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1197
1198 bool MadeChange = false;
1199 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1200 GI != E; ) {
1201 GlobalValue *GV = *GI++;
1202 if (!ECGlobals.count(GV)) continue;
1203
1204 const DSNodeHandle &GVNH = SM[GV];
1205 assert(!GVNH.isNull() && "Global has null NH!?");
1206
1207 // Okay, this global is in some equivalence class. Start by finding the
1208 // leader of the class.
1209 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1210
1211 // If the leader isn't already in the graph, insert it into the node
1212 // corresponding to GV.
1213 if (!SM.global_count(Leader)) {
1214 GVNH.getNode()->addGlobal(Leader);
1215 SM[Leader] = GVNH;
1216 } else {
1217 // Otherwise, the leader is in the graph, make sure the nodes are the
1218 // merged in the specified graph.
1219 const DSNodeHandle &LNH = SM[Leader];
1220 if (LNH.getNode() != GVNH.getNode())
1221 LNH.mergeWith(GVNH);
1222 }
1223
1224 // Next step, remove the global from the DSNode.
1225 GVNH.getNode()->removeGlobal(GV);
1226
1227 // Finally, remove the global from the ScalarMap.
1228 SM.erase(GV);
1229 MadeChange = true;
1230 }
1231
1232 DEBUG(if(MadeChange) G.AssertGraphOK());
1233}
1234
Chris Lattnerb12914b2004-09-20 04:48:05 +00001235bool LocalDataStructures::runOnModule(Module &M) {
Chris Lattner15869aa2003-11-02 22:27:28 +00001236 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattneraa0b4682002-11-09 21:12:07 +00001237
Chris Lattnerf4f62272005-03-19 22:23:45 +00001238 // First step, build the globals graph.
1239 GlobalsGraph = new DSGraph(GlobalECs, TD);
Chris Lattnerc420ab62004-02-25 23:31:02 +00001240 {
1241 GraphBuilder GGB(*GlobalsGraph);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001242
Chris Lattnerf4f62272005-03-19 22:23:45 +00001243 // Add initializers for all of the globals to the globals graph.
1244 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1245 I != E; ++I)
Chris Lattnerc420ab62004-02-25 23:31:02 +00001246 if (!I->isExternal())
1247 GGB.mergeInGlobalInitializer(I);
1248 }
1249
Chris Lattnerf4f62272005-03-19 22:23:45 +00001250 // Next step, iterate through the nodes in the globals graph, unioning
1251 // together the globals into equivalence classes.
Chris Lattner9b426bd2005-03-20 03:32:35 +00001252 std::set<GlobalValue*> ECGlobals;
1253 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1254 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1255 ECGlobals.clear();
Chris Lattnerf4f62272005-03-19 22:23:45 +00001256
Chris Lattneraa0b4682002-11-09 21:12:07 +00001257 // Calculate all of the graphs...
1258 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1259 if (!I->isExternal())
Chris Lattnerf4f62272005-03-19 22:23:45 +00001260 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1261 GlobalsGraph)));
Chris Lattner26c4fc32003-09-20 21:48:16 +00001262
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001263 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner26c4fc32003-09-20 21:48:16 +00001264 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner9b426bd2005-03-20 03:32:35 +00001265
1266 // Now that we've computed all of the graphs, and merged all of the info into
1267 // the globals graph, see if we have further constrained the globals in the
1268 // program if so, update GlobalECs and remove the extraneous globals from the
1269 // program.
1270 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1271 if (!ECGlobals.empty()) {
1272 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1273 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1274 E = DSInfo.end(); I != E; ++I)
1275 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1276 }
1277
Chris Lattneraa0b4682002-11-09 21:12:07 +00001278 return false;
1279}
1280
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001281// releaseMemory - If the pass pipeline is done with this pass, we can release
1282// our memory... here...
1283//
1284void LocalDataStructures::releaseMemory() {
Chris Lattner81d924d2003-06-30 04:53:27 +00001285 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1286 E = DSInfo.end(); I != E; ++I) {
1287 I->second->getReturnNodes().erase(I->first);
1288 if (I->second->getReturnNodes().empty())
1289 delete I->second;
1290 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001291
1292 // Empty map so next time memory is released, data structures are not
1293 // re-deleted.
1294 DSInfo.clear();
Chris Lattner2e4f9bf2002-11-09 20:01:01 +00001295 delete GlobalsGraph;
1296 GlobalsGraph = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001297}
Brian Gaeked0fde302003-11-11 22:41:34 +00001298