blob: 2ef4aa8af550e3b2be57799a97ff88dbc5df2b0c [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 Lattnerfccd06f2002-10-01 22:33:50 +000027
28// FIXME: This should eventually be a FunctionPass that is automatically
29// aggregated into a Pass.
30//
31#include "llvm/Module.h"
32
Chris Lattner9a927292003-11-12 23:11:14 +000033using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000034
Chris Lattner97f51a32002-07-27 01:12:15 +000035static RegisterAnalysis<LocalDataStructures>
36X("datastructure", "Local Data Structure Analysis");
Chris Lattner97f51a32002-07-27 01:12:15 +000037
Chris Lattnera1907662003-11-13 03:10:49 +000038static cl::opt<bool>
Chris Lattnerf0431b02004-08-02 20:16:21 +000039TrackIntegersAsPointers("dsa-track-integers", cl::Hidden,
Chris Lattnera1907662003-11-13 03:10:49 +000040 cl::desc("If this is set, track integers as potential pointers"));
Chris Lattnera1907662003-11-13 03:10:49 +000041
John Criswellfa700522005-12-19 17:38:39 +000042static cl::list<std::string>
John Criswell61af9132005-12-19 20:14:38 +000043AllocList("dsa-alloc-list",
John Criswellfa700522005-12-19 17:38:39 +000044 cl::value_desc("list"),
45 cl::desc("List of functions that allocate memory from the heap"),
John Criswell61af9132005-12-19 20:14:38 +000046 cl::CommaSeparated, cl::Hidden);
John Criswellfa700522005-12-19 17:38:39 +000047
John Criswell30751602005-12-19 19:54:23 +000048static cl::list<std::string>
John Criswell61af9132005-12-19 20:14:38 +000049FreeList("dsa-free-list",
John Criswell30751602005-12-19 19:54:23 +000050 cl::value_desc("list"),
51 cl::desc("List of functions that free memory from the heap"),
John Criswell61af9132005-12-19 20:14:38 +000052 cl::CommaSeparated, cl::Hidden);
John Criswell30751602005-12-19 19:54:23 +000053
Chris Lattner9a927292003-11-12 23:11:14 +000054namespace llvm {
Chris Lattnerb1060432002-11-07 05:20:53 +000055namespace DS {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000056 // isPointerType - Return true if this type is big enough to hold a pointer.
57 bool isPointerType(const Type *Ty) {
58 if (isa<PointerType>(Ty))
59 return true;
Chris Lattnera1907662003-11-13 03:10:49 +000060 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
Chris Lattnerfccd06f2002-10-01 22:33:50 +000061 return Ty->getPrimitiveSize() >= PointerSize;
62 return false;
63 }
Chris Lattner9a927292003-11-12 23:11:14 +000064}}
Chris Lattnerfccd06f2002-10-01 22:33:50 +000065
Brian Gaeked0fde302003-11-11 22:41:34 +000066using namespace DS;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000067
68namespace {
Chris Lattner923fc052003-02-05 21:59:58 +000069 cl::opt<bool>
70 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
71 cl::desc("Disable direct call optimization in "
72 "DSGraph construction"));
Chris Lattnerca3f7902003-02-08 20:18:39 +000073 cl::opt<bool>
74 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
75 cl::desc("Disable field sensitivity in DSGraphs"));
Chris Lattner923fc052003-02-05 21:59:58 +000076
Chris Lattnerfccd06f2002-10-01 22:33:50 +000077 //===--------------------------------------------------------------------===//
78 // GraphBuilder Class
79 //===--------------------------------------------------------------------===//
80 //
81 /// This class is the builder class that constructs the local data structure
82 /// graph by performing a single pass over the function in question.
83 ///
Chris Lattnerc68c31b2002-07-10 22:38:08 +000084 class GraphBuilder : InstVisitor<GraphBuilder> {
85 DSGraph &G;
Chris Lattner26c4fc32003-09-20 21:48:16 +000086 DSNodeHandle *RetNode; // Node that gets returned...
Chris Lattner62482e52004-01-28 09:15:42 +000087 DSScalarMap &ScalarMap;
Chris Lattnera9548d92005-01-30 23:51:02 +000088 std::list<DSCallSite> *FunctionCalls;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000089
90 public:
Misha Brukman2b37d7c2005-04-21 21:13:18 +000091 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
Chris Lattnera9548d92005-01-30 23:51:02 +000092 std::list<DSCallSite> &fc)
Chris Lattner26c4fc32003-09-20 21:48:16 +000093 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
94 FunctionCalls(&fc) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000095
96 // Create scalar nodes for all pointer arguments...
Chris Lattnera513fb12005-03-22 02:45:13 +000097 for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end();
98 I != E; ++I)
Chris Lattnerfccd06f2002-10-01 22:33:50 +000099 if (isPointerType(I->getType()))
100 getValueDest(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +0000101
Chris Lattner26c4fc32003-09-20 21:48:16 +0000102 visit(f); // Single pass over the function
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000103 }
104
Chris Lattner26c4fc32003-09-20 21:48:16 +0000105 // GraphBuilder ctor for working on the globals graph
106 GraphBuilder(DSGraph &g)
107 : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
108 }
109
110 void mergeInGlobalInitializer(GlobalVariable *GV);
111
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000112 private:
113 // Visitor functions, used to handle each instruction type we encounter...
114 friend class InstVisitor<GraphBuilder>;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000115 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
116 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
117 void handleAlloc(AllocationInst &AI, bool isHeap);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000118
119 void visitPHINode(PHINode &PN);
Chris Lattner6e84bd72005-02-25 01:27:48 +0000120 void visitSelectInst(SelectInst &SI);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000121
Chris Lattner51340062002-11-08 05:00:44 +0000122 void visitGetElementPtrInst(User &GEP);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000123 void visitReturnInst(ReturnInst &RI);
124 void visitLoadInst(LoadInst &LI);
125 void visitStoreInst(StoreInst &SI);
126 void visitCallInst(CallInst &CI);
Chris Lattner808a7ae2003-09-20 16:34:13 +0000127 void visitInvokeInst(InvokeInst &II);
Chris Lattner32672652005-03-05 19:04:31 +0000128 void visitSetCondInst(SetCondInst &SCI);
Vikram S. Advebac06222002-12-06 21:17:10 +0000129 void visitFreeInst(FreeInst &FI);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000130 void visitCastInst(CastInst &CI);
Chris Lattner878e5212003-02-04 00:59:50 +0000131 void visitInstruction(Instruction &I);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000132
Chris Lattner808a7ae2003-09-20 16:34:13 +0000133 void visitCallSite(CallSite CS);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000134 void visitVAArgInst(VAArgInst &I);
Chris Lattner26c4fc32003-09-20 21:48:16 +0000135
136 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000137 private:
138 // Helper functions used to implement the visitation functions...
139
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000140 /// createNode - Create a new DSNode, ensuring that it is properly added to
141 /// the graph.
142 ///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000143 DSNode *createNode(const Type *Ty = 0) {
144 DSNode *N = new DSNode(Ty, &G); // Create the node
Chris Lattnere158b192003-06-16 12:08:18 +0000145 if (DisableFieldSensitivity) {
Chris Lattner2412a052004-05-23 21:14:09 +0000146 // Create node handle referring to the old node so that it is
147 // immediately removed from the graph when the node handle is destroyed.
148 DSNodeHandle OldNNH = N;
Chris Lattnerca3f7902003-02-08 20:18:39 +0000149 N->foldNodeCompletely();
Chris Lattnere158b192003-06-16 12:08:18 +0000150 if (DSNode *FN = N->getForwardNode())
151 N = FN;
152 }
Chris Lattner92673292002-11-02 00:13:20 +0000153 return N;
154 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000155
Chris Lattnerc875f022002-11-03 21:27:48 +0000156 /// setDestTo - Set the ScalarMap entry for the specified value to point to
Chris Lattner92673292002-11-02 00:13:20 +0000157 /// the specified destination. If the Value already points to a node, make
158 /// sure to merge the two destinations together.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000159 ///
Chris Lattner92673292002-11-02 00:13:20 +0000160 void setDestTo(Value &V, const DSNodeHandle &NH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000161
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000162 /// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000163 ///
Chris Lattner92673292002-11-02 00:13:20 +0000164 DSNodeHandle getValueDest(Value &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000165
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000166 /// getLink - This method is used to return the specified link in the
167 /// specified node if one exists. If a link does not already exist (it's
Chris Lattner7e51c872002-10-31 06:52:26 +0000168 /// null), then we create a new node, link it, then return it.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000169 ///
Chris Lattner7e51c872002-10-31 06:52:26 +0000170 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000171 };
172}
173
Brian Gaeked0fde302003-11-11 22:41:34 +0000174using namespace DS;
175
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000176//===----------------------------------------------------------------------===//
177// DSGraph constructor - Simply use the GraphBuilder to construct the local
178// graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000179DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
180 Function &F, DSGraph *GG)
181 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
Chris Lattner2a068862002-11-10 06:53:38 +0000182 PrintAuxCalls = false;
Chris Lattner30514192003-07-02 04:37:26 +0000183
184 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
185
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000186 // Use the graph builder to construct the local version of the graph
Chris Lattner26c4fc32003-09-20 21:48:16 +0000187 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
Chris Lattner4fe34612002-11-18 21:44:19 +0000188#ifndef NDEBUG
189 Timer::addPeakMemoryMeasurement();
190#endif
Chris Lattner1a1a85d2003-02-14 04:55:58 +0000191
Chris Lattnerc420ab62004-02-25 23:31:02 +0000192 // If there are any constant globals referenced in this function, merge their
193 // initializers into the local graph from the globals graph.
194 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
195 ReachabilityCloner RC(*this, *GG, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000196
Chris Lattnerc420ab62004-02-25 23:31:02 +0000197 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
198 I != ScalarMap.global_end(); ++I)
199 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattner76a9eb32004-03-03 23:00:19 +0000200 if (!GV->isExternal() && GV->isConstant())
Chris Lattnerc420ab62004-02-25 23:31:02 +0000201 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
202 }
203
Chris Lattner394471f2003-01-23 22:05:33 +0000204 markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner96517252002-11-09 20:55:24 +0000205
206 // Remove any nodes made dead due to merging...
Chris Lattner394471f2003-01-23 22:05:33 +0000207 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000208}
209
210
211//===----------------------------------------------------------------------===//
212// Helper method implementations...
213//
214
Chris Lattner92673292002-11-02 00:13:20 +0000215/// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000216///
Chris Lattner51340062002-11-08 05:00:44 +0000217DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
218 Value *V = &Val;
Chris Lattner82962de2004-11-03 18:51:26 +0000219 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
Chris Lattner51340062002-11-08 05:00:44 +0000220 return 0; // Null doesn't point to anything, don't add to ScalarMap!
Chris Lattner92673292002-11-02 00:13:20 +0000221
Vikram S. Advebac06222002-12-06 21:17:10 +0000222 DSNodeHandle &NH = ScalarMap[V];
Chris Lattner62c3a952004-10-30 04:22:45 +0000223 if (!NH.isNull())
Vikram S. Advebac06222002-12-06 21:17:10 +0000224 return NH; // Already have a node? Just return it...
225
226 // Otherwise we need to create a new node to point to.
227 // Check first for constant expressions that must be traversed to
228 // extract the actual value.
Reid Spencere8404342004-07-18 00:18:30 +0000229 DSNode* N;
230 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
Chris Lattner48427b52005-03-20 01:18:00 +0000231 // Create a new global node for this global variable.
Reid Spencere8404342004-07-18 00:18:30 +0000232 N = createNode(GV->getType()->getElementType());
233 N->addGlobal(GV);
234 } else if (Constant *C = dyn_cast<Constant>(V)) {
235 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnera513fb12005-03-22 02:45:13 +0000236 if (CE->getOpcode() == Instruction::Cast) {
237 if (isa<PointerType>(CE->getOperand(0)->getType()))
238 NH = getValueDest(*CE->getOperand(0));
239 else
240 NH = createNode()->setUnknownNodeMarker();
241 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner51340062002-11-08 05:00:44 +0000242 visitGetElementPtrInst(*CE);
Chris Lattner62482e52004-01-28 09:15:42 +0000243 DSScalarMap::iterator I = ScalarMap.find(CE);
Chris Lattner2cfbaaf2002-11-09 20:14:03 +0000244 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
Chris Lattner1e56c542003-02-09 23:04:12 +0000245 NH = I->second;
246 } else {
247 // This returns a conservative unknown node for any unhandled ConstExpr
Chris Lattnerbd92b732003-06-19 21:15:11 +0000248 return NH = createNode()->setUnknownNodeMarker();
Chris Lattner51340062002-11-08 05:00:44 +0000249 }
Chris Lattner62c3a952004-10-30 04:22:45 +0000250 if (NH.isNull()) { // (getelementptr null, X) returns null
Chris Lattner1e56c542003-02-09 23:04:12 +0000251 ScalarMap.erase(V);
252 return 0;
253 }
254 return NH;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000255 } else if (isa<UndefValue>(C)) {
256 ScalarMap.erase(V);
257 return 0;
Chris Lattner51340062002-11-08 05:00:44 +0000258 } else {
259 assert(0 && "Unknown constant type!");
260 }
Reid Spencere8404342004-07-18 00:18:30 +0000261 N = createNode(); // just create a shadow node
Chris Lattner92673292002-11-02 00:13:20 +0000262 } else {
263 // Otherwise just create a shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000264 N = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000265 }
266
Chris Lattnerefffdc92004-07-07 06:12:52 +0000267 NH.setTo(N, 0); // Remember that we are pointing to it...
Chris Lattner92673292002-11-02 00:13:20 +0000268 return NH;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000269}
270
Chris Lattner0d9bab82002-07-18 00:12:30 +0000271
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000272/// getLink - This method is used to return the specified link in the
273/// specified node if one exists. If a link does not already exist (it's
274/// null), then we create a new node, link it, then return it. We must
275/// specify the type of the Node field we are accessing so that we know what
276/// type should be linked to if we need to create a new node.
277///
Chris Lattner7e51c872002-10-31 06:52:26 +0000278DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000279 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
Chris Lattner08db7192002-11-06 06:20:27 +0000280 DSNodeHandle &Link = Node.getLink(LinkNo);
Chris Lattner62c3a952004-10-30 04:22:45 +0000281 if (Link.isNull()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000282 // If the link hasn't been created yet, make and return a new shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000283 Link = createNode();
Chris Lattner08db7192002-11-06 06:20:27 +0000284 }
285 return Link;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000286}
287
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000288
Chris Lattnerc875f022002-11-03 21:27:48 +0000289/// setDestTo - Set the ScalarMap entry for the specified value to point to the
Chris Lattner92673292002-11-02 00:13:20 +0000290/// specified destination. If the Value already points to a node, make sure to
291/// merge the two destinations together.
292///
293void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000294 ScalarMap[&V].mergeWith(NH);
Chris Lattner92673292002-11-02 00:13:20 +0000295}
296
297
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000298//===----------------------------------------------------------------------===//
299// Specific instruction type handler implementations...
300//
301
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000302/// Alloca & Malloc instruction implementation - Simply create a new memory
303/// object, pointing the scalar to it.
304///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000305void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
306 DSNode *N = createNode();
307 if (isHeap)
308 N->setHeapNodeMarker();
309 else
310 N->setAllocaNodeMarker();
311 setDestTo(AI, N);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000312}
313
314// PHINode - Make the scalar for the PHI node point to all of the things the
315// incoming values point to... which effectively causes them to be merged.
316//
317void GraphBuilder::visitPHINode(PHINode &PN) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000318 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000319
Chris Lattnerc875f022002-11-03 21:27:48 +0000320 DSNodeHandle &PNDest = ScalarMap[&PN];
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000321 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
Chris Lattner92673292002-11-02 00:13:20 +0000322 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000323}
324
Chris Lattner6e84bd72005-02-25 01:27:48 +0000325void GraphBuilder::visitSelectInst(SelectInst &SI) {
326 if (!isPointerType(SI.getType())) return; // Only pointer Selects
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000327
Chris Lattner6e84bd72005-02-25 01:27:48 +0000328 DSNodeHandle &Dest = ScalarMap[&SI];
329 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
330 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
331}
332
Chris Lattner32672652005-03-05 19:04:31 +0000333void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
334 if (!isPointerType(SCI.getOperand(0)->getType()) ||
335 isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
336 ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
337}
338
339
Chris Lattner51340062002-11-08 05:00:44 +0000340void GraphBuilder::visitGetElementPtrInst(User &GEP) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000341 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
Chris Lattner753b1132005-02-24 19:55:31 +0000342 if (Value.isNull())
343 Value = createNode();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000344
Chris Lattner179bc7d2003-11-14 17:09:46 +0000345 // As a special case, if all of the index operands of GEP are constant zeros,
346 // handle this just like we handle casts (ie, don't do much).
347 bool AllZeros = true;
348 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
349 if (GEP.getOperand(i) !=
350 Constant::getNullValue(GEP.getOperand(i)->getType())) {
351 AllZeros = false;
352 break;
353 }
354
355 // If all of the indices are zero, the result points to the operand without
356 // applying the type.
Chris Lattner0c9707a2005-03-18 23:18:20 +0000357 if (AllZeros || (!Value.isNull() &&
358 Value.getNode()->isNodeCompletelyFolded())) {
Chris Lattner179bc7d2003-11-14 17:09:46 +0000359 setDestTo(GEP, Value);
360 return;
361 }
362
363
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000364 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
365 const Type *CurTy = PTy->getElementType();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000366
Chris Lattner08db7192002-11-06 06:20:27 +0000367 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
368 // If the node had to be folded... exit quickly
Chris Lattner92673292002-11-02 00:13:20 +0000369 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000370 return;
371 }
372
Chris Lattner15869aa2003-11-02 22:27:28 +0000373 const TargetData &TD = Value.getNode()->getTargetData();
374
Chris Lattner08db7192002-11-06 06:20:27 +0000375#if 0
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000376 // Handle the pointer index specially...
377 if (GEP.getNumOperands() > 1 &&
Chris Lattner28977af2004-04-05 01:30:19 +0000378 (!isa<Constant>(GEP.getOperand(1)) ||
379 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000380
381 // If we already know this is an array being accessed, don't do anything...
382 if (!TopTypeRec.isArray) {
383 TopTypeRec.isArray = true;
384
385 // If we are treating some inner field pointer as an array, fold the node
386 // up because we cannot handle it right. This can come because of
387 // something like this: &((&Pt->X)[1]) == &Pt->Y
388 //
389 if (Value.getOffset()) {
390 // Value is now the pointer we want to GEP to be...
391 Value.getNode()->foldNodeCompletely();
Chris Lattner92673292002-11-02 00:13:20 +0000392 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000393 return;
394 } else {
395 // This is a pointer to the first byte of the node. Make sure that we
396 // are pointing to the outter most type in the node.
397 // FIXME: We need to check one more case here...
398 }
399 }
400 }
Chris Lattner08db7192002-11-06 06:20:27 +0000401#endif
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000402
403 // All of these subscripts are indexing INTO the elements we have...
Chris Lattner26c4fc32003-09-20 21:48:16 +0000404 unsigned Offset = 0;
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000405 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
406 I != E; ++I)
407 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000408 unsigned FieldNo =
409 (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
410 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
Chris Lattner82e9d722004-03-01 19:02:54 +0000411 } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
412 if (!isa<Constant>(I.getOperand()) ||
413 !cast<Constant>(I.getOperand())->isNullValue())
414 Value.getNode()->setArrayMarker();
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000415 }
416
417
Chris Lattner08db7192002-11-06 06:20:27 +0000418#if 0
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000419 if (const SequentialType *STy = cast<SequentialType>(*I)) {
420 CurTy = STy->getElementType();
Chris Lattnere03f32b2002-10-02 06:24:36 +0000421 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000422 Offset += CS->getValue()*TD.getTypeSize(CurTy);
Chris Lattnere03f32b2002-10-02 06:24:36 +0000423 } else {
424 // Variable index into a node. We must merge all of the elements of the
425 // sequential type here.
426 if (isa<PointerType>(STy))
427 std::cerr << "Pointer indexing not handled yet!\n";
428 else {
429 const ArrayType *ATy = cast<ArrayType>(STy);
430 unsigned ElSize = TD.getTypeSize(CurTy);
431 DSNode *N = Value.getNode();
432 assert(N && "Value must have a node!");
433 unsigned RawOffset = Offset+Value.getOffset();
434
435 // Loop over all of the elements of the array, merging them into the
Misha Brukman2f2d0652003-09-11 18:14:24 +0000436 // zeroth element.
Chris Lattnere03f32b2002-10-02 06:24:36 +0000437 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
438 // Merge all of the byte components of this array element
439 for (unsigned j = 0; j != ElSize; ++j)
440 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
441 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000442 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000443 }
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000444#endif
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000445
446 // Add in the offset calculated...
447 Value.setOffset(Value.getOffset()+Offset);
448
Sumant Kowshik8a3802d2005-12-06 18:04:30 +0000449 // Check the offset
450 DSNode *N = Value.getNode();
451 if (N &&
452 !N->isNodeCompletelyFolded() &&
453 (N->getSize() != 0 || Offset != 0) &&
454 !N->isForwarding()) {
455 if ((Offset >= N->getSize()) || int(Offset) < 0) {
456 // Accessing offsets out of node size range
457 // This is seen in the "magic" struct in named (from bind), where the
458 // fourth field is an array of length 0, presumably used to create struct
459 // instances of different sizes
460
461 // Collapse the node since its size is now variable
462 N->foldNodeCompletely();
463 }
464 }
465
466 // Value is now the pointer we want to GEP to be...
Chris Lattner92673292002-11-02 00:13:20 +0000467 setDestTo(GEP, Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000468}
469
470void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattner92673292002-11-02 00:13:20 +0000471 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
Chris Lattner6e84bd72005-02-25 01:27:48 +0000472 if (Ptr.isNull())
473 Ptr = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000474
475 // Make that the node is read from...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000476 Ptr.getNode()->setReadMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000477
478 // Ensure a typerecord exists...
Chris Lattner088b6392003-03-03 17:13:31 +0000479 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
Chris Lattner92673292002-11-02 00:13:20 +0000480
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000481 if (isPointerType(LI.getType()))
Chris Lattner92673292002-11-02 00:13:20 +0000482 setDestTo(LI, getLink(Ptr));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000483}
484
485void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000486 const Type *StoredTy = SI.getOperand(0)->getType();
Chris Lattner92673292002-11-02 00:13:20 +0000487 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000488 if (Dest.isNull()) return;
Chris Lattner92673292002-11-02 00:13:20 +0000489
Vikram S. Advebac06222002-12-06 21:17:10 +0000490 // Mark that the node is written to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000491 Dest.getNode()->setModifiedMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000492
Chris Lattner26c4fc32003-09-20 21:48:16 +0000493 // Ensure a type-record exists...
Chris Lattner08db7192002-11-06 06:20:27 +0000494 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000495
496 // Avoid adding edges from null, or processing non-"pointer" stores
Chris Lattner92673292002-11-02 00:13:20 +0000497 if (isPointerType(StoredTy))
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000498 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000499}
500
501void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattner92673292002-11-02 00:13:20 +0000502 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
Chris Lattner26c4fc32003-09-20 21:48:16 +0000503 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000504}
505
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000506void GraphBuilder::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +0000507 //FIXME: also updates the argument
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000508 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
509 if (Ptr.isNull()) return;
510
511 // Make that the node is read from.
512 Ptr.getNode()->setReadMarker();
513
Chris Lattner62c3a952004-10-30 04:22:45 +0000514 // Ensure a type record exists.
515 DSNode *PtrN = Ptr.getNode();
516 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000517
518 if (isPointerType(I.getType()))
519 setDestTo(I, getLink(Ptr));
520}
521
522
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000523void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000524 visitCallSite(&CI);
525}
526
527void GraphBuilder::visitInvokeInst(InvokeInst &II) {
528 visitCallSite(&II);
529}
530
531void GraphBuilder::visitCallSite(CallSite CS) {
Chris Lattnercb582402004-02-26 22:07:22 +0000532 Value *Callee = CS.getCalledValue();
Chris Lattnercb582402004-02-26 22:07:22 +0000533
Chris Lattner894263b2003-09-20 16:50:46 +0000534 // Special case handling of certain libc allocation functions here.
Chris Lattnercb582402004-02-26 22:07:22 +0000535 if (Function *F = dyn_cast<Function>(Callee))
Chris Lattner894263b2003-09-20 16:50:46 +0000536 if (F->isExternal())
Chris Lattnera07b72f2004-02-13 16:09:54 +0000537 switch (F->getIntrinsicID()) {
Chris Lattner317201d2004-03-13 00:24:00 +0000538 case Intrinsic::vastart:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000539 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
540 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000541 case Intrinsic::vacopy:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000542 getValueDest(*CS.getInstruction()).
543 mergeWith(getValueDest(**(CS.arg_begin())));
544 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000545 case Intrinsic::vaend:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000546 return; // noop
Chris Lattnera07b72f2004-02-13 16:09:54 +0000547 case Intrinsic::memmove:
548 case Intrinsic::memcpy: {
549 // Merge the first & second arguments, and mark the memory read and
Chris Lattnerfb8c6102003-11-08 21:55:50 +0000550 // modified.
Chris Lattnera07b72f2004-02-13 16:09:54 +0000551 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
Chris Lattner67ce57a2003-11-09 03:32:52 +0000552 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
553 if (DSNode *N = RetNH.getNode())
554 N->setModifiedMarker()->setReadMarker();
555 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000556 }
Chris Lattnereee33b22004-02-16 18:37:40 +0000557 case Intrinsic::memset:
558 // Mark the memory modified.
559 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
560 N->setModifiedMarker();
561 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000562 default:
John Criswellfa700522005-12-19 17:38:39 +0000563 // Determine if the called function is one of the specified heap
564 // allocation functions
565 for (cl::list<std::string>::iterator AllocFunc = AllocList.begin(),
566 LastAllocFunc = AllocList.end();
567 AllocFunc != LastAllocFunc;
568 ++AllocFunc) {
569 if (F->getName() == *(AllocFunc)) {
570 setDestTo(*CS.getInstruction(),
571 createNode()->setHeapNodeMarker()->setModifiedMarker());
572 return;
573 }
574 }
575
John Criswell30751602005-12-19 19:54:23 +0000576 // Determine if the called function is one of the specified heap
577 // free functions
578 for (cl::list<std::string>::iterator FreeFunc = FreeList.begin(),
579 LastFreeFunc = FreeList.end();
580 FreeFunc != LastFreeFunc;
581 ++FreeFunc) {
582 if (F->getName() == *(FreeFunc)) {
583 // Mark that the node is written to...
584 if (DSNode *N = getValueDest(*(CS.getArgument(0))).getNode())
585 N->setModifiedMarker()->setHeapNodeMarker();
586 return;
587 }
588 }
589
Vikram S. Advee4e97ef2004-05-25 08:14:52 +0000590 if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
591 F->getName() == "memalign" || F->getName() == "valloc") {
Chris Lattnera07b72f2004-02-13 16:09:54 +0000592 setDestTo(*CS.getInstruction(),
593 createNode()->setHeapNodeMarker()->setModifiedMarker());
594 return;
595 } else if (F->getName() == "realloc") {
596 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
Chris Lattner82962de2004-11-03 18:51:26 +0000597 if (CS.arg_begin() != CS.arg_end())
598 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
Chris Lattnera07b72f2004-02-13 16:09:54 +0000599 if (DSNode *N = RetNH.getNode())
600 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
601 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000602 } else if (F->getName() == "memmove") {
603 // Merge the first & second arguments, and mark the memory read and
604 // modified.
605 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
606 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
607 if (DSNode *N = RetNH.getNode())
608 N->setModifiedMarker()->setReadMarker();
609 return;
610
Chris Lattnerd5612092004-02-24 22:02:48 +0000611 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000612 F->getName() == "atol" || F->getName() == "atoll" ||
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000613 F->getName() == "remove" || F->getName() == "unlink" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000614 F->getName() == "rename" || F->getName() == "memcmp" ||
615 F->getName() == "strcmp" || F->getName() == "strncmp" ||
616 F->getName() == "execl" || F->getName() == "execlp" ||
617 F->getName() == "execle" || F->getName() == "execv" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000618 F->getName() == "execvp" || F->getName() == "chmod" ||
619 F->getName() == "puts" || F->getName() == "write" ||
620 F->getName() == "open" || F->getName() == "create" ||
621 F->getName() == "truncate" || F->getName() == "chdir" ||
622 F->getName() == "mkdir" || F->getName() == "rmdir") {
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000623 // These functions read all of their pointer operands.
624 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
625 AI != E; ++AI) {
626 if (isPointerType((*AI)->getType()))
627 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000628 N->setReadMarker();
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000629 }
Chris Lattner304e1432004-02-16 22:57:19 +0000630 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000631 } else if (F->getName() == "read" || F->getName() == "pipe" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000632 F->getName() == "wait" || F->getName() == "time") {
Chris Lattner52fc8d72004-02-25 23:06:40 +0000633 // These functions write all of their pointer operands.
634 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
635 AI != E; ++AI) {
636 if (isPointerType((*AI)->getType()))
637 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000638 N->setModifiedMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000639 }
640 return;
Chris Lattneradc1efe2004-02-25 17:43:20 +0000641 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
642 F->getName() == "lstat") {
643 // These functions read their first operand if its a pointer.
644 CallSite::arg_iterator AI = CS.arg_begin();
645 if (isPointerType((*AI)->getType())) {
646 DSNodeHandle Path = getValueDest(**AI);
647 if (DSNode *N = Path.getNode()) N->setReadMarker();
648 }
Chris Lattner304e1432004-02-16 22:57:19 +0000649
Chris Lattneradc1efe2004-02-25 17:43:20 +0000650 // Then they write into the stat buffer.
651 DSNodeHandle StatBuf = getValueDest(**++AI);
652 if (DSNode *N = StatBuf.getNode()) {
653 N->setModifiedMarker();
654 const Type *StatTy = F->getFunctionType()->getParamType(1);
655 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
656 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
657 }
Chris Lattneradc1efe2004-02-25 17:43:20 +0000658 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000659 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
660 F->getName() == "strtold") {
661 // These functions read the first pointer
662 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
663 Str->setReadMarker();
664 // If the second parameter is passed, it will point to the first
665 // argument node.
666 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
667 if (DSNode *End = EndPtrNH.getNode()) {
668 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
669 EndPtrNH.getOffset(), false);
670 End->setModifiedMarker();
671 DSNodeHandle &Link = getLink(EndPtrNH);
672 Link.mergeWith(getValueDest(**CS.arg_begin()));
673 }
674 }
675
676 return;
Chris Lattner6b586df2004-02-27 20:04:48 +0000677 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
678 F->getName() == "freopen") {
679 // These functions read all of their pointer operands.
680 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
681 AI != E; ++AI)
682 if (isPointerType((*AI)->getType()))
683 if (DSNode *N = getValueDest(**AI).getNode())
684 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000685
Chris Lattner68300db2004-02-13 20:05:32 +0000686 // fopen allocates in an unknown way and writes to the file
687 // descriptor. Also, merge the allocated type into the node.
688 DSNodeHandle Result = getValueDest(*CS.getInstruction());
Chris Lattnerd5612092004-02-24 22:02:48 +0000689 if (DSNode *N = Result.getNode()) {
690 N->setModifiedMarker()->setUnknownNodeMarker();
691 const Type *RetTy = F->getFunctionType()->getReturnType();
692 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
693 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
694 }
Chris Lattner6b586df2004-02-27 20:04:48 +0000695
696 // If this is freopen, merge the file descriptor passed in with the
697 // result.
Chris Lattnerfe781652004-12-08 16:22:26 +0000698 if (F->getName() == "freopen") {
699 // ICC doesn't handle getting the iterator, decrementing and
700 // dereferencing it in one operation without error. Do it in 2 steps
701 CallSite::arg_iterator compit = CS.arg_end();
702 Result.mergeWith(getValueDest(**--compit));
703 }
Chris Lattnerd5612092004-02-24 22:02:48 +0000704 return;
Chris Lattner68300db2004-02-13 20:05:32 +0000705 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
706 // fclose reads and deallocates the memory in an unknown way for the
707 // file descriptor. It merges the FILE type into the descriptor.
708 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000709 if (DSNode *N = H.getNode()) {
710 N->setReadMarker()->setUnknownNodeMarker();
711 const Type *ArgTy = F->getFunctionType()->getParamType(0);
712 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
713 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
714 }
Chris Lattner68300db2004-02-13 20:05:32 +0000715 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000716 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
Chris Lattner304e1432004-02-16 22:57:19 +0000717 (F->getName() == "fflush" || F->getName() == "feof" ||
718 F->getName() == "fileno" || F->getName() == "clearerr" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000719 F->getName() == "rewind" || F->getName() == "ftell" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000720 F->getName() == "ferror" || F->getName() == "fgetc" ||
721 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
Chris Lattner304e1432004-02-16 22:57:19 +0000722 // fflush reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000723 // 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()->setModifiedMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000727
Chris Lattnerd5612092004-02-24 22:02:48 +0000728 const Type *ArgTy = F->getFunctionType()->getParamType(0);
729 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
730 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
731 }
732 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000733 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
Chris Lattnerd5612092004-02-24 22:02:48 +0000734 (F->getName() == "fwrite" || F->getName() == "fread")) {
735 // fread writes the first operand, fwrite reads it. They both
736 // read/write the FILE descriptor, and merges the FILE type.
Chris Lattnerfe781652004-12-08 16:22:26 +0000737 CallSite::arg_iterator compit = CS.arg_end();
738 DSNodeHandle H = getValueDest(**--compit);
Chris Lattnerd5612092004-02-24 22:02:48 +0000739 if (DSNode *N = H.getNode()) {
740 N->setReadMarker()->setModifiedMarker();
741 const Type *ArgTy = F->getFunctionType()->getParamType(3);
742 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
743 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
744 }
745
746 H = getValueDest(**CS.arg_begin());
747 if (DSNode *N = H.getNode())
748 if (F->getName() == "fwrite")
749 N->setReadMarker();
750 else
751 N->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000752 return;
753 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
Chris Lattner304e1432004-02-16 22:57:19 +0000754 // fgets reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000755 // merges the FILE type into the descriptor, and writes to the
756 // argument. It returns the argument as well.
757 CallSite::arg_iterator AI = CS.arg_begin();
758 DSNodeHandle H = getValueDest(**AI);
759 if (DSNode *N = H.getNode())
760 N->setModifiedMarker(); // Writes buffer
761 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
762 ++AI; ++AI;
763
764 // Reads and writes file descriptor, merge in FILE type.
Chris Lattneradc1efe2004-02-25 17:43:20 +0000765 H = getValueDest(**AI);
Chris Lattnerd5612092004-02-24 22:02:48 +0000766 if (DSNode *N = H.getNode()) {
Chris Lattner339d8df2004-02-13 21:21:48 +0000767 N->setReadMarker()->setModifiedMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000768 const Type *ArgTy = F->getFunctionType()->getParamType(2);
769 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
770 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
771 }
772 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000773 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
774 F->getName() == "fputs" || F->getName() == "putc" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000775 F->getName() == "ftell" || F->getName() == "rewind" ||
776 F->getName() == "_IO_putc") {
777 // These functions read and write the memory for the file descriptor,
778 // which is passes as the last argument.
Chris Lattnerfe781652004-12-08 16:22:26 +0000779 CallSite::arg_iterator compit = CS.arg_end();
780 DSNodeHandle H = getValueDest(**--compit);
Chris Lattneradc1efe2004-02-25 17:43:20 +0000781 if (DSNode *N = H.getNode()) {
782 N->setReadMarker()->setModifiedMarker();
Chris Lattnerfe781652004-12-08 16:22:26 +0000783 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
784 const Type *ArgTy = *--compit2;
Chris Lattnerd5612092004-02-24 22:02:48 +0000785 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
786 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
787 }
Chris Lattner52fc8d72004-02-25 23:06:40 +0000788
789 // Any pointer arguments are read.
790 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
791 AI != E; ++AI)
792 if (isPointerType((*AI)->getType()))
793 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000794 N->setReadMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000795 return;
796 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
797 F->getName() == "fsetpos") {
798 // These functions read and write the memory for the file descriptor,
799 // and read/write all other arguments.
800 DSNodeHandle H = getValueDest(**CS.arg_begin());
801 if (DSNode *N = H.getNode()) {
Chris Lattnerfe781652004-12-08 16:22:26 +0000802 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
803 const Type *ArgTy = *--compit2;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000804 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
805 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
806 }
807
808 // Any pointer arguments are read.
809 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
810 AI != E; ++AI)
811 if (isPointerType((*AI)->getType()))
812 if (DSNode *N = getValueDest(**AI).getNode())
813 N->setReadMarker()->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000814 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000815 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
816 F->getName() == "sprintf") {
Chris Lattner339d8df2004-02-13 21:21:48 +0000817 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
818
819 if (F->getName() == "fprintf") {
820 // fprintf reads and writes the FILE argument, and applies the type
821 // to it.
822 DSNodeHandle H = getValueDest(**AI);
823 if (DSNode *N = H.getNode()) {
824 N->setModifiedMarker();
825 const Type *ArgTy = (*AI)->getType();
826 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
827 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
828 }
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000829 } else if (F->getName() == "sprintf") {
830 // sprintf writes the first string argument.
831 DSNodeHandle H = getValueDest(**AI++);
832 if (DSNode *N = H.getNode()) {
833 N->setModifiedMarker();
834 const Type *ArgTy = (*AI)->getType();
835 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
836 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
837 }
Chris Lattner339d8df2004-02-13 21:21:48 +0000838 }
839
840 for (; AI != E; ++AI) {
841 // printf reads all pointer arguments.
842 if (isPointerType((*AI)->getType()))
843 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000844 N->setReadMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000845 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000846 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000847 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
848 F->getName() == "vsprintf") {
849 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
850
851 if (F->getName() == "vfprintf") {
852 // ffprintf reads and writes the FILE argument, and applies the type
853 // to it.
854 DSNodeHandle H = getValueDest(**AI);
855 if (DSNode *N = H.getNode()) {
856 N->setModifiedMarker()->setReadMarker();
857 const Type *ArgTy = (*AI)->getType();
858 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
859 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
860 }
861 ++AI;
862 } else if (F->getName() == "vsprintf") {
863 // vsprintf writes the first string argument.
864 DSNodeHandle H = getValueDest(**AI++);
865 if (DSNode *N = H.getNode()) {
866 N->setModifiedMarker();
867 const Type *ArgTy = (*AI)->getType();
868 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
869 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
870 }
871 }
872
873 // Read the format
874 if (AI != E) {
875 if (isPointerType((*AI)->getType()))
876 if (DSNode *N = getValueDest(**AI).getNode())
877 N->setReadMarker();
878 ++AI;
879 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000880
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000881 // Read the valist, and the pointed-to objects.
882 if (AI != E && isPointerType((*AI)->getType())) {
883 const DSNodeHandle &VAList = getValueDest(**AI);
884 if (DSNode *N = VAList.getNode()) {
885 N->setReadMarker();
886 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
887 VAList.getOffset(), false);
888
889 DSNodeHandle &VAListObjs = getLink(VAList);
890 VAListObjs.getNode()->setReadMarker();
891 }
892 }
893
894 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000895 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
896 F->getName() == "sscanf") {
897 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
Chris Lattner339d8df2004-02-13 21:21:48 +0000898
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000899 if (F->getName() == "fscanf") {
900 // fscanf reads and writes the FILE argument, and applies the type
901 // to it.
902 DSNodeHandle H = getValueDest(**AI);
903 if (DSNode *N = H.getNode()) {
904 N->setReadMarker();
905 const Type *ArgTy = (*AI)->getType();
906 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
907 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
908 }
909 } else if (F->getName() == "sscanf") {
910 // sscanf reads the first string argument.
911 DSNodeHandle H = getValueDest(**AI++);
912 if (DSNode *N = H.getNode()) {
913 N->setReadMarker();
914 const Type *ArgTy = (*AI)->getType();
915 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
916 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
917 }
918 }
919
920 for (; AI != E; ++AI) {
921 // scanf writes all pointer arguments.
922 if (isPointerType((*AI)->getType()))
923 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000924 N->setModifiedMarker();
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000925 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000926 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000927 } else if (F->getName() == "strtok") {
928 // strtok reads and writes the first argument, returning it. It reads
929 // its second arg. FIXME: strtok also modifies some hidden static
930 // data. Someday this might matter.
931 CallSite::arg_iterator AI = CS.arg_begin();
932 DSNodeHandle H = getValueDest(**AI++);
933 if (DSNode *N = H.getNode()) {
934 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
935 const Type *ArgTy = F->getFunctionType()->getParamType(0);
936 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
937 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
938 }
939 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
940
941 H = getValueDest(**AI); // Reads delimiter
942 if (DSNode *N = H.getNode()) {
943 N->setReadMarker();
944 const Type *ArgTy = F->getFunctionType()->getParamType(1);
945 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
946 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
947 }
948 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000949 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
950 F->getName() == "strstr") {
951 // These read their arguments, and return the first one
Chris Lattneradc1efe2004-02-25 17:43:20 +0000952 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattner1fe98742004-02-26 03:43:08 +0000953 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
954
955 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
956 AI != E; ++AI)
957 if (isPointerType((*AI)->getType()))
958 if (DSNode *N = getValueDest(**AI).getNode())
959 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000960
Chris Lattneradc1efe2004-02-25 17:43:20 +0000961 if (DSNode *N = H.getNode())
962 N->setReadMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000963 return;
Chris Lattnerbeacefa2004-11-08 21:08:28 +0000964 } else if (F->getName() == "__assert_fail") {
965 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
966 AI != E; ++AI)
967 if (isPointerType((*AI)->getType()))
968 if (DSNode *N = getValueDest(**AI).getNode())
969 N->setReadMarker();
970 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000971 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
972 // This writes its second argument, and forces it to double.
Chris Lattnerfe781652004-12-08 16:22:26 +0000973 CallSite::arg_iterator compit = CS.arg_end();
974 DSNodeHandle H = getValueDest(**--compit);
Chris Lattner52fc8d72004-02-25 23:06:40 +0000975 if (DSNode *N = H.getNode()) {
976 N->setModifiedMarker();
977 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
978 }
979 return;
Chris Lattner339d8df2004-02-13 21:21:48 +0000980 } else {
Chris Lattner304e1432004-02-16 22:57:19 +0000981 // Unknown function, warn if it returns a pointer type or takes a
982 // pointer argument.
983 bool Warn = isPointerType(CS.getInstruction()->getType());
984 if (!Warn)
985 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
986 I != E; ++I)
987 if (isPointerType((*I)->getType())) {
988 Warn = true;
989 break;
990 }
991 if (Warn)
992 std::cerr << "WARNING: Call to unknown external function '"
993 << F->getName() << "' will cause pessimistic results!\n";
Chris Lattnera07b72f2004-02-13 16:09:54 +0000994 }
Chris Lattner894263b2003-09-20 16:50:46 +0000995 }
996
997
Chris Lattnerc314ac42002-07-11 20:32:02 +0000998 // Set up the return value...
Chris Lattner0969c502002-10-21 02:08:03 +0000999 DSNodeHandle RetVal;
Chris Lattner808a7ae2003-09-20 16:34:13 +00001000 Instruction *I = CS.getInstruction();
1001 if (isPointerType(I->getType()))
1002 RetVal = getValueDest(*I);
Chris Lattnerc314ac42002-07-11 20:32:02 +00001003
Chris Lattnercb582402004-02-26 22:07:22 +00001004 DSNode *CalleeNode = 0;
1005 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
1006 CalleeNode = getValueDest(*Callee).getNode();
1007 if (CalleeNode == 0) {
1008 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
Chris Lattnerfbc2d842003-09-24 23:42:58 +00001009 return; // Calling a null pointer?
1010 }
1011 }
Chris Lattner0d9bab82002-07-18 00:12:30 +00001012
Chris Lattner0969c502002-10-21 02:08:03 +00001013 std::vector<DSNodeHandle> Args;
Chris Lattner808a7ae2003-09-20 16:34:13 +00001014 Args.reserve(CS.arg_end()-CS.arg_begin());
Chris Lattner0969c502002-10-21 02:08:03 +00001015
1016 // Calculate the arguments vector...
Chris Lattner808a7ae2003-09-20 16:34:13 +00001017 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
1018 if (isPointerType((*I)->getType()))
1019 Args.push_back(getValueDest(**I));
Chris Lattner0969c502002-10-21 02:08:03 +00001020
1021 // Add a new function call entry...
Chris Lattnercb582402004-02-26 22:07:22 +00001022 if (CalleeNode)
1023 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
Chris Lattner923fc052003-02-05 21:59:58 +00001024 else
Chris Lattnercb582402004-02-26 22:07:22 +00001025 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
Chris Lattner26c4fc32003-09-20 21:48:16 +00001026 Args));
Chris Lattnerc68c31b2002-07-10 22:38:08 +00001027}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001028
Vikram S. Advebac06222002-12-06 21:17:10 +00001029void GraphBuilder::visitFreeInst(FreeInst &FI) {
Vikram S. Advebac06222002-12-06 21:17:10 +00001030 // Mark that the node is written to...
Chris Lattnerd5612092004-02-24 22:02:48 +00001031 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
1032 N->setModifiedMarker()->setHeapNodeMarker();
Vikram S. Advebac06222002-12-06 21:17:10 +00001033}
1034
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001035/// Handle casts...
1036void GraphBuilder::visitCastInst(CastInst &CI) {
Chris Lattner5af344d2002-11-02 00:36:03 +00001037 if (isPointerType(CI.getType()))
1038 if (isPointerType(CI.getOperand(0)->getType())) {
Chris Lattner157b2522004-10-06 19:29:13 +00001039 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1040 if (Ptr.getNode() == 0) return;
1041
Chris Lattner5af344d2002-11-02 00:36:03 +00001042 // Cast one pointer to the other, just act like a copy instruction
Chris Lattner157b2522004-10-06 19:29:13 +00001043 setDestTo(CI, Ptr);
Chris Lattner5af344d2002-11-02 00:36:03 +00001044 } else {
1045 // Cast something (floating point, small integer) to a pointer. We need
1046 // to track the fact that the node points to SOMETHING, just something we
1047 // don't know about. Make an "Unknown" node.
1048 //
Chris Lattnerbd92b732003-06-19 21:15:11 +00001049 setDestTo(CI, createNode()->setUnknownNodeMarker());
Chris Lattner5af344d2002-11-02 00:36:03 +00001050 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001051}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001052
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001053
Chris Lattner878e5212003-02-04 00:59:50 +00001054// visitInstruction - For all other instruction types, if we have any arguments
1055// that are of pointer type, make them have unknown composition bits, and merge
1056// the nodes together.
1057void GraphBuilder::visitInstruction(Instruction &Inst) {
1058 DSNodeHandle CurNode;
1059 if (isPointerType(Inst.getType()))
1060 CurNode = getValueDest(Inst);
1061 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1062 if (isPointerType((*I)->getType()))
1063 CurNode.mergeWith(getValueDest(**I));
1064
Chris Lattner62c3a952004-10-30 04:22:45 +00001065 if (DSNode *N = CurNode.getNode())
1066 N->setUnknownNodeMarker();
Chris Lattner878e5212003-02-04 00:59:50 +00001067}
1068
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001069
1070
1071//===----------------------------------------------------------------------===//
1072// LocalDataStructures Implementation
1073//===----------------------------------------------------------------------===//
1074
Chris Lattner26c4fc32003-09-20 21:48:16 +00001075// MergeConstantInitIntoNode - Merge the specified constant into the node
1076// pointed to by NH.
1077void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1078 // Ensure a type-record exists...
Chris Lattner62c3a952004-10-30 04:22:45 +00001079 DSNode *NHN = NH.getNode();
1080 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
Chris Lattner26c4fc32003-09-20 21:48:16 +00001081
1082 if (C->getType()->isFirstClassType()) {
1083 if (isPointerType(C->getType()))
1084 // Avoid adding edges from null, or processing non-"pointer" stores
1085 NH.addEdgeTo(getValueDest(*C));
1086 return;
1087 }
Chris Lattner15869aa2003-11-02 22:27:28 +00001088
1089 const TargetData &TD = NH.getNode()->getTargetData();
1090
Chris Lattner26c4fc32003-09-20 21:48:16 +00001091 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1092 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1093 // We don't currently do any indexing for arrays...
1094 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1095 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1096 const StructLayout *SL = TD.getStructLayout(CS->getType());
1097 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattner62c3a952004-10-30 04:22:45 +00001098 DSNode *NHN = NH.getNode();
Chris Lattner507bdf92005-01-12 04:51:37 +00001099 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
Chris Lattner26c4fc32003-09-20 21:48:16 +00001100 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1101 }
Chris Lattner48b2f6b2004-10-26 16:23:03 +00001102 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
Chris Lattner896481e2004-02-15 05:53:42 +00001103 // Noop
Chris Lattner26c4fc32003-09-20 21:48:16 +00001104 } else {
1105 assert(0 && "Unknown constant type!");
1106 }
1107}
1108
1109void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1110 assert(!GV->isExternal() && "Cannot merge in external global!");
1111 // Get a node handle to the global node and merge the initializer into it.
1112 DSNodeHandle NH = getValueDest(*GV);
1113 MergeConstantInitIntoNode(NH, GV->getInitializer());
1114}
1115
1116
Chris Lattner9b426bd2005-03-20 03:32:35 +00001117/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1118/// contains multiple globals, DSA will never, ever, be able to tell the globals
1119/// apart. Instead of maintaining this information in all of the graphs
1120/// throughout the entire program, store only a single global (the "leader") in
1121/// the graphs, and build equivalence classes for the rest of the globals.
1122static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1123 DSScalarMap &SM = GG.getScalarMap();
1124 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1125 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1126 I != E; ++I) {
1127 if (I->getGlobalsList().size() <= 1) continue;
1128
1129 // First, build up the equivalence set for this block of globals.
1130 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1131 GlobalValue *First = GVs[0];
1132 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1133 GlobalECs.unionSets(First, GVs[i]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001134
Chris Lattner9b426bd2005-03-20 03:32:35 +00001135 // Next, get the leader element.
1136 assert(First == GlobalECs.getLeaderValue(First) &&
1137 "First did not end up being the leader?");
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001138
Chris Lattner9b426bd2005-03-20 03:32:35 +00001139 // Next, remove all globals from the scalar map that are not the leader.
1140 assert(GVs[0] == First && "First had to be at the front!");
1141 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1142 ECGlobals.insert(GVs[i]);
1143 SM.erase(SM.find(GVs[i]));
1144 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001145
Chris Lattner9b426bd2005-03-20 03:32:35 +00001146 // Finally, change the global node to only contain the leader.
1147 I->clearGlobals();
1148 I->addGlobal(First);
1149 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001150
Chris Lattner9b426bd2005-03-20 03:32:35 +00001151 DEBUG(GG.AssertGraphOK());
1152}
1153
1154/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1155/// really just equivalent to some other globals, remove the globals from the
1156/// specified DSGraph (if present), and merge any nodes with their leader nodes.
1157static void EliminateUsesOfECGlobals(DSGraph &G,
1158 const std::set<GlobalValue*> &ECGlobals) {
1159 DSScalarMap &SM = G.getScalarMap();
1160 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1161
1162 bool MadeChange = false;
1163 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1164 GI != E; ) {
1165 GlobalValue *GV = *GI++;
1166 if (!ECGlobals.count(GV)) continue;
1167
1168 const DSNodeHandle &GVNH = SM[GV];
1169 assert(!GVNH.isNull() && "Global has null NH!?");
1170
1171 // Okay, this global is in some equivalence class. Start by finding the
1172 // leader of the class.
1173 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1174
1175 // If the leader isn't already in the graph, insert it into the node
1176 // corresponding to GV.
1177 if (!SM.global_count(Leader)) {
1178 GVNH.getNode()->addGlobal(Leader);
1179 SM[Leader] = GVNH;
1180 } else {
1181 // Otherwise, the leader is in the graph, make sure the nodes are the
1182 // merged in the specified graph.
1183 const DSNodeHandle &LNH = SM[Leader];
1184 if (LNH.getNode() != GVNH.getNode())
1185 LNH.mergeWith(GVNH);
1186 }
1187
1188 // Next step, remove the global from the DSNode.
1189 GVNH.getNode()->removeGlobal(GV);
1190
1191 // Finally, remove the global from the ScalarMap.
1192 SM.erase(GV);
1193 MadeChange = true;
1194 }
1195
1196 DEBUG(if(MadeChange) G.AssertGraphOK());
1197}
1198
Chris Lattnerb12914b2004-09-20 04:48:05 +00001199bool LocalDataStructures::runOnModule(Module &M) {
Chris Lattner15869aa2003-11-02 22:27:28 +00001200 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattneraa0b4682002-11-09 21:12:07 +00001201
Chris Lattnerf4f62272005-03-19 22:23:45 +00001202 // First step, build the globals graph.
1203 GlobalsGraph = new DSGraph(GlobalECs, TD);
Chris Lattnerc420ab62004-02-25 23:31:02 +00001204 {
1205 GraphBuilder GGB(*GlobalsGraph);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001206
Chris Lattnerf4f62272005-03-19 22:23:45 +00001207 // Add initializers for all of the globals to the globals graph.
1208 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1209 I != E; ++I)
Chris Lattnerc420ab62004-02-25 23:31:02 +00001210 if (!I->isExternal())
1211 GGB.mergeInGlobalInitializer(I);
1212 }
1213
Chris Lattnerf4f62272005-03-19 22:23:45 +00001214 // Next step, iterate through the nodes in the globals graph, unioning
1215 // together the globals into equivalence classes.
Chris Lattner9b426bd2005-03-20 03:32:35 +00001216 std::set<GlobalValue*> ECGlobals;
1217 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1218 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1219 ECGlobals.clear();
Chris Lattnerf4f62272005-03-19 22:23:45 +00001220
Chris Lattneraa0b4682002-11-09 21:12:07 +00001221 // Calculate all of the graphs...
1222 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1223 if (!I->isExternal())
Chris Lattnerf4f62272005-03-19 22:23:45 +00001224 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1225 GlobalsGraph)));
Chris Lattner26c4fc32003-09-20 21:48:16 +00001226
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001227 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner26c4fc32003-09-20 21:48:16 +00001228 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner9b426bd2005-03-20 03:32:35 +00001229
1230 // Now that we've computed all of the graphs, and merged all of the info into
1231 // the globals graph, see if we have further constrained the globals in the
1232 // program if so, update GlobalECs and remove the extraneous globals from the
1233 // program.
1234 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1235 if (!ECGlobals.empty()) {
1236 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1237 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1238 E = DSInfo.end(); I != E; ++I)
1239 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1240 }
1241
Chris Lattneraa0b4682002-11-09 21:12:07 +00001242 return false;
1243}
1244
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001245// releaseMemory - If the pass pipeline is done with this pass, we can release
1246// our memory... here...
1247//
1248void LocalDataStructures::releaseMemory() {
Chris Lattner81d924d2003-06-30 04:53:27 +00001249 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1250 E = DSInfo.end(); I != E; ++I) {
1251 I->second->getReturnNodes().erase(I->first);
1252 if (I->second->getReturnNodes().empty())
1253 delete I->second;
1254 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001255
1256 // Empty map so next time memory is released, data structures are not
1257 // re-deleted.
1258 DSInfo.clear();
Chris Lattner2e4f9bf2002-11-09 20:01:01 +00001259 delete GlobalsGraph;
1260 GlobalsGraph = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001261}
Brian Gaeked0fde302003-11-11 22:41:34 +00001262