blob: 2542fd01962c9c3f5f463ec22966ef8f16ba8e6b [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 Lattner5d8925c2006-08-27 22:30:17 +000036static RegisterPass<LocalDataStructures>
Chris Lattner97f51a32002-07-27 01:12:15 +000037X("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
Andrew Lenharth118c0942006-11-03 17:43:19 +0000134 bool visitIntrinsic(CallSite CS, Function* F);
135 bool visitExternal(CallSite CS, Function* F);
Chris Lattner808a7ae2003-09-20 16:34:13 +0000136 void visitCallSite(CallSite CS);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000137 void visitVAArgInst(VAArgInst &I);
Chris Lattner26c4fc32003-09-20 21:48:16 +0000138
139 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000140 private:
141 // Helper functions used to implement the visitation functions...
142
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000143 /// createNode - Create a new DSNode, ensuring that it is properly added to
144 /// the graph.
145 ///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000146 DSNode *createNode(const Type *Ty = 0) {
147 DSNode *N = new DSNode(Ty, &G); // Create the node
Chris Lattnere158b192003-06-16 12:08:18 +0000148 if (DisableFieldSensitivity) {
Chris Lattner2412a052004-05-23 21:14:09 +0000149 // Create node handle referring to the old node so that it is
150 // immediately removed from the graph when the node handle is destroyed.
151 DSNodeHandle OldNNH = N;
Chris Lattnerca3f7902003-02-08 20:18:39 +0000152 N->foldNodeCompletely();
Chris Lattnere158b192003-06-16 12:08:18 +0000153 if (DSNode *FN = N->getForwardNode())
154 N = FN;
155 }
Chris Lattner92673292002-11-02 00:13:20 +0000156 return N;
157 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000158
Chris Lattnerc875f022002-11-03 21:27:48 +0000159 /// setDestTo - Set the ScalarMap entry for the specified value to point to
Chris Lattner92673292002-11-02 00:13:20 +0000160 /// the specified destination. If the Value already points to a node, make
161 /// sure to merge the two destinations together.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000162 ///
Chris Lattner92673292002-11-02 00:13:20 +0000163 void setDestTo(Value &V, const DSNodeHandle &NH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000164
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000165 /// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000166 ///
Chris Lattner92673292002-11-02 00:13:20 +0000167 DSNodeHandle getValueDest(Value &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000168
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000169 /// getLink - This method is used to return the specified link in the
170 /// specified node if one exists. If a link does not already exist (it's
Chris Lattner7e51c872002-10-31 06:52:26 +0000171 /// null), then we create a new node, link it, then return it.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000172 ///
Chris Lattner7e51c872002-10-31 06:52:26 +0000173 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000174 };
175}
176
Brian Gaeked0fde302003-11-11 22:41:34 +0000177using namespace DS;
178
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000179//===----------------------------------------------------------------------===//
180// DSGraph constructor - Simply use the GraphBuilder to construct the local
181// graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000182DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
183 Function &F, DSGraph *GG)
184 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
Chris Lattner2a068862002-11-10 06:53:38 +0000185 PrintAuxCalls = false;
Chris Lattner30514192003-07-02 04:37:26 +0000186
187 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
188
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000189 // Use the graph builder to construct the local version of the graph
Chris Lattner26c4fc32003-09-20 21:48:16 +0000190 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
Chris Lattner4fe34612002-11-18 21:44:19 +0000191#ifndef NDEBUG
192 Timer::addPeakMemoryMeasurement();
193#endif
Chris Lattner1a1a85d2003-02-14 04:55:58 +0000194
Chris Lattnerc420ab62004-02-25 23:31:02 +0000195 // If there are any constant globals referenced in this function, merge their
196 // initializers into the local graph from the globals graph.
197 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
198 ReachabilityCloner RC(*this, *GG, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000199
Chris Lattnerc420ab62004-02-25 23:31:02 +0000200 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
201 I != ScalarMap.global_end(); ++I)
202 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattner76a9eb32004-03-03 23:00:19 +0000203 if (!GV->isExternal() && GV->isConstant())
Chris Lattnerc420ab62004-02-25 23:31:02 +0000204 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
205 }
206
Chris Lattner394471f2003-01-23 22:05:33 +0000207 markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner96517252002-11-09 20:55:24 +0000208
209 // Remove any nodes made dead due to merging...
Chris Lattner394471f2003-01-23 22:05:33 +0000210 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000211}
212
213
214//===----------------------------------------------------------------------===//
215// Helper method implementations...
216//
217
Chris Lattner92673292002-11-02 00:13:20 +0000218/// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000219///
Chris Lattner51340062002-11-08 05:00:44 +0000220DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
221 Value *V = &Val;
Chris Lattner82962de2004-11-03 18:51:26 +0000222 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
Chris Lattner51340062002-11-08 05:00:44 +0000223 return 0; // Null doesn't point to anything, don't add to ScalarMap!
Chris Lattner92673292002-11-02 00:13:20 +0000224
Vikram S. Advebac06222002-12-06 21:17:10 +0000225 DSNodeHandle &NH = ScalarMap[V];
Chris Lattner62c3a952004-10-30 04:22:45 +0000226 if (!NH.isNull())
Vikram S. Advebac06222002-12-06 21:17:10 +0000227 return NH; // Already have a node? Just return it...
228
229 // Otherwise we need to create a new node to point to.
230 // Check first for constant expressions that must be traversed to
231 // extract the actual value.
Reid Spencere8404342004-07-18 00:18:30 +0000232 DSNode* N;
233 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
Chris Lattner48427b52005-03-20 01:18:00 +0000234 // Create a new global node for this global variable.
Reid Spencere8404342004-07-18 00:18:30 +0000235 N = createNode(GV->getType()->getElementType());
236 N->addGlobal(GV);
237 } else if (Constant *C = dyn_cast<Constant>(V)) {
238 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnera513fb12005-03-22 02:45:13 +0000239 if (CE->getOpcode() == Instruction::Cast) {
240 if (isa<PointerType>(CE->getOperand(0)->getType()))
241 NH = getValueDest(*CE->getOperand(0));
242 else
243 NH = createNode()->setUnknownNodeMarker();
244 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner51340062002-11-08 05:00:44 +0000245 visitGetElementPtrInst(*CE);
Chris Lattner62482e52004-01-28 09:15:42 +0000246 DSScalarMap::iterator I = ScalarMap.find(CE);
Chris Lattner2cfbaaf2002-11-09 20:14:03 +0000247 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
Chris Lattner1e56c542003-02-09 23:04:12 +0000248 NH = I->second;
249 } else {
250 // This returns a conservative unknown node for any unhandled ConstExpr
Chris Lattnerbd92b732003-06-19 21:15:11 +0000251 return NH = createNode()->setUnknownNodeMarker();
Chris Lattner51340062002-11-08 05:00:44 +0000252 }
Chris Lattner62c3a952004-10-30 04:22:45 +0000253 if (NH.isNull()) { // (getelementptr null, X) returns null
Chris Lattner1e56c542003-02-09 23:04:12 +0000254 ScalarMap.erase(V);
255 return 0;
256 }
257 return NH;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000258 } else if (isa<UndefValue>(C)) {
259 ScalarMap.erase(V);
260 return 0;
Chris Lattner51340062002-11-08 05:00:44 +0000261 } else {
262 assert(0 && "Unknown constant type!");
263 }
Reid Spencere8404342004-07-18 00:18:30 +0000264 N = createNode(); // just create a shadow node
Chris Lattner92673292002-11-02 00:13:20 +0000265 } else {
266 // Otherwise just create a shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000267 N = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000268 }
269
Chris Lattnerefffdc92004-07-07 06:12:52 +0000270 NH.setTo(N, 0); // Remember that we are pointing to it...
Chris Lattner92673292002-11-02 00:13:20 +0000271 return NH;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000272}
273
Chris Lattner0d9bab82002-07-18 00:12:30 +0000274
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000275/// getLink - This method is used to return the specified link in the
276/// specified node if one exists. If a link does not already exist (it's
277/// null), then we create a new node, link it, then return it. We must
278/// specify the type of the Node field we are accessing so that we know what
279/// type should be linked to if we need to create a new node.
280///
Chris Lattner7e51c872002-10-31 06:52:26 +0000281DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000282 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
Chris Lattner08db7192002-11-06 06:20:27 +0000283 DSNodeHandle &Link = Node.getLink(LinkNo);
Chris Lattner62c3a952004-10-30 04:22:45 +0000284 if (Link.isNull()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000285 // If the link hasn't been created yet, make and return a new shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000286 Link = createNode();
Chris Lattner08db7192002-11-06 06:20:27 +0000287 }
288 return Link;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000289}
290
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000291
Chris Lattnerc875f022002-11-03 21:27:48 +0000292/// setDestTo - Set the ScalarMap entry for the specified value to point to the
Chris Lattner92673292002-11-02 00:13:20 +0000293/// specified destination. If the Value already points to a node, make sure to
294/// merge the two destinations together.
295///
296void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000297 ScalarMap[&V].mergeWith(NH);
Chris Lattner92673292002-11-02 00:13:20 +0000298}
299
300
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000301//===----------------------------------------------------------------------===//
302// Specific instruction type handler implementations...
303//
304
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000305/// Alloca & Malloc instruction implementation - Simply create a new memory
306/// object, pointing the scalar to it.
307///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000308void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
309 DSNode *N = createNode();
310 if (isHeap)
311 N->setHeapNodeMarker();
312 else
313 N->setAllocaNodeMarker();
314 setDestTo(AI, N);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000315}
316
317// PHINode - Make the scalar for the PHI node point to all of the things the
318// incoming values point to... which effectively causes them to be merged.
319//
320void GraphBuilder::visitPHINode(PHINode &PN) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000321 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000322
Chris Lattnerc875f022002-11-03 21:27:48 +0000323 DSNodeHandle &PNDest = ScalarMap[&PN];
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000324 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
Chris Lattner92673292002-11-02 00:13:20 +0000325 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000326}
327
Chris Lattner6e84bd72005-02-25 01:27:48 +0000328void GraphBuilder::visitSelectInst(SelectInst &SI) {
329 if (!isPointerType(SI.getType())) return; // Only pointer Selects
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000330
Chris Lattner6e84bd72005-02-25 01:27:48 +0000331 DSNodeHandle &Dest = ScalarMap[&SI];
332 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
333 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
334}
335
Chris Lattner32672652005-03-05 19:04:31 +0000336void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
337 if (!isPointerType(SCI.getOperand(0)->getType()) ||
338 isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
339 ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
340}
341
342
Chris Lattner51340062002-11-08 05:00:44 +0000343void GraphBuilder::visitGetElementPtrInst(User &GEP) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000344 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
Chris Lattner753b1132005-02-24 19:55:31 +0000345 if (Value.isNull())
346 Value = createNode();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000347
Chris Lattner179bc7d2003-11-14 17:09:46 +0000348 // As a special case, if all of the index operands of GEP are constant zeros,
349 // handle this just like we handle casts (ie, don't do much).
350 bool AllZeros = true;
351 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
352 if (GEP.getOperand(i) !=
353 Constant::getNullValue(GEP.getOperand(i)->getType())) {
354 AllZeros = false;
355 break;
356 }
357
358 // If all of the indices are zero, the result points to the operand without
359 // applying the type.
Chris Lattner0c9707a2005-03-18 23:18:20 +0000360 if (AllZeros || (!Value.isNull() &&
361 Value.getNode()->isNodeCompletelyFolded())) {
Chris Lattner179bc7d2003-11-14 17:09:46 +0000362 setDestTo(GEP, Value);
363 return;
364 }
365
366
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000367 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
368 const Type *CurTy = PTy->getElementType();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000369
Chris Lattner08db7192002-11-06 06:20:27 +0000370 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
371 // If the node had to be folded... exit quickly
Chris Lattner92673292002-11-02 00:13:20 +0000372 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000373 return;
374 }
375
Chris Lattner15869aa2003-11-02 22:27:28 +0000376 const TargetData &TD = Value.getNode()->getTargetData();
377
Chris Lattner08db7192002-11-06 06:20:27 +0000378#if 0
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000379 // Handle the pointer index specially...
380 if (GEP.getNumOperands() > 1 &&
Chris Lattner28977af2004-04-05 01:30:19 +0000381 (!isa<Constant>(GEP.getOperand(1)) ||
382 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000383
384 // If we already know this is an array being accessed, don't do anything...
385 if (!TopTypeRec.isArray) {
386 TopTypeRec.isArray = true;
387
388 // If we are treating some inner field pointer as an array, fold the node
389 // up because we cannot handle it right. This can come because of
390 // something like this: &((&Pt->X)[1]) == &Pt->Y
391 //
392 if (Value.getOffset()) {
393 // Value is now the pointer we want to GEP to be...
394 Value.getNode()->foldNodeCompletely();
Chris Lattner92673292002-11-02 00:13:20 +0000395 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000396 return;
397 } else {
398 // This is a pointer to the first byte of the node. Make sure that we
399 // are pointing to the outter most type in the node.
400 // FIXME: We need to check one more case here...
401 }
402 }
403 }
Chris Lattner08db7192002-11-06 06:20:27 +0000404#endif
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000405
406 // All of these subscripts are indexing INTO the elements we have...
Chris Lattner26c4fc32003-09-20 21:48:16 +0000407 unsigned Offset = 0;
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000408 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
409 I != E; ++I)
410 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Andrew Lenharth118c0942006-11-03 17:43:19 +0000411 const ConstantInt* CUI = cast<ConstantInt>(I.getOperand());
412 unsigned FieldNo =
413 CUI->getType()->isSigned() ? CUI->getSExtValue() : CUI->getZExtValue();
Chris Lattner507bdf92005-01-12 04:51:37 +0000414 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
Reid Spencer3ed469c2006-11-02 20:25:50 +0000415 } else if (isa<PointerType>(*I)) {
Chris Lattner82e9d722004-03-01 19:02:54 +0000416 if (!isa<Constant>(I.getOperand()) ||
417 !cast<Constant>(I.getOperand())->isNullValue())
418 Value.getNode()->setArrayMarker();
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000419 }
420
421
Chris Lattner08db7192002-11-06 06:20:27 +0000422#if 0
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000423 if (const SequentialType *STy = cast<SequentialType>(*I)) {
424 CurTy = STy->getElementType();
Jim Laskey978b35e2006-10-23 14:39:22 +0000425 if (ConstantInt *CS = dyn_cast<ConstantInt>(GEP.getOperand(i))) {
Andrew Lenharth118c0942006-11-03 17:43:19 +0000426 Offset +=
427 (CS->getType()->isSigned() ? CS->getSExtValue() : CS->getZExtValue())
428 * TD.getTypeSize(CurTy);
Chris Lattnere03f32b2002-10-02 06:24:36 +0000429 } else {
430 // Variable index into a node. We must merge all of the elements of the
431 // sequential type here.
432 if (isa<PointerType>(STy))
433 std::cerr << "Pointer indexing not handled yet!\n";
434 else {
435 const ArrayType *ATy = cast<ArrayType>(STy);
436 unsigned ElSize = TD.getTypeSize(CurTy);
437 DSNode *N = Value.getNode();
438 assert(N && "Value must have a node!");
439 unsigned RawOffset = Offset+Value.getOffset();
440
441 // Loop over all of the elements of the array, merging them into the
Misha Brukman2f2d0652003-09-11 18:14:24 +0000442 // zeroth element.
Chris Lattnere03f32b2002-10-02 06:24:36 +0000443 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
444 // Merge all of the byte components of this array element
445 for (unsigned j = 0; j != ElSize; ++j)
446 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
447 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000448 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000449 }
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000450#endif
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000451
452 // Add in the offset calculated...
453 Value.setOffset(Value.getOffset()+Offset);
454
Sumant Kowshik8a3802d2005-12-06 18:04:30 +0000455 // Check the offset
456 DSNode *N = Value.getNode();
457 if (N &&
458 !N->isNodeCompletelyFolded() &&
459 (N->getSize() != 0 || Offset != 0) &&
460 !N->isForwarding()) {
461 if ((Offset >= N->getSize()) || int(Offset) < 0) {
462 // Accessing offsets out of node size range
463 // This is seen in the "magic" struct in named (from bind), where the
464 // fourth field is an array of length 0, presumably used to create struct
465 // instances of different sizes
466
467 // Collapse the node since its size is now variable
468 N->foldNodeCompletely();
469 }
470 }
471
472 // Value is now the pointer we want to GEP to be...
Chris Lattner92673292002-11-02 00:13:20 +0000473 setDestTo(GEP, Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000474}
475
476void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattner92673292002-11-02 00:13:20 +0000477 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
Chris Lattner6e84bd72005-02-25 01:27:48 +0000478 if (Ptr.isNull())
479 Ptr = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000480
481 // Make that the node is read from...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000482 Ptr.getNode()->setReadMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000483
484 // Ensure a typerecord exists...
Chris Lattner088b6392003-03-03 17:13:31 +0000485 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
Chris Lattner92673292002-11-02 00:13:20 +0000486
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000487 if (isPointerType(LI.getType()))
Chris Lattner92673292002-11-02 00:13:20 +0000488 setDestTo(LI, getLink(Ptr));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000489}
490
491void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000492 const Type *StoredTy = SI.getOperand(0)->getType();
Chris Lattner92673292002-11-02 00:13:20 +0000493 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000494 if (Dest.isNull()) return;
Chris Lattner92673292002-11-02 00:13:20 +0000495
Vikram S. Advebac06222002-12-06 21:17:10 +0000496 // Mark that the node is written to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000497 Dest.getNode()->setModifiedMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000498
Chris Lattner26c4fc32003-09-20 21:48:16 +0000499 // Ensure a type-record exists...
Chris Lattner08db7192002-11-06 06:20:27 +0000500 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000501
502 // Avoid adding edges from null, or processing non-"pointer" stores
Chris Lattner92673292002-11-02 00:13:20 +0000503 if (isPointerType(StoredTy))
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000504 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000505}
506
507void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattner92673292002-11-02 00:13:20 +0000508 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
Chris Lattner26c4fc32003-09-20 21:48:16 +0000509 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000510}
511
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000512void GraphBuilder::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +0000513 //FIXME: also updates the argument
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000514 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
515 if (Ptr.isNull()) return;
516
517 // Make that the node is read from.
518 Ptr.getNode()->setReadMarker();
519
Chris Lattner62c3a952004-10-30 04:22:45 +0000520 // Ensure a type record exists.
521 DSNode *PtrN = Ptr.getNode();
522 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000523
524 if (isPointerType(I.getType()))
525 setDestTo(I, getLink(Ptr));
526}
527
528
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000529void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000530 visitCallSite(&CI);
531}
532
533void GraphBuilder::visitInvokeInst(InvokeInst &II) {
534 visitCallSite(&II);
535}
536
Andrew Lenharth118c0942006-11-03 17:43:19 +0000537/// returns true if the intrinsic is handled
538bool GraphBuilder::visitIntrinsic(CallSite CS, Function *F) {
539 switch (F->getIntrinsicID()) {
540 case Intrinsic::vastart:
541 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
542 return true;
543 case Intrinsic::vacopy:
544 getValueDest(*CS.getInstruction()).
545 mergeWith(getValueDest(**(CS.arg_begin())));
546 return true;
547 case Intrinsic::vaend:
548 case Intrinsic::dbg_func_start:
549 case Intrinsic::dbg_region_end:
550 case Intrinsic::dbg_stoppoint:
551 return true; // noop
552 case Intrinsic::memcpy_i32:
553 case Intrinsic::memcpy_i64:
554 case Intrinsic::memmove_i32:
555 case Intrinsic::memmove_i64: {
556 // Merge the first & second arguments, and mark the memory read and
557 // modified.
558 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
559 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
560 if (DSNode *N = RetNH.getNode())
561 N->setModifiedMarker()->setReadMarker();
562 return true;
563 }
564 case Intrinsic::memset_i32:
565 case Intrinsic::memset_i64:
566 // Mark the memory modified.
567 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
568 N->setModifiedMarker();
569 return true;
570 default:
571 DEBUG(std::cerr << "[dsa:local] Unhandled intrinsic: " << F->getName() << "\n");
572 return false;
573 }
574}
575
576/// returns true if the external is a recognized libc function with a
577/// known (and generated) graph
578bool GraphBuilder::visitExternal(CallSite CS, Function *F) {
579 if (F->getName() == "calloc"
580 || F->getName() == "posix_memalign"
581 || F->getName() == "memalign" || F->getName() == "valloc") {
582 setDestTo(*CS.getInstruction(),
583 createNode()->setHeapNodeMarker()->setModifiedMarker());
584 return true;
585 } else if (F->getName() == "realloc") {
586 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
587 if (CS.arg_begin() != CS.arg_end())
588 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
589 if (DSNode *N = RetNH.getNode())
590 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
591 return true;
592 } else if (F->getName() == "memmove") {
593 // Merge the first & second arguments, and mark the memory read and
594 // modified.
595 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
596 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
597 if (DSNode *N = RetNH.getNode())
598 N->setModifiedMarker()->setReadMarker();
599 return true;
600 } else if (F->getName() == "free") {
601 // Mark that the node is written to...
602 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
603 N->setModifiedMarker()->setHeapNodeMarker();
604 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
605 F->getName() == "atol" || F->getName() == "atoll" ||
606 F->getName() == "remove" || F->getName() == "unlink" ||
607 F->getName() == "rename" || F->getName() == "memcmp" ||
608 F->getName() == "strcmp" || F->getName() == "strncmp" ||
609 F->getName() == "execl" || F->getName() == "execlp" ||
610 F->getName() == "execle" || F->getName() == "execv" ||
611 F->getName() == "execvp" || F->getName() == "chmod" ||
612 F->getName() == "puts" || F->getName() == "write" ||
613 F->getName() == "open" || F->getName() == "create" ||
614 F->getName() == "truncate" || F->getName() == "chdir" ||
615 F->getName() == "mkdir" || F->getName() == "rmdir" ||
616 F->getName() == "strlen") {
617 // These functions read all of their pointer operands.
618 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
619 AI != E; ++AI) {
620 if (isPointerType((*AI)->getType()))
621 if (DSNode *N = getValueDest(**AI).getNode())
622 N->setReadMarker();
623 }
624 return true;
625 } else if (F->getName() == "memchr") {
626 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
627 DSNodeHandle Result = getValueDest(*CS.getInstruction());
628 RetNH.mergeWith(Result);
629 if (DSNode *N = RetNH.getNode())
630 N->setReadMarker();
631 return true;
632 } else if (F->getName() == "read" || F->getName() == "pipe" ||
633 F->getName() == "wait" || F->getName() == "time" ||
634 F->getName() == "getrusage") {
635 // These functions write all of their pointer operands.
636 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
637 AI != E; ++AI) {
638 if (isPointerType((*AI)->getType()))
639 if (DSNode *N = getValueDest(**AI).getNode())
640 N->setModifiedMarker();
641 }
642 return true;
643 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
644 F->getName() == "lstat") {
645 // These functions read their first operand if its a pointer.
646 CallSite::arg_iterator AI = CS.arg_begin();
647 if (isPointerType((*AI)->getType())) {
648 DSNodeHandle Path = getValueDest(**AI);
649 if (DSNode *N = Path.getNode()) N->setReadMarker();
650 }
651
652 // Then they write into the stat buffer.
653 DSNodeHandle StatBuf = getValueDest(**++AI);
654 if (DSNode *N = StatBuf.getNode()) {
655 N->setModifiedMarker();
656 const Type *StatTy = F->getFunctionType()->getParamType(1);
657 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
658 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
659 }
660 return true;
661 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
662 F->getName() == "strtold") {
663 // These functions read the first pointer
664 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
665 Str->setReadMarker();
666 // If the second parameter is passed, it will point to the first
667 // argument node.
668 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
669 if (DSNode *End = EndPtrNH.getNode()) {
670 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
671 EndPtrNH.getOffset(), false);
672 End->setModifiedMarker();
673 DSNodeHandle &Link = getLink(EndPtrNH);
674 Link.mergeWith(getValueDest(**CS.arg_begin()));
675 }
676 }
677 return true;
678 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
679 F->getName() == "freopen") {
680 // These functions read all of their pointer operands.
681 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
682 AI != E; ++AI)
683 if (isPointerType((*AI)->getType()))
684 if (DSNode *N = getValueDest(**AI).getNode())
685 N->setReadMarker();
686
687 // fopen allocates in an unknown way and writes to the file
688 // descriptor. Also, merge the allocated type into the node.
689 DSNodeHandle Result = getValueDest(*CS.getInstruction());
690 if (DSNode *N = Result.getNode()) {
691 N->setModifiedMarker()->setUnknownNodeMarker();
692 const Type *RetTy = F->getFunctionType()->getReturnType();
693 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
694 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
695 }
696
697 // If this is freopen, merge the file descriptor passed in with the
698 // result.
699 if (F->getName() == "freopen") {
700 // ICC doesn't handle getting the iterator, decrementing and
701 // dereferencing it in one operation without error. Do it in 2 steps
702 CallSite::arg_iterator compit = CS.arg_end();
703 Result.mergeWith(getValueDest(**--compit));
704 }
705 return true;
706 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
707 // fclose reads and deallocates the memory in an unknown way for the
708 // file descriptor. It merges the FILE type into the descriptor.
709 DSNodeHandle H = getValueDest(**CS.arg_begin());
710 if (DSNode *N = H.getNode()) {
711 N->setReadMarker()->setUnknownNodeMarker();
712 const Type *ArgTy = F->getFunctionType()->getParamType(0);
713 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
714 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
715 }
716 return true;
717 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
718 (F->getName() == "fflush" || F->getName() == "feof" ||
719 F->getName() == "fileno" || F->getName() == "clearerr" ||
720 F->getName() == "rewind" || F->getName() == "ftell" ||
721 F->getName() == "ferror" || F->getName() == "fgetc" ||
722 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
723 // fflush reads and writes the memory for the file descriptor. It
724 // merges the FILE type into the descriptor.
725 DSNodeHandle H = getValueDest(**CS.arg_begin());
726 if (DSNode *N = H.getNode()) {
727 N->setReadMarker()->setModifiedMarker();
728
729 const Type *ArgTy = F->getFunctionType()->getParamType(0);
730 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
731 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
732 }
733 return true;
734 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
735 (F->getName() == "fwrite" || F->getName() == "fread")) {
736 // fread writes the first operand, fwrite reads it. They both
737 // read/write the FILE descriptor, and merges the FILE type.
738 CallSite::arg_iterator compit = CS.arg_end();
739 DSNodeHandle H = getValueDest(**--compit);
740 if (DSNode *N = H.getNode()) {
741 N->setReadMarker()->setModifiedMarker();
742 const Type *ArgTy = F->getFunctionType()->getParamType(3);
743 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
744 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
745 }
746
747 H = getValueDest(**CS.arg_begin());
748 if (DSNode *N = H.getNode())
749 if (F->getName() == "fwrite")
750 N->setReadMarker();
751 else
752 N->setModifiedMarker();
753 return true;
754 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
755 // fgets reads and writes the memory for the file descriptor. It
756 // merges the FILE type into the descriptor, and writes to the
757 // argument. It returns the argument as well.
758 CallSite::arg_iterator AI = CS.arg_begin();
759 DSNodeHandle H = getValueDest(**AI);
760 if (DSNode *N = H.getNode())
761 N->setModifiedMarker(); // Writes buffer
762 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
763 ++AI; ++AI;
764
765 // Reads and writes file descriptor, merge in FILE type.
766 H = getValueDest(**AI);
767 if (DSNode *N = H.getNode()) {
768 N->setReadMarker()->setModifiedMarker();
769 const Type *ArgTy = F->getFunctionType()->getParamType(2);
770 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
771 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
772 }
773 return true;
774 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
775 F->getName() == "fputs" || F->getName() == "putc" ||
776 F->getName() == "ftell" || F->getName() == "rewind" ||
777 F->getName() == "_IO_putc") {
778 // These functions read and write the memory for the file descriptor,
779 // which is passes as the last argument.
780 CallSite::arg_iterator compit = CS.arg_end();
781 DSNodeHandle H = getValueDest(**--compit);
782 if (DSNode *N = H.getNode()) {
783 N->setReadMarker()->setModifiedMarker();
784 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
785 const Type *ArgTy = *--compit2;
786 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
787 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
788 }
789
790 // Any pointer arguments are read.
791 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
792 AI != E; ++AI)
793 if (isPointerType((*AI)->getType()))
794 if (DSNode *N = getValueDest(**AI).getNode())
795 N->setReadMarker();
796 return true;
797 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
798 F->getName() == "fsetpos") {
799 // These functions read and write the memory for the file descriptor,
800 // and read/write all other arguments.
801 DSNodeHandle H = getValueDest(**CS.arg_begin());
802 if (DSNode *N = H.getNode()) {
803 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
804 const Type *ArgTy = *--compit2;
805 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
806 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
807 }
808
809 // Any pointer arguments are read.
810 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
811 AI != E; ++AI)
812 if (isPointerType((*AI)->getType()))
813 if (DSNode *N = getValueDest(**AI).getNode())
814 N->setReadMarker()->setModifiedMarker();
815 return true;
816 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
817 F->getName() == "sprintf") {
818 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
819
820 if (F->getName() == "fprintf") {
821 // fprintf reads and writes the FILE argument, and applies the type
822 // to it.
823 DSNodeHandle H = getValueDest(**AI);
824 if (DSNode *N = H.getNode()) {
825 N->setModifiedMarker();
826 const Type *ArgTy = (*AI)->getType();
827 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
828 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
829 }
830 } else if (F->getName() == "sprintf") {
831 // sprintf writes the first string argument.
832 DSNodeHandle H = getValueDest(**AI++);
833 if (DSNode *N = H.getNode()) {
834 N->setModifiedMarker();
835 const Type *ArgTy = (*AI)->getType();
836 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
837 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
838 }
839 }
840
841 for (; AI != E; ++AI) {
842 // printf reads all pointer arguments.
843 if (isPointerType((*AI)->getType()))
844 if (DSNode *N = getValueDest(**AI).getNode())
845 N->setReadMarker();
846 }
847 return true;
848 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
849 F->getName() == "vsprintf") {
850 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
851
852 if (F->getName() == "vfprintf") {
853 // ffprintf reads and writes the FILE argument, and applies the type
854 // to it.
855 DSNodeHandle H = getValueDest(**AI);
856 if (DSNode *N = H.getNode()) {
857 N->setModifiedMarker()->setReadMarker();
858 const Type *ArgTy = (*AI)->getType();
859 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
860 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
861 }
862 ++AI;
863 } else if (F->getName() == "vsprintf") {
864 // vsprintf writes the first string argument.
865 DSNodeHandle H = getValueDest(**AI++);
866 if (DSNode *N = H.getNode()) {
867 N->setModifiedMarker();
868 const Type *ArgTy = (*AI)->getType();
869 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
870 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
871 }
872 }
873
874 // Read the format
875 if (AI != E) {
876 if (isPointerType((*AI)->getType()))
877 if (DSNode *N = getValueDest(**AI).getNode())
878 N->setReadMarker();
879 ++AI;
880 }
881
882 // Read the valist, and the pointed-to objects.
883 if (AI != E && isPointerType((*AI)->getType())) {
884 const DSNodeHandle &VAList = getValueDest(**AI);
885 if (DSNode *N = VAList.getNode()) {
886 N->setReadMarker();
887 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
888 VAList.getOffset(), false);
889
890 DSNodeHandle &VAListObjs = getLink(VAList);
891 VAListObjs.getNode()->setReadMarker();
892 }
893 }
894
895 return true;
896 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
897 F->getName() == "sscanf") {
898 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
899
900 if (F->getName() == "fscanf") {
901 // fscanf reads and writes the FILE argument, and applies the type
902 // to it.
903 DSNodeHandle H = getValueDest(**AI);
904 if (DSNode *N = H.getNode()) {
905 N->setReadMarker();
906 const Type *ArgTy = (*AI)->getType();
907 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
908 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
909 }
910 } else if (F->getName() == "sscanf") {
911 // sscanf reads the first string argument.
912 DSNodeHandle H = getValueDest(**AI++);
913 if (DSNode *N = H.getNode()) {
914 N->setReadMarker();
915 const Type *ArgTy = (*AI)->getType();
916 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
917 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
918 }
919 }
920
921 for (; AI != E; ++AI) {
922 // scanf writes all pointer arguments.
923 if (isPointerType((*AI)->getType()))
924 if (DSNode *N = getValueDest(**AI).getNode())
925 N->setModifiedMarker();
926 }
927 return true;
928 } else if (F->getName() == "strtok") {
929 // strtok reads and writes the first argument, returning it. It reads
930 // its second arg. FIXME: strtok also modifies some hidden static
931 // data. Someday this might matter.
932 CallSite::arg_iterator AI = CS.arg_begin();
933 DSNodeHandle H = getValueDest(**AI++);
934 if (DSNode *N = H.getNode()) {
935 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
936 const Type *ArgTy = F->getFunctionType()->getParamType(0);
937 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
938 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
939 }
940 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
941
942 H = getValueDest(**AI); // Reads delimiter
943 if (DSNode *N = H.getNode()) {
944 N->setReadMarker();
945 const Type *ArgTy = F->getFunctionType()->getParamType(1);
946 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
947 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
948 }
949 return true;
950 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
951 F->getName() == "strstr") {
952 // These read their arguments, and return the first one
953 DSNodeHandle H = getValueDest(**CS.arg_begin());
954 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
955
956 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
957 AI != E; ++AI)
958 if (isPointerType((*AI)->getType()))
959 if (DSNode *N = getValueDest(**AI).getNode())
960 N->setReadMarker();
961
962 if (DSNode *N = H.getNode())
963 N->setReadMarker();
964 return true;
965 } else if (F->getName() == "__assert_fail") {
966 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
967 AI != E; ++AI)
968 if (isPointerType((*AI)->getType()))
969 if (DSNode *N = getValueDest(**AI).getNode())
970 N->setReadMarker();
971 return true;
972 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
973 // This writes its second argument, and forces it to double.
974 CallSite::arg_iterator compit = CS.arg_end();
975 DSNodeHandle H = getValueDest(**--compit);
976 if (DSNode *N = H.getNode()) {
977 N->setModifiedMarker();
978 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
979 }
980 return true;
981 } else if (F->getName() == "strcat" || F->getName() == "strncat") {
982 //This might be making unsafe assumptions about usage
983 //Merge return and first arg
984 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
985 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
986 if (DSNode *N = RetNH.getNode())
987 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
988 //and read second pointer
989 if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
990 N->setReadMarker();
991 return true;
992 } else if (F->getName() == "strcpy" || F->getName() == "strncpy") {
993 //This might be making unsafe assumptions about usage
994 //Merge return and first arg
995 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
996 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
997 if (DSNode *N = RetNH.getNode())
998 N->setHeapNodeMarker()->setModifiedMarker();
999 //and read second pointer
1000 if (DSNode *N = getValueDest(**(CS.arg_begin() + 1)).getNode())
1001 N->setReadMarker();
1002 return true;
1003 }
1004 return false;
1005}
1006
Chris Lattner808a7ae2003-09-20 16:34:13 +00001007void GraphBuilder::visitCallSite(CallSite CS) {
Chris Lattnercb582402004-02-26 22:07:22 +00001008 Value *Callee = CS.getCalledValue();
Chris Lattnercb582402004-02-26 22:07:22 +00001009
Chris Lattner894263b2003-09-20 16:50:46 +00001010 // Special case handling of certain libc allocation functions here.
Chris Lattnercb582402004-02-26 22:07:22 +00001011 if (Function *F = dyn_cast<Function>(Callee))
Chris Lattner894263b2003-09-20 16:50:46 +00001012 if (F->isExternal())
Andrew Lenharth118c0942006-11-03 17:43:19 +00001013 if (F->isIntrinsic() && visitIntrinsic(CS, F))
Chris Lattner6b3e3cc2004-03-04 20:33:47 +00001014 return;
Andrew Lenharth118c0942006-11-03 17:43:19 +00001015 else {
John Criswellfa700522005-12-19 17:38:39 +00001016 // Determine if the called function is one of the specified heap
1017 // allocation functions
Andrew Lenharth118c0942006-11-03 17:43:19 +00001018 if (AllocList.end() != std::find(AllocList.begin(), AllocList.end(), F->getName())) {
1019 setDestTo(*CS.getInstruction(),
1020 createNode()->setHeapNodeMarker()->setModifiedMarker());
1021 return;
1022 }
John Criswellfa700522005-12-19 17:38:39 +00001023
John Criswell30751602005-12-19 19:54:23 +00001024 // Determine if the called function is one of the specified heap
1025 // free functions
Andrew Lenharth118c0942006-11-03 17:43:19 +00001026 if (FreeList.end() != std::find(FreeList.begin(), FreeList.end(), F->getName())) {
1027 // Mark that the node is written to...
1028 if (DSNode *N = getValueDest(*(CS.getArgument(0))).getNode())
1029 N->setModifiedMarker()->setHeapNodeMarker();
1030 return;
1031 }
1032 if (visitExternal(CS,F))
1033 return;
1034 // Unknown function, warn if it returns a pointer type or takes a
1035 // pointer argument.
1036 bool Warn = isPointerType(CS.getInstruction()->getType());
1037 if (!Warn)
1038 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1039 I != E; ++I)
1040 if (isPointerType((*I)->getType())) {
1041 Warn = true;
1042 break;
Chris Lattner3aeb40c2004-03-04 21:03:54 +00001043 }
Andrew Lenharth118c0942006-11-03 17:43:19 +00001044 if (Warn) {
1045 DEBUG(std::cerr << "WARNING: Call to unknown external function '"
1046 << F->getName() << "' will cause pessimistic results!\n");
Chris Lattnera07b72f2004-02-13 16:09:54 +00001047 }
Chris Lattner894263b2003-09-20 16:50:46 +00001048 }
1049
Chris Lattnerc314ac42002-07-11 20:32:02 +00001050 // Set up the return value...
Chris Lattner0969c502002-10-21 02:08:03 +00001051 DSNodeHandle RetVal;
Chris Lattner808a7ae2003-09-20 16:34:13 +00001052 Instruction *I = CS.getInstruction();
1053 if (isPointerType(I->getType()))
1054 RetVal = getValueDest(*I);
Chris Lattnerc314ac42002-07-11 20:32:02 +00001055
Chris Lattnercb582402004-02-26 22:07:22 +00001056 DSNode *CalleeNode = 0;
1057 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
1058 CalleeNode = getValueDest(*Callee).getNode();
1059 if (CalleeNode == 0) {
1060 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
Chris Lattnerfbc2d842003-09-24 23:42:58 +00001061 return; // Calling a null pointer?
1062 }
1063 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001064
Chris Lattner0969c502002-10-21 02:08:03 +00001065 std::vector<DSNodeHandle> Args;
Chris Lattner808a7ae2003-09-20 16:34:13 +00001066 Args.reserve(CS.arg_end()-CS.arg_begin());
Chris Lattner0969c502002-10-21 02:08:03 +00001067
1068 // Calculate the arguments vector...
Chris Lattner808a7ae2003-09-20 16:34:13 +00001069 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1070 if (isPointerType((*I)->getType()))
1071 Args.push_back(getValueDest(**I));
Chris Lattner0969c502002-10-21 02:08:03 +00001072
1073 // Add a new function call entry...
Chris Lattnercb582402004-02-26 22:07:22 +00001074 if (CalleeNode)
1075 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
Chris Lattner923fc052003-02-05 21:59:58 +00001076 else
Chris Lattnercb582402004-02-26 22:07:22 +00001077 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
Chris Lattner26c4fc32003-09-20 21:48:16 +00001078 Args));
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001079}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001080
Vikram S. Advebac06222002-12-06 21:17:10 +00001081void GraphBuilder::visitFreeInst(FreeInst &FI) {
Vikram S. Advebac06222002-12-06 21:17:10 +00001082 // Mark that the node is written to...
Chris Lattnerd5612092004-02-24 22:02:48 +00001083 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
1084 N->setModifiedMarker()->setHeapNodeMarker();
Vikram S. Advebac06222002-12-06 21:17:10 +00001085}
1086
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001087/// Handle casts...
1088void GraphBuilder::visitCastInst(CastInst &CI) {
Chris Lattner5af344d2002-11-02 00:36:03 +00001089 if (isPointerType(CI.getType()))
1090 if (isPointerType(CI.getOperand(0)->getType())) {
Chris Lattner157b2522004-10-06 19:29:13 +00001091 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1092 if (Ptr.getNode() == 0) return;
1093
Chris Lattner5af344d2002-11-02 00:36:03 +00001094 // Cast one pointer to the other, just act like a copy instruction
Chris Lattner157b2522004-10-06 19:29:13 +00001095 setDestTo(CI, Ptr);
Chris Lattner5af344d2002-11-02 00:36:03 +00001096 } else {
1097 // Cast something (floating point, small integer) to a pointer. We need
1098 // to track the fact that the node points to SOMETHING, just something we
1099 // don't know about. Make an "Unknown" node.
1100 //
Chris Lattnerbd92b732003-06-19 21:15:11 +00001101 setDestTo(CI, createNode()->setUnknownNodeMarker());
Chris Lattner5af344d2002-11-02 00:36:03 +00001102 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001103}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001104
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001105
Chris Lattner878e5212003-02-04 00:59:50 +00001106// visitInstruction - For all other instruction types, if we have any arguments
1107// that are of pointer type, make them have unknown composition bits, and merge
1108// the nodes together.
1109void GraphBuilder::visitInstruction(Instruction &Inst) {
1110 DSNodeHandle CurNode;
1111 if (isPointerType(Inst.getType()))
1112 CurNode = getValueDest(Inst);
1113 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1114 if (isPointerType((*I)->getType()))
1115 CurNode.mergeWith(getValueDest(**I));
1116
Chris Lattner62c3a952004-10-30 04:22:45 +00001117 if (DSNode *N = CurNode.getNode())
1118 N->setUnknownNodeMarker();
Chris Lattner878e5212003-02-04 00:59:50 +00001119}
1120
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001121
1122
1123//===----------------------------------------------------------------------===//
1124// LocalDataStructures Implementation
1125//===----------------------------------------------------------------------===//
1126
Chris Lattner26c4fc32003-09-20 21:48:16 +00001127// MergeConstantInitIntoNode - Merge the specified constant into the node
1128// pointed to by NH.
1129void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1130 // Ensure a type-record exists...
Chris Lattner62c3a952004-10-30 04:22:45 +00001131 DSNode *NHN = NH.getNode();
1132 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
Chris Lattner26c4fc32003-09-20 21:48:16 +00001133
1134 if (C->getType()->isFirstClassType()) {
1135 if (isPointerType(C->getType()))
1136 // Avoid adding edges from null, or processing non-"pointer" stores
1137 NH.addEdgeTo(getValueDest(*C));
1138 return;
1139 }
Chris Lattner15869aa2003-11-02 22:27:28 +00001140
1141 const TargetData &TD = NH.getNode()->getTargetData();
1142
Chris Lattner26c4fc32003-09-20 21:48:16 +00001143 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1144 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1145 // We don't currently do any indexing for arrays...
1146 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1147 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1148 const StructLayout *SL = TD.getStructLayout(CS->getType());
1149 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattner62c3a952004-10-30 04:22:45 +00001150 DSNode *NHN = NH.getNode();
Andrew Lenharth99c19422006-04-13 19:31:49 +00001151 //Some programmers think ending a structure with a [0 x sbyte] is cute
Andrew Lenharth99c19422006-04-13 19:31:49 +00001152 if (SL->MemberOffsets[i] < SL->StructSize) {
1153 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
1154 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1155 } else if (SL->MemberOffsets[i] == SL->StructSize) {
1156 DEBUG(std::cerr << "Zero size element at end of struct\n");
Andrew Lenharthceeb17d2006-04-25 19:33:23 +00001157 NHN->foldNodeCompletely();
Andrew Lenharth99c19422006-04-13 19:31:49 +00001158 } else {
1159 assert(0 && "type was smaller than offsets of of struct layout indicate");
1160 }
Chris Lattner26c4fc32003-09-20 21:48:16 +00001161 }
Chris Lattner48b2f6b2004-10-26 16:23:03 +00001162 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
Chris Lattner896481e2004-02-15 05:53:42 +00001163 // Noop
Chris Lattner26c4fc32003-09-20 21:48:16 +00001164 } else {
1165 assert(0 && "Unknown constant type!");
1166 }
1167}
1168
1169void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1170 assert(!GV->isExternal() && "Cannot merge in external global!");
1171 // Get a node handle to the global node and merge the initializer into it.
1172 DSNodeHandle NH = getValueDest(*GV);
1173 MergeConstantInitIntoNode(NH, GV->getInitializer());
1174}
1175
1176
Chris Lattner9b426bd2005-03-20 03:32:35 +00001177/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1178/// contains multiple globals, DSA will never, ever, be able to tell the globals
1179/// apart. Instead of maintaining this information in all of the graphs
1180/// throughout the entire program, store only a single global (the "leader") in
1181/// the graphs, and build equivalence classes for the rest of the globals.
1182static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1183 DSScalarMap &SM = GG.getScalarMap();
1184 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1185 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1186 I != E; ++I) {
1187 if (I->getGlobalsList().size() <= 1) continue;
1188
1189 // First, build up the equivalence set for this block of globals.
1190 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1191 GlobalValue *First = GVs[0];
1192 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1193 GlobalECs.unionSets(First, GVs[i]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001194
Chris Lattner9b426bd2005-03-20 03:32:35 +00001195 // Next, get the leader element.
1196 assert(First == GlobalECs.getLeaderValue(First) &&
1197 "First did not end up being the leader?");
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001198
Chris Lattner9b426bd2005-03-20 03:32:35 +00001199 // Next, remove all globals from the scalar map that are not the leader.
1200 assert(GVs[0] == First && "First had to be at the front!");
1201 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1202 ECGlobals.insert(GVs[i]);
1203 SM.erase(SM.find(GVs[i]));
1204 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001205
Chris Lattner9b426bd2005-03-20 03:32:35 +00001206 // Finally, change the global node to only contain the leader.
1207 I->clearGlobals();
1208 I->addGlobal(First);
1209 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001210
Chris Lattner9b426bd2005-03-20 03:32:35 +00001211 DEBUG(GG.AssertGraphOK());
1212}
1213
1214/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1215/// really just equivalent to some other globals, remove the globals from the
1216/// specified DSGraph (if present), and merge any nodes with their leader nodes.
1217static void EliminateUsesOfECGlobals(DSGraph &G,
1218 const std::set<GlobalValue*> &ECGlobals) {
1219 DSScalarMap &SM = G.getScalarMap();
1220 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1221
1222 bool MadeChange = false;
1223 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1224 GI != E; ) {
1225 GlobalValue *GV = *GI++;
1226 if (!ECGlobals.count(GV)) continue;
1227
1228 const DSNodeHandle &GVNH = SM[GV];
1229 assert(!GVNH.isNull() && "Global has null NH!?");
1230
1231 // Okay, this global is in some equivalence class. Start by finding the
1232 // leader of the class.
1233 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1234
1235 // If the leader isn't already in the graph, insert it into the node
1236 // corresponding to GV.
1237 if (!SM.global_count(Leader)) {
1238 GVNH.getNode()->addGlobal(Leader);
1239 SM[Leader] = GVNH;
1240 } else {
1241 // Otherwise, the leader is in the graph, make sure the nodes are the
1242 // merged in the specified graph.
1243 const DSNodeHandle &LNH = SM[Leader];
1244 if (LNH.getNode() != GVNH.getNode())
1245 LNH.mergeWith(GVNH);
1246 }
1247
1248 // Next step, remove the global from the DSNode.
1249 GVNH.getNode()->removeGlobal(GV);
1250
1251 // Finally, remove the global from the ScalarMap.
1252 SM.erase(GV);
1253 MadeChange = true;
1254 }
1255
1256 DEBUG(if(MadeChange) G.AssertGraphOK());
1257}
1258
Chris Lattnerb12914b2004-09-20 04:48:05 +00001259bool LocalDataStructures::runOnModule(Module &M) {
Chris Lattner15869aa2003-11-02 22:27:28 +00001260 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattneraa0b4682002-11-09 21:12:07 +00001261
Chris Lattnerf4f62272005-03-19 22:23:45 +00001262 // First step, build the globals graph.
1263 GlobalsGraph = new DSGraph(GlobalECs, TD);
Chris Lattnerc420ab62004-02-25 23:31:02 +00001264 {
1265 GraphBuilder GGB(*GlobalsGraph);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001266
Chris Lattnerf4f62272005-03-19 22:23:45 +00001267 // Add initializers for all of the globals to the globals graph.
1268 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1269 I != E; ++I)
Chris Lattnerc420ab62004-02-25 23:31:02 +00001270 if (!I->isExternal())
1271 GGB.mergeInGlobalInitializer(I);
1272 }
1273
Chris Lattnerf4f62272005-03-19 22:23:45 +00001274 // Next step, iterate through the nodes in the globals graph, unioning
1275 // together the globals into equivalence classes.
Chris Lattner9b426bd2005-03-20 03:32:35 +00001276 std::set<GlobalValue*> ECGlobals;
1277 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1278 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1279 ECGlobals.clear();
Chris Lattnerf4f62272005-03-19 22:23:45 +00001280
Chris Lattneraa0b4682002-11-09 21:12:07 +00001281 // Calculate all of the graphs...
1282 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1283 if (!I->isExternal())
Chris Lattnerf4f62272005-03-19 22:23:45 +00001284 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1285 GlobalsGraph)));
Chris Lattner26c4fc32003-09-20 21:48:16 +00001286
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001287 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner26c4fc32003-09-20 21:48:16 +00001288 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner9b426bd2005-03-20 03:32:35 +00001289
1290 // Now that we've computed all of the graphs, and merged all of the info into
1291 // the globals graph, see if we have further constrained the globals in the
1292 // program if so, update GlobalECs and remove the extraneous globals from the
1293 // program.
1294 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1295 if (!ECGlobals.empty()) {
1296 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1297 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1298 E = DSInfo.end(); I != E; ++I)
1299 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1300 }
1301
Chris Lattneraa0b4682002-11-09 21:12:07 +00001302 return false;
1303}
1304
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001305// releaseMemory - If the pass pipeline is done with this pass, we can release
1306// our memory... here...
1307//
1308void LocalDataStructures::releaseMemory() {
Chris Lattner81d924d2003-06-30 04:53:27 +00001309 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1310 E = DSInfo.end(); I != E; ++I) {
1311 I->second->getReturnNodes().erase(I->first);
1312 if (I->second->getReturnNodes().empty())
1313 delete I->second;
1314 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001315
1316 // Empty map so next time memory is released, data structures are not
1317 // re-deleted.
1318 DSInfo.clear();
Chris Lattner2e4f9bf2002-11-09 20:01:01 +00001319 delete GlobalsGraph;
1320 GlobalsGraph = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001321}
Brian Gaeked0fde302003-11-11 22:41:34 +00001322