blob: 75ad018c149bb540dcc5425967e708c9c8314ad9 [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
Chris Lattner9a927292003-11-12 23:11:14 +000042namespace llvm {
Chris Lattnerb1060432002-11-07 05:20:53 +000043namespace DS {
Chris Lattnerfccd06f2002-10-01 22:33:50 +000044 // isPointerType - Return true if this type is big enough to hold a pointer.
45 bool isPointerType(const Type *Ty) {
46 if (isa<PointerType>(Ty))
47 return true;
Chris Lattnera1907662003-11-13 03:10:49 +000048 else if (TrackIntegersAsPointers && Ty->isPrimitiveType() &&Ty->isInteger())
Chris Lattnerfccd06f2002-10-01 22:33:50 +000049 return Ty->getPrimitiveSize() >= PointerSize;
50 return false;
51 }
Chris Lattner9a927292003-11-12 23:11:14 +000052}}
Chris Lattnerfccd06f2002-10-01 22:33:50 +000053
Brian Gaeked0fde302003-11-11 22:41:34 +000054using namespace DS;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000055
56namespace {
Chris Lattner923fc052003-02-05 21:59:58 +000057 cl::opt<bool>
58 DisableDirectCallOpt("disable-direct-call-dsopt", cl::Hidden,
59 cl::desc("Disable direct call optimization in "
60 "DSGraph construction"));
Chris Lattnerca3f7902003-02-08 20:18:39 +000061 cl::opt<bool>
62 DisableFieldSensitivity("disable-ds-field-sensitivity", cl::Hidden,
63 cl::desc("Disable field sensitivity in DSGraphs"));
Chris Lattner923fc052003-02-05 21:59:58 +000064
Chris Lattnerfccd06f2002-10-01 22:33:50 +000065 //===--------------------------------------------------------------------===//
66 // GraphBuilder Class
67 //===--------------------------------------------------------------------===//
68 //
69 /// This class is the builder class that constructs the local data structure
70 /// graph by performing a single pass over the function in question.
71 ///
Chris Lattnerc68c31b2002-07-10 22:38:08 +000072 class GraphBuilder : InstVisitor<GraphBuilder> {
73 DSGraph &G;
Chris Lattner26c4fc32003-09-20 21:48:16 +000074 DSNodeHandle *RetNode; // Node that gets returned...
Chris Lattner62482e52004-01-28 09:15:42 +000075 DSScalarMap &ScalarMap;
Chris Lattnera9548d92005-01-30 23:51:02 +000076 std::list<DSCallSite> *FunctionCalls;
Chris Lattnerc68c31b2002-07-10 22:38:08 +000077
78 public:
Misha Brukman2b37d7c2005-04-21 21:13:18 +000079 GraphBuilder(Function &f, DSGraph &g, DSNodeHandle &retNode,
Chris Lattnera9548d92005-01-30 23:51:02 +000080 std::list<DSCallSite> &fc)
Chris Lattner26c4fc32003-09-20 21:48:16 +000081 : G(g), RetNode(&retNode), ScalarMap(G.getScalarMap()),
82 FunctionCalls(&fc) {
Chris Lattner0d9bab82002-07-18 00:12:30 +000083
84 // Create scalar nodes for all pointer arguments...
Chris Lattnera513fb12005-03-22 02:45:13 +000085 for (Function::arg_iterator I = f.arg_begin(), E = f.arg_end();
86 I != E; ++I)
Chris Lattnerfccd06f2002-10-01 22:33:50 +000087 if (isPointerType(I->getType()))
88 getValueDest(*I);
Chris Lattner0d9bab82002-07-18 00:12:30 +000089
Chris Lattner26c4fc32003-09-20 21:48:16 +000090 visit(f); // Single pass over the function
Chris Lattnerc68c31b2002-07-10 22:38:08 +000091 }
92
Chris Lattner26c4fc32003-09-20 21:48:16 +000093 // GraphBuilder ctor for working on the globals graph
94 GraphBuilder(DSGraph &g)
95 : G(g), RetNode(0), ScalarMap(G.getScalarMap()), FunctionCalls(0) {
96 }
97
98 void mergeInGlobalInitializer(GlobalVariable *GV);
99
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000100 private:
101 // Visitor functions, used to handle each instruction type we encounter...
102 friend class InstVisitor<GraphBuilder>;
Chris Lattnerbd92b732003-06-19 21:15:11 +0000103 void visitMallocInst(MallocInst &MI) { handleAlloc(MI, true); }
104 void visitAllocaInst(AllocaInst &AI) { handleAlloc(AI, false); }
105 void handleAlloc(AllocationInst &AI, bool isHeap);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000106
107 void visitPHINode(PHINode &PN);
Chris Lattner6e84bd72005-02-25 01:27:48 +0000108 void visitSelectInst(SelectInst &SI);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000109
Chris Lattner51340062002-11-08 05:00:44 +0000110 void visitGetElementPtrInst(User &GEP);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000111 void visitReturnInst(ReturnInst &RI);
112 void visitLoadInst(LoadInst &LI);
113 void visitStoreInst(StoreInst &SI);
114 void visitCallInst(CallInst &CI);
Chris Lattner808a7ae2003-09-20 16:34:13 +0000115 void visitInvokeInst(InvokeInst &II);
Chris Lattner32672652005-03-05 19:04:31 +0000116 void visitSetCondInst(SetCondInst &SCI);
Vikram S. Advebac06222002-12-06 21:17:10 +0000117 void visitFreeInst(FreeInst &FI);
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000118 void visitCastInst(CastInst &CI);
Chris Lattner878e5212003-02-04 00:59:50 +0000119 void visitInstruction(Instruction &I);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000120
Chris Lattner808a7ae2003-09-20 16:34:13 +0000121 void visitCallSite(CallSite CS);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000122 void visitVAArgInst(VAArgInst &I);
Chris Lattner26c4fc32003-09-20 21:48:16 +0000123
124 void MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000125 private:
126 // Helper functions used to implement the visitation functions...
127
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000128 /// createNode - Create a new DSNode, ensuring that it is properly added to
129 /// the graph.
130 ///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000131 DSNode *createNode(const Type *Ty = 0) {
132 DSNode *N = new DSNode(Ty, &G); // Create the node
Chris Lattnere158b192003-06-16 12:08:18 +0000133 if (DisableFieldSensitivity) {
Chris Lattner2412a052004-05-23 21:14:09 +0000134 // Create node handle referring to the old node so that it is
135 // immediately removed from the graph when the node handle is destroyed.
136 DSNodeHandle OldNNH = N;
Chris Lattnerca3f7902003-02-08 20:18:39 +0000137 N->foldNodeCompletely();
Chris Lattnere158b192003-06-16 12:08:18 +0000138 if (DSNode *FN = N->getForwardNode())
139 N = FN;
140 }
Chris Lattner92673292002-11-02 00:13:20 +0000141 return N;
142 }
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000143
Chris Lattnerc875f022002-11-03 21:27:48 +0000144 /// setDestTo - Set the ScalarMap entry for the specified value to point to
Chris Lattner92673292002-11-02 00:13:20 +0000145 /// the specified destination. If the Value already points to a node, make
146 /// sure to merge the two destinations together.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000147 ///
Chris Lattner92673292002-11-02 00:13:20 +0000148 void setDestTo(Value &V, const DSNodeHandle &NH);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000149
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000150 /// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000151 ///
Chris Lattner92673292002-11-02 00:13:20 +0000152 DSNodeHandle getValueDest(Value &V);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000153
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000154 /// getLink - This method is used to return the specified link in the
155 /// specified node if one exists. If a link does not already exist (it's
Chris Lattner7e51c872002-10-31 06:52:26 +0000156 /// null), then we create a new node, link it, then return it.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000157 ///
Chris Lattner7e51c872002-10-31 06:52:26 +0000158 DSNodeHandle &getLink(const DSNodeHandle &Node, unsigned Link = 0);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000159 };
160}
161
Brian Gaeked0fde302003-11-11 22:41:34 +0000162using namespace DS;
163
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000164//===----------------------------------------------------------------------===//
165// DSGraph constructor - Simply use the GraphBuilder to construct the local
166// graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000167DSGraph::DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td,
168 Function &F, DSGraph *GG)
169 : GlobalsGraph(GG), ScalarMap(ECs), TD(td) {
Chris Lattner2a068862002-11-10 06:53:38 +0000170 PrintAuxCalls = false;
Chris Lattner30514192003-07-02 04:37:26 +0000171
172 DEBUG(std::cerr << " [Loc] Calculating graph for: " << F.getName() << "\n");
173
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000174 // Use the graph builder to construct the local version of the graph
Chris Lattner26c4fc32003-09-20 21:48:16 +0000175 GraphBuilder B(F, *this, ReturnNodes[&F], FunctionCalls);
Chris Lattner4fe34612002-11-18 21:44:19 +0000176#ifndef NDEBUG
177 Timer::addPeakMemoryMeasurement();
178#endif
Chris Lattner1a1a85d2003-02-14 04:55:58 +0000179
Chris Lattnerc420ab62004-02-25 23:31:02 +0000180 // If there are any constant globals referenced in this function, merge their
181 // initializers into the local graph from the globals graph.
182 if (ScalarMap.global_begin() != ScalarMap.global_end()) {
183 ReachabilityCloner RC(*this, *GG, 0);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000184
Chris Lattnerc420ab62004-02-25 23:31:02 +0000185 for (DSScalarMap::global_iterator I = ScalarMap.global_begin();
186 I != ScalarMap.global_end(); ++I)
187 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
Chris Lattner76a9eb32004-03-03 23:00:19 +0000188 if (!GV->isExternal() && GV->isConstant())
Chris Lattnerc420ab62004-02-25 23:31:02 +0000189 RC.merge(ScalarMap[GV], GG->ScalarMap[GV]);
190 }
191
Chris Lattner394471f2003-01-23 22:05:33 +0000192 markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner96517252002-11-09 20:55:24 +0000193
194 // Remove any nodes made dead due to merging...
Chris Lattner394471f2003-01-23 22:05:33 +0000195 removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000196}
197
198
199//===----------------------------------------------------------------------===//
200// Helper method implementations...
201//
202
Chris Lattner92673292002-11-02 00:13:20 +0000203/// getValueDest - Return the DSNode that the actual value points to.
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000204///
Chris Lattner51340062002-11-08 05:00:44 +0000205DSNodeHandle GraphBuilder::getValueDest(Value &Val) {
206 Value *V = &Val;
Chris Lattner82962de2004-11-03 18:51:26 +0000207 if (isa<Constant>(V) && cast<Constant>(V)->isNullValue())
Chris Lattner51340062002-11-08 05:00:44 +0000208 return 0; // Null doesn't point to anything, don't add to ScalarMap!
Chris Lattner92673292002-11-02 00:13:20 +0000209
Vikram S. Advebac06222002-12-06 21:17:10 +0000210 DSNodeHandle &NH = ScalarMap[V];
Chris Lattner62c3a952004-10-30 04:22:45 +0000211 if (!NH.isNull())
Vikram S. Advebac06222002-12-06 21:17:10 +0000212 return NH; // Already have a node? Just return it...
213
214 // Otherwise we need to create a new node to point to.
215 // Check first for constant expressions that must be traversed to
216 // extract the actual value.
Reid Spencere8404342004-07-18 00:18:30 +0000217 DSNode* N;
218 if (GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
Chris Lattner48427b52005-03-20 01:18:00 +0000219 // Create a new global node for this global variable.
Reid Spencere8404342004-07-18 00:18:30 +0000220 N = createNode(GV->getType()->getElementType());
221 N->addGlobal(GV);
222 } else if (Constant *C = dyn_cast<Constant>(V)) {
223 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattnera513fb12005-03-22 02:45:13 +0000224 if (CE->getOpcode() == Instruction::Cast) {
225 if (isa<PointerType>(CE->getOperand(0)->getType()))
226 NH = getValueDest(*CE->getOperand(0));
227 else
228 NH = createNode()->setUnknownNodeMarker();
229 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
Chris Lattner51340062002-11-08 05:00:44 +0000230 visitGetElementPtrInst(*CE);
Chris Lattner62482e52004-01-28 09:15:42 +0000231 DSScalarMap::iterator I = ScalarMap.find(CE);
Chris Lattner2cfbaaf2002-11-09 20:14:03 +0000232 assert(I != ScalarMap.end() && "GEP didn't get processed right?");
Chris Lattner1e56c542003-02-09 23:04:12 +0000233 NH = I->second;
234 } else {
235 // This returns a conservative unknown node for any unhandled ConstExpr
Chris Lattnerbd92b732003-06-19 21:15:11 +0000236 return NH = createNode()->setUnknownNodeMarker();
Chris Lattner51340062002-11-08 05:00:44 +0000237 }
Chris Lattner62c3a952004-10-30 04:22:45 +0000238 if (NH.isNull()) { // (getelementptr null, X) returns null
Chris Lattner1e56c542003-02-09 23:04:12 +0000239 ScalarMap.erase(V);
240 return 0;
241 }
242 return NH;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000243 } else if (isa<UndefValue>(C)) {
244 ScalarMap.erase(V);
245 return 0;
Chris Lattner51340062002-11-08 05:00:44 +0000246 } else {
247 assert(0 && "Unknown constant type!");
248 }
Reid Spencere8404342004-07-18 00:18:30 +0000249 N = createNode(); // just create a shadow node
Chris Lattner92673292002-11-02 00:13:20 +0000250 } else {
251 // Otherwise just create a shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000252 N = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000253 }
254
Chris Lattnerefffdc92004-07-07 06:12:52 +0000255 NH.setTo(N, 0); // Remember that we are pointing to it...
Chris Lattner92673292002-11-02 00:13:20 +0000256 return NH;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000257}
258
Chris Lattner0d9bab82002-07-18 00:12:30 +0000259
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000260/// getLink - This method is used to return the specified link in the
261/// specified node if one exists. If a link does not already exist (it's
262/// null), then we create a new node, link it, then return it. We must
263/// specify the type of the Node field we are accessing so that we know what
264/// type should be linked to if we need to create a new node.
265///
Chris Lattner7e51c872002-10-31 06:52:26 +0000266DSNodeHandle &GraphBuilder::getLink(const DSNodeHandle &node, unsigned LinkNo) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000267 DSNodeHandle &Node = const_cast<DSNodeHandle&>(node);
Chris Lattner08db7192002-11-06 06:20:27 +0000268 DSNodeHandle &Link = Node.getLink(LinkNo);
Chris Lattner62c3a952004-10-30 04:22:45 +0000269 if (Link.isNull()) {
Chris Lattner08db7192002-11-06 06:20:27 +0000270 // If the link hasn't been created yet, make and return a new shadow node
Chris Lattnerbd92b732003-06-19 21:15:11 +0000271 Link = createNode();
Chris Lattner08db7192002-11-06 06:20:27 +0000272 }
273 return Link;
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000274}
275
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000276
Chris Lattnerc875f022002-11-03 21:27:48 +0000277/// setDestTo - Set the ScalarMap entry for the specified value to point to the
Chris Lattner92673292002-11-02 00:13:20 +0000278/// specified destination. If the Value already points to a node, make sure to
279/// merge the two destinations together.
280///
281void GraphBuilder::setDestTo(Value &V, const DSNodeHandle &NH) {
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000282 ScalarMap[&V].mergeWith(NH);
Chris Lattner92673292002-11-02 00:13:20 +0000283}
284
285
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000286//===----------------------------------------------------------------------===//
287// Specific instruction type handler implementations...
288//
289
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000290/// Alloca & Malloc instruction implementation - Simply create a new memory
291/// object, pointing the scalar to it.
292///
Chris Lattnerbd92b732003-06-19 21:15:11 +0000293void GraphBuilder::handleAlloc(AllocationInst &AI, bool isHeap) {
294 DSNode *N = createNode();
295 if (isHeap)
296 N->setHeapNodeMarker();
297 else
298 N->setAllocaNodeMarker();
299 setDestTo(AI, N);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000300}
301
302// PHINode - Make the scalar for the PHI node point to all of the things the
303// incoming values point to... which effectively causes them to be merged.
304//
305void GraphBuilder::visitPHINode(PHINode &PN) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000306 if (!isPointerType(PN.getType())) return; // Only pointer PHIs
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000307
Chris Lattnerc875f022002-11-03 21:27:48 +0000308 DSNodeHandle &PNDest = ScalarMap[&PN];
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000309 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
Chris Lattner92673292002-11-02 00:13:20 +0000310 PNDest.mergeWith(getValueDest(*PN.getIncomingValue(i)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000311}
312
Chris Lattner6e84bd72005-02-25 01:27:48 +0000313void GraphBuilder::visitSelectInst(SelectInst &SI) {
314 if (!isPointerType(SI.getType())) return; // Only pointer Selects
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000315
Chris Lattner6e84bd72005-02-25 01:27:48 +0000316 DSNodeHandle &Dest = ScalarMap[&SI];
317 Dest.mergeWith(getValueDest(*SI.getOperand(1)));
318 Dest.mergeWith(getValueDest(*SI.getOperand(2)));
319}
320
Chris Lattner32672652005-03-05 19:04:31 +0000321void GraphBuilder::visitSetCondInst(SetCondInst &SCI) {
322 if (!isPointerType(SCI.getOperand(0)->getType()) ||
323 isa<ConstantPointerNull>(SCI.getOperand(1))) return; // Only pointers
324 ScalarMap[SCI.getOperand(0)].mergeWith(getValueDest(*SCI.getOperand(1)));
325}
326
327
Chris Lattner51340062002-11-08 05:00:44 +0000328void GraphBuilder::visitGetElementPtrInst(User &GEP) {
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000329 DSNodeHandle Value = getValueDest(*GEP.getOperand(0));
Chris Lattner753b1132005-02-24 19:55:31 +0000330 if (Value.isNull())
331 Value = createNode();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000332
Chris Lattner179bc7d2003-11-14 17:09:46 +0000333 // As a special case, if all of the index operands of GEP are constant zeros,
334 // handle this just like we handle casts (ie, don't do much).
335 bool AllZeros = true;
336 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i)
337 if (GEP.getOperand(i) !=
338 Constant::getNullValue(GEP.getOperand(i)->getType())) {
339 AllZeros = false;
340 break;
341 }
342
343 // If all of the indices are zero, the result points to the operand without
344 // applying the type.
Chris Lattner0c9707a2005-03-18 23:18:20 +0000345 if (AllZeros || (!Value.isNull() &&
346 Value.getNode()->isNodeCompletelyFolded())) {
Chris Lattner179bc7d2003-11-14 17:09:46 +0000347 setDestTo(GEP, Value);
348 return;
349 }
350
351
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000352 const PointerType *PTy = cast<PointerType>(GEP.getOperand(0)->getType());
353 const Type *CurTy = PTy->getElementType();
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000354
Chris Lattner08db7192002-11-06 06:20:27 +0000355 if (Value.getNode()->mergeTypeInfo(CurTy, Value.getOffset())) {
356 // If the node had to be folded... exit quickly
Chris Lattner92673292002-11-02 00:13:20 +0000357 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000358 return;
359 }
360
Chris Lattner15869aa2003-11-02 22:27:28 +0000361 const TargetData &TD = Value.getNode()->getTargetData();
362
Chris Lattner08db7192002-11-06 06:20:27 +0000363#if 0
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000364 // Handle the pointer index specially...
365 if (GEP.getNumOperands() > 1 &&
Chris Lattner28977af2004-04-05 01:30:19 +0000366 (!isa<Constant>(GEP.getOperand(1)) ||
367 !cast<Constant>(GEP.getOperand(1))->isNullValue())) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000368
369 // If we already know this is an array being accessed, don't do anything...
370 if (!TopTypeRec.isArray) {
371 TopTypeRec.isArray = true;
372
373 // If we are treating some inner field pointer as an array, fold the node
374 // up because we cannot handle it right. This can come because of
375 // something like this: &((&Pt->X)[1]) == &Pt->Y
376 //
377 if (Value.getOffset()) {
378 // Value is now the pointer we want to GEP to be...
379 Value.getNode()->foldNodeCompletely();
Chris Lattner92673292002-11-02 00:13:20 +0000380 setDestTo(GEP, Value); // GEP result points to folded node
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000381 return;
382 } else {
383 // This is a pointer to the first byte of the node. Make sure that we
384 // are pointing to the outter most type in the node.
385 // FIXME: We need to check one more case here...
386 }
387 }
388 }
Chris Lattner08db7192002-11-06 06:20:27 +0000389#endif
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000390
391 // All of these subscripts are indexing INTO the elements we have...
Chris Lattner26c4fc32003-09-20 21:48:16 +0000392 unsigned Offset = 0;
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000393 for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
394 I != E; ++I)
395 if (const StructType *STy = dyn_cast<StructType>(*I)) {
Chris Lattner507bdf92005-01-12 04:51:37 +0000396 unsigned FieldNo =
397 (unsigned)cast<ConstantUInt>(I.getOperand())->getValue();
398 Offset += (unsigned)TD.getStructLayout(STy)->MemberOffsets[FieldNo];
Chris Lattner82e9d722004-03-01 19:02:54 +0000399 } else if (const PointerType *PTy = dyn_cast<PointerType>(*I)) {
400 if (!isa<Constant>(I.getOperand()) ||
401 !cast<Constant>(I.getOperand())->isNullValue())
402 Value.getNode()->setArrayMarker();
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000403 }
404
405
Chris Lattner08db7192002-11-06 06:20:27 +0000406#if 0
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000407 if (const SequentialType *STy = cast<SequentialType>(*I)) {
408 CurTy = STy->getElementType();
Chris Lattnere03f32b2002-10-02 06:24:36 +0000409 if (ConstantSInt *CS = dyn_cast<ConstantSInt>(GEP.getOperand(i))) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000410 Offset += CS->getValue()*TD.getTypeSize(CurTy);
Chris Lattnere03f32b2002-10-02 06:24:36 +0000411 } else {
412 // Variable index into a node. We must merge all of the elements of the
413 // sequential type here.
414 if (isa<PointerType>(STy))
415 std::cerr << "Pointer indexing not handled yet!\n";
416 else {
417 const ArrayType *ATy = cast<ArrayType>(STy);
418 unsigned ElSize = TD.getTypeSize(CurTy);
419 DSNode *N = Value.getNode();
420 assert(N && "Value must have a node!");
421 unsigned RawOffset = Offset+Value.getOffset();
422
423 // Loop over all of the elements of the array, merging them into the
Misha Brukman2f2d0652003-09-11 18:14:24 +0000424 // zeroth element.
Chris Lattnere03f32b2002-10-02 06:24:36 +0000425 for (unsigned i = 1, e = ATy->getNumElements(); i != e; ++i)
426 // Merge all of the byte components of this array element
427 for (unsigned j = 0; j != ElSize; ++j)
428 N->mergeIndexes(RawOffset+j, RawOffset+i*ElSize+j);
429 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000430 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000431 }
Chris Lattnerfa3711a2003-11-25 20:19:55 +0000432#endif
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000433
434 // Add in the offset calculated...
435 Value.setOffset(Value.getOffset()+Offset);
436
Sumant Kowshik8a3802d2005-12-06 18:04:30 +0000437 // Check the offset
438 DSNode *N = Value.getNode();
439 if (N &&
440 !N->isNodeCompletelyFolded() &&
441 (N->getSize() != 0 || Offset != 0) &&
442 !N->isForwarding()) {
443 if ((Offset >= N->getSize()) || int(Offset) < 0) {
444 // Accessing offsets out of node size range
445 // This is seen in the "magic" struct in named (from bind), where the
446 // fourth field is an array of length 0, presumably used to create struct
447 // instances of different sizes
448
449 // Collapse the node since its size is now variable
450 N->foldNodeCompletely();
451 }
452 }
453
454 // Value is now the pointer we want to GEP to be...
Chris Lattner92673292002-11-02 00:13:20 +0000455 setDestTo(GEP, Value);
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000456}
457
458void GraphBuilder::visitLoadInst(LoadInst &LI) {
Chris Lattner92673292002-11-02 00:13:20 +0000459 DSNodeHandle Ptr = getValueDest(*LI.getOperand(0));
Chris Lattner6e84bd72005-02-25 01:27:48 +0000460 if (Ptr.isNull())
461 Ptr = createNode();
Chris Lattner92673292002-11-02 00:13:20 +0000462
463 // Make that the node is read from...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000464 Ptr.getNode()->setReadMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000465
466 // Ensure a typerecord exists...
Chris Lattner088b6392003-03-03 17:13:31 +0000467 Ptr.getNode()->mergeTypeInfo(LI.getType(), Ptr.getOffset(), false);
Chris Lattner92673292002-11-02 00:13:20 +0000468
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000469 if (isPointerType(LI.getType()))
Chris Lattner92673292002-11-02 00:13:20 +0000470 setDestTo(LI, getLink(Ptr));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000471}
472
473void GraphBuilder::visitStoreInst(StoreInst &SI) {
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000474 const Type *StoredTy = SI.getOperand(0)->getType();
Chris Lattner92673292002-11-02 00:13:20 +0000475 DSNodeHandle Dest = getValueDest(*SI.getOperand(1));
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000476 if (Dest.isNull()) return;
Chris Lattner92673292002-11-02 00:13:20 +0000477
Vikram S. Advebac06222002-12-06 21:17:10 +0000478 // Mark that the node is written to...
Chris Lattnerbd92b732003-06-19 21:15:11 +0000479 Dest.getNode()->setModifiedMarker();
Chris Lattner8f0a16e2002-10-31 05:45:02 +0000480
Chris Lattner26c4fc32003-09-20 21:48:16 +0000481 // Ensure a type-record exists...
Chris Lattner08db7192002-11-06 06:20:27 +0000482 Dest.getNode()->mergeTypeInfo(StoredTy, Dest.getOffset());
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000483
484 // Avoid adding edges from null, or processing non-"pointer" stores
Chris Lattner92673292002-11-02 00:13:20 +0000485 if (isPointerType(StoredTy))
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000486 Dest.addEdgeTo(getValueDest(*SI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000487}
488
489void GraphBuilder::visitReturnInst(ReturnInst &RI) {
Chris Lattner92673292002-11-02 00:13:20 +0000490 if (RI.getNumOperands() && isPointerType(RI.getOperand(0)->getType()))
Chris Lattner26c4fc32003-09-20 21:48:16 +0000491 RetNode->mergeWith(getValueDest(*RI.getOperand(0)));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000492}
493
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000494void GraphBuilder::visitVAArgInst(VAArgInst &I) {
Andrew Lenharth558bc882005-06-18 18:34:52 +0000495 //FIXME: also updates the argument
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000496 DSNodeHandle Ptr = getValueDest(*I.getOperand(0));
497 if (Ptr.isNull()) return;
498
499 // Make that the node is read from.
500 Ptr.getNode()->setReadMarker();
501
Chris Lattner62c3a952004-10-30 04:22:45 +0000502 // Ensure a type record exists.
503 DSNode *PtrN = Ptr.getNode();
504 PtrN->mergeTypeInfo(I.getType(), Ptr.getOffset(), false);
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000505
506 if (isPointerType(I.getType()))
507 setDestTo(I, getLink(Ptr));
508}
509
510
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000511void GraphBuilder::visitCallInst(CallInst &CI) {
Chris Lattner808a7ae2003-09-20 16:34:13 +0000512 visitCallSite(&CI);
513}
514
515void GraphBuilder::visitInvokeInst(InvokeInst &II) {
516 visitCallSite(&II);
517}
518
519void GraphBuilder::visitCallSite(CallSite CS) {
Chris Lattnercb582402004-02-26 22:07:22 +0000520 Value *Callee = CS.getCalledValue();
Chris Lattnercb582402004-02-26 22:07:22 +0000521
Chris Lattner894263b2003-09-20 16:50:46 +0000522 // Special case handling of certain libc allocation functions here.
Chris Lattnercb582402004-02-26 22:07:22 +0000523 if (Function *F = dyn_cast<Function>(Callee))
Chris Lattner894263b2003-09-20 16:50:46 +0000524 if (F->isExternal())
Chris Lattnera07b72f2004-02-13 16:09:54 +0000525 switch (F->getIntrinsicID()) {
Chris Lattner317201d2004-03-13 00:24:00 +0000526 case Intrinsic::vastart:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000527 getValueDest(*CS.getInstruction()).getNode()->setAllocaNodeMarker();
528 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000529 case Intrinsic::vacopy:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000530 getValueDest(*CS.getInstruction()).
531 mergeWith(getValueDest(**(CS.arg_begin())));
532 return;
Chris Lattner317201d2004-03-13 00:24:00 +0000533 case Intrinsic::vaend:
Chris Lattner6b3e3cc2004-03-04 20:33:47 +0000534 return; // noop
Chris Lattnera07b72f2004-02-13 16:09:54 +0000535 case Intrinsic::memmove:
536 case Intrinsic::memcpy: {
537 // Merge the first & second arguments, and mark the memory read and
Chris Lattnerfb8c6102003-11-08 21:55:50 +0000538 // modified.
Chris Lattnera07b72f2004-02-13 16:09:54 +0000539 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
Chris Lattner67ce57a2003-11-09 03:32:52 +0000540 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
541 if (DSNode *N = RetNH.getNode())
542 N->setModifiedMarker()->setReadMarker();
543 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000544 }
Chris Lattnereee33b22004-02-16 18:37:40 +0000545 case Intrinsic::memset:
546 // Mark the memory modified.
547 if (DSNode *N = getValueDest(**CS.arg_begin()).getNode())
548 N->setModifiedMarker();
549 return;
Chris Lattnera07b72f2004-02-13 16:09:54 +0000550 default:
Vikram S. Advee4e97ef2004-05-25 08:14:52 +0000551 if (F->getName() == "calloc" || F->getName() == "posix_memalign" ||
552 F->getName() == "memalign" || F->getName() == "valloc") {
Chris Lattnera07b72f2004-02-13 16:09:54 +0000553 setDestTo(*CS.getInstruction(),
554 createNode()->setHeapNodeMarker()->setModifiedMarker());
555 return;
556 } else if (F->getName() == "realloc") {
557 DSNodeHandle RetNH = getValueDest(*CS.getInstruction());
Chris Lattner82962de2004-11-03 18:51:26 +0000558 if (CS.arg_begin() != CS.arg_end())
559 RetNH.mergeWith(getValueDest(**CS.arg_begin()));
Chris Lattnera07b72f2004-02-13 16:09:54 +0000560 if (DSNode *N = RetNH.getNode())
561 N->setHeapNodeMarker()->setModifiedMarker()->setReadMarker();
562 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000563 } else if (F->getName() == "memmove") {
564 // Merge the first & second arguments, and mark the memory read and
565 // modified.
566 DSNodeHandle RetNH = getValueDest(**CS.arg_begin());
567 RetNH.mergeWith(getValueDest(**(CS.arg_begin()+1)));
568 if (DSNode *N = RetNH.getNode())
569 N->setModifiedMarker()->setReadMarker();
570 return;
571
Chris Lattnerd5612092004-02-24 22:02:48 +0000572 } else if (F->getName() == "atoi" || F->getName() == "atof" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000573 F->getName() == "atol" || F->getName() == "atoll" ||
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000574 F->getName() == "remove" || F->getName() == "unlink" ||
Chris Lattneradc1efe2004-02-25 17:43:20 +0000575 F->getName() == "rename" || F->getName() == "memcmp" ||
576 F->getName() == "strcmp" || F->getName() == "strncmp" ||
577 F->getName() == "execl" || F->getName() == "execlp" ||
578 F->getName() == "execle" || F->getName() == "execv" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000579 F->getName() == "execvp" || F->getName() == "chmod" ||
580 F->getName() == "puts" || F->getName() == "write" ||
581 F->getName() == "open" || F->getName() == "create" ||
582 F->getName() == "truncate" || F->getName() == "chdir" ||
583 F->getName() == "mkdir" || F->getName() == "rmdir") {
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000584 // These functions read all of their pointer operands.
585 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
586 AI != E; ++AI) {
587 if (isPointerType((*AI)->getType()))
588 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000589 N->setReadMarker();
Chris Lattner39bb2dc2004-02-24 22:17:00 +0000590 }
Chris Lattner304e1432004-02-16 22:57:19 +0000591 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000592 } else if (F->getName() == "read" || F->getName() == "pipe" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000593 F->getName() == "wait" || F->getName() == "time") {
Chris Lattner52fc8d72004-02-25 23:06:40 +0000594 // These functions write all of their pointer operands.
595 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
596 AI != E; ++AI) {
597 if (isPointerType((*AI)->getType()))
598 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000599 N->setModifiedMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000600 }
601 return;
Chris Lattneradc1efe2004-02-25 17:43:20 +0000602 } else if (F->getName() == "stat" || F->getName() == "fstat" ||
603 F->getName() == "lstat") {
604 // These functions read their first operand if its a pointer.
605 CallSite::arg_iterator AI = CS.arg_begin();
606 if (isPointerType((*AI)->getType())) {
607 DSNodeHandle Path = getValueDest(**AI);
608 if (DSNode *N = Path.getNode()) N->setReadMarker();
609 }
Chris Lattner304e1432004-02-16 22:57:19 +0000610
Chris Lattneradc1efe2004-02-25 17:43:20 +0000611 // Then they write into the stat buffer.
612 DSNodeHandle StatBuf = getValueDest(**++AI);
613 if (DSNode *N = StatBuf.getNode()) {
614 N->setModifiedMarker();
615 const Type *StatTy = F->getFunctionType()->getParamType(1);
616 if (const PointerType *PTy = dyn_cast<PointerType>(StatTy))
617 N->mergeTypeInfo(PTy->getElementType(), StatBuf.getOffset());
618 }
Chris Lattneradc1efe2004-02-25 17:43:20 +0000619 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000620 } else if (F->getName() == "strtod" || F->getName() == "strtof" ||
621 F->getName() == "strtold") {
622 // These functions read the first pointer
623 if (DSNode *Str = getValueDest(**CS.arg_begin()).getNode()) {
624 Str->setReadMarker();
625 // If the second parameter is passed, it will point to the first
626 // argument node.
627 const DSNodeHandle &EndPtrNH = getValueDest(**(CS.arg_begin()+1));
628 if (DSNode *End = EndPtrNH.getNode()) {
629 End->mergeTypeInfo(PointerType::get(Type::SByteTy),
630 EndPtrNH.getOffset(), false);
631 End->setModifiedMarker();
632 DSNodeHandle &Link = getLink(EndPtrNH);
633 Link.mergeWith(getValueDest(**CS.arg_begin()));
634 }
635 }
636
637 return;
Chris Lattner6b586df2004-02-27 20:04:48 +0000638 } else if (F->getName() == "fopen" || F->getName() == "fdopen" ||
639 F->getName() == "freopen") {
640 // These functions read all of their pointer operands.
641 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
642 AI != E; ++AI)
643 if (isPointerType((*AI)->getType()))
644 if (DSNode *N = getValueDest(**AI).getNode())
645 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000646
Chris Lattner68300db2004-02-13 20:05:32 +0000647 // fopen allocates in an unknown way and writes to the file
648 // descriptor. Also, merge the allocated type into the node.
649 DSNodeHandle Result = getValueDest(*CS.getInstruction());
Chris Lattnerd5612092004-02-24 22:02:48 +0000650 if (DSNode *N = Result.getNode()) {
651 N->setModifiedMarker()->setUnknownNodeMarker();
652 const Type *RetTy = F->getFunctionType()->getReturnType();
653 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
654 N->mergeTypeInfo(PTy->getElementType(), Result.getOffset());
655 }
Chris Lattner6b586df2004-02-27 20:04:48 +0000656
657 // If this is freopen, merge the file descriptor passed in with the
658 // result.
Chris Lattnerfe781652004-12-08 16:22:26 +0000659 if (F->getName() == "freopen") {
660 // ICC doesn't handle getting the iterator, decrementing and
661 // dereferencing it in one operation without error. Do it in 2 steps
662 CallSite::arg_iterator compit = CS.arg_end();
663 Result.mergeWith(getValueDest(**--compit));
664 }
Chris Lattnerd5612092004-02-24 22:02:48 +0000665 return;
Chris Lattner68300db2004-02-13 20:05:32 +0000666 } else if (F->getName() == "fclose" && CS.arg_end()-CS.arg_begin() ==1){
667 // fclose reads and deallocates the memory in an unknown way for the
668 // file descriptor. It merges the FILE type into the descriptor.
669 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000670 if (DSNode *N = H.getNode()) {
671 N->setReadMarker()->setUnknownNodeMarker();
672 const Type *ArgTy = F->getFunctionType()->getParamType(0);
673 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
674 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
675 }
Chris Lattner68300db2004-02-13 20:05:32 +0000676 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000677 } else if (CS.arg_end()-CS.arg_begin() == 1 &&
Chris Lattner304e1432004-02-16 22:57:19 +0000678 (F->getName() == "fflush" || F->getName() == "feof" ||
679 F->getName() == "fileno" || F->getName() == "clearerr" ||
Chris Lattner52fc8d72004-02-25 23:06:40 +0000680 F->getName() == "rewind" || F->getName() == "ftell" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000681 F->getName() == "ferror" || F->getName() == "fgetc" ||
682 F->getName() == "fgetc" || F->getName() == "_IO_getc")) {
Chris Lattner304e1432004-02-16 22:57:19 +0000683 // fflush reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000684 // merges the FILE type into the descriptor.
685 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattnerd5612092004-02-24 22:02:48 +0000686 if (DSNode *N = H.getNode()) {
687 N->setReadMarker()->setModifiedMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000688
Chris Lattnerd5612092004-02-24 22:02:48 +0000689 const Type *ArgTy = F->getFunctionType()->getParamType(0);
690 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
691 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
692 }
693 return;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000694 } else if (CS.arg_end()-CS.arg_begin() == 4 &&
Chris Lattnerd5612092004-02-24 22:02:48 +0000695 (F->getName() == "fwrite" || F->getName() == "fread")) {
696 // fread writes the first operand, fwrite reads it. They both
697 // read/write the FILE descriptor, and merges the FILE type.
Chris Lattnerfe781652004-12-08 16:22:26 +0000698 CallSite::arg_iterator compit = CS.arg_end();
699 DSNodeHandle H = getValueDest(**--compit);
Chris Lattnerd5612092004-02-24 22:02:48 +0000700 if (DSNode *N = H.getNode()) {
701 N->setReadMarker()->setModifiedMarker();
702 const Type *ArgTy = F->getFunctionType()->getParamType(3);
703 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
704 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
705 }
706
707 H = getValueDest(**CS.arg_begin());
708 if (DSNode *N = H.getNode())
709 if (F->getName() == "fwrite")
710 N->setReadMarker();
711 else
712 N->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000713 return;
714 } else if (F->getName() == "fgets" && CS.arg_end()-CS.arg_begin() == 3){
Chris Lattner304e1432004-02-16 22:57:19 +0000715 // fgets reads and writes the memory for the file descriptor. It
Chris Lattner339d8df2004-02-13 21:21:48 +0000716 // merges the FILE type into the descriptor, and writes to the
717 // argument. It returns the argument as well.
718 CallSite::arg_iterator AI = CS.arg_begin();
719 DSNodeHandle H = getValueDest(**AI);
720 if (DSNode *N = H.getNode())
721 N->setModifiedMarker(); // Writes buffer
722 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
723 ++AI; ++AI;
724
725 // Reads and writes file descriptor, merge in FILE type.
Chris Lattneradc1efe2004-02-25 17:43:20 +0000726 H = getValueDest(**AI);
Chris Lattnerd5612092004-02-24 22:02:48 +0000727 if (DSNode *N = H.getNode()) {
Chris Lattner339d8df2004-02-13 21:21:48 +0000728 N->setReadMarker()->setModifiedMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000729 const Type *ArgTy = F->getFunctionType()->getParamType(2);
730 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
731 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
732 }
733 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000734 } else if (F->getName() == "ungetc" || F->getName() == "fputc" ||
735 F->getName() == "fputs" || F->getName() == "putc" ||
Chris Lattner6b586df2004-02-27 20:04:48 +0000736 F->getName() == "ftell" || F->getName() == "rewind" ||
737 F->getName() == "_IO_putc") {
738 // These functions read and write the memory for the file descriptor,
739 // which is passes as the last argument.
Chris Lattnerfe781652004-12-08 16:22:26 +0000740 CallSite::arg_iterator compit = CS.arg_end();
741 DSNodeHandle H = getValueDest(**--compit);
Chris Lattneradc1efe2004-02-25 17:43:20 +0000742 if (DSNode *N = H.getNode()) {
743 N->setReadMarker()->setModifiedMarker();
Chris Lattnerfe781652004-12-08 16:22:26 +0000744 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
745 const Type *ArgTy = *--compit2;
Chris Lattnerd5612092004-02-24 22:02:48 +0000746 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
747 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
748 }
Chris Lattner52fc8d72004-02-25 23:06:40 +0000749
750 // Any pointer arguments are read.
751 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
752 AI != E; ++AI)
753 if (isPointerType((*AI)->getType()))
754 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000755 N->setReadMarker();
Chris Lattner52fc8d72004-02-25 23:06:40 +0000756 return;
757 } else if (F->getName() == "fseek" || F->getName() == "fgetpos" ||
758 F->getName() == "fsetpos") {
759 // These functions read and write the memory for the file descriptor,
760 // and read/write all other arguments.
761 DSNodeHandle H = getValueDest(**CS.arg_begin());
762 if (DSNode *N = H.getNode()) {
Chris Lattnerfe781652004-12-08 16:22:26 +0000763 FunctionType::param_iterator compit2 = F->getFunctionType()->param_end();
764 const Type *ArgTy = *--compit2;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000765 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
766 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
767 }
768
769 // Any pointer arguments are read.
770 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
771 AI != E; ++AI)
772 if (isPointerType((*AI)->getType()))
773 if (DSNode *N = getValueDest(**AI).getNode())
774 N->setReadMarker()->setModifiedMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000775 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000776 } else if (F->getName() == "printf" || F->getName() == "fprintf" ||
777 F->getName() == "sprintf") {
Chris Lattner339d8df2004-02-13 21:21:48 +0000778 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
779
780 if (F->getName() == "fprintf") {
781 // fprintf reads and writes the FILE argument, and applies the type
782 // to it.
783 DSNodeHandle H = getValueDest(**AI);
784 if (DSNode *N = H.getNode()) {
785 N->setModifiedMarker();
786 const Type *ArgTy = (*AI)->getType();
787 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
788 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
789 }
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000790 } else if (F->getName() == "sprintf") {
791 // sprintf writes the first string argument.
792 DSNodeHandle H = getValueDest(**AI++);
793 if (DSNode *N = H.getNode()) {
794 N->setModifiedMarker();
795 const Type *ArgTy = (*AI)->getType();
796 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
797 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
798 }
Chris Lattner339d8df2004-02-13 21:21:48 +0000799 }
800
801 for (; AI != E; ++AI) {
802 // printf reads all pointer arguments.
803 if (isPointerType((*AI)->getType()))
804 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000805 N->setReadMarker();
Chris Lattner339d8df2004-02-13 21:21:48 +0000806 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000807 return;
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000808 } else if (F->getName() == "vprintf" || F->getName() == "vfprintf" ||
809 F->getName() == "vsprintf") {
810 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
811
812 if (F->getName() == "vfprintf") {
813 // ffprintf reads and writes the FILE argument, and applies the type
814 // to it.
815 DSNodeHandle H = getValueDest(**AI);
816 if (DSNode *N = H.getNode()) {
817 N->setModifiedMarker()->setReadMarker();
818 const Type *ArgTy = (*AI)->getType();
819 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
820 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
821 }
822 ++AI;
823 } else if (F->getName() == "vsprintf") {
824 // vsprintf writes the first string argument.
825 DSNodeHandle H = getValueDest(**AI++);
826 if (DSNode *N = H.getNode()) {
827 N->setModifiedMarker();
828 const Type *ArgTy = (*AI)->getType();
829 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
830 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
831 }
832 }
833
834 // Read the format
835 if (AI != E) {
836 if (isPointerType((*AI)->getType()))
837 if (DSNode *N = getValueDest(**AI).getNode())
838 N->setReadMarker();
839 ++AI;
840 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000841
Chris Lattner3aeb40c2004-03-04 21:03:54 +0000842 // Read the valist, and the pointed-to objects.
843 if (AI != E && isPointerType((*AI)->getType())) {
844 const DSNodeHandle &VAList = getValueDest(**AI);
845 if (DSNode *N = VAList.getNode()) {
846 N->setReadMarker();
847 N->mergeTypeInfo(PointerType::get(Type::SByteTy),
848 VAList.getOffset(), false);
849
850 DSNodeHandle &VAListObjs = getLink(VAList);
851 VAListObjs.getNode()->setReadMarker();
852 }
853 }
854
855 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000856 } else if (F->getName() == "scanf" || F->getName() == "fscanf" ||
857 F->getName() == "sscanf") {
858 CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
Chris Lattner339d8df2004-02-13 21:21:48 +0000859
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000860 if (F->getName() == "fscanf") {
861 // fscanf reads and writes the FILE argument, and applies the type
862 // to it.
863 DSNodeHandle H = getValueDest(**AI);
864 if (DSNode *N = H.getNode()) {
865 N->setReadMarker();
866 const Type *ArgTy = (*AI)->getType();
867 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
868 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
869 }
870 } else if (F->getName() == "sscanf") {
871 // sscanf reads the first string argument.
872 DSNodeHandle H = getValueDest(**AI++);
873 if (DSNode *N = H.getNode()) {
874 N->setReadMarker();
875 const Type *ArgTy = (*AI)->getType();
876 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
877 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
878 }
879 }
880
881 for (; AI != E; ++AI) {
882 // scanf writes all pointer arguments.
883 if (isPointerType((*AI)->getType()))
884 if (DSNode *N = getValueDest(**AI).getNode())
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000885 N->setModifiedMarker();
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000886 }
Chris Lattner4e46e322004-02-20 23:27:09 +0000887 return;
Chris Lattner8ecc27e2004-02-20 20:27:11 +0000888 } else if (F->getName() == "strtok") {
889 // strtok reads and writes the first argument, returning it. It reads
890 // its second arg. FIXME: strtok also modifies some hidden static
891 // data. Someday this might matter.
892 CallSite::arg_iterator AI = CS.arg_begin();
893 DSNodeHandle H = getValueDest(**AI++);
894 if (DSNode *N = H.getNode()) {
895 N->setReadMarker()->setModifiedMarker(); // Reads/Writes buffer
896 const Type *ArgTy = F->getFunctionType()->getParamType(0);
897 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
898 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
899 }
900 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
901
902 H = getValueDest(**AI); // Reads delimiter
903 if (DSNode *N = H.getNode()) {
904 N->setReadMarker();
905 const Type *ArgTy = F->getFunctionType()->getParamType(1);
906 if (const PointerType *PTy = dyn_cast<PointerType>(ArgTy))
907 N->mergeTypeInfo(PTy->getElementType(), H.getOffset());
908 }
909 return;
Chris Lattner1fe98742004-02-26 03:43:08 +0000910 } else if (F->getName() == "strchr" || F->getName() == "strrchr" ||
911 F->getName() == "strstr") {
912 // These read their arguments, and return the first one
Chris Lattneradc1efe2004-02-25 17:43:20 +0000913 DSNodeHandle H = getValueDest(**CS.arg_begin());
Chris Lattner1fe98742004-02-26 03:43:08 +0000914 H.mergeWith(getValueDest(*CS.getInstruction())); // Returns buffer
915
916 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
917 AI != E; ++AI)
918 if (isPointerType((*AI)->getType()))
919 if (DSNode *N = getValueDest(**AI).getNode())
920 N->setReadMarker();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000921
Chris Lattneradc1efe2004-02-25 17:43:20 +0000922 if (DSNode *N = H.getNode())
923 N->setReadMarker();
Chris Lattneradc1efe2004-02-25 17:43:20 +0000924 return;
Chris Lattnerbeacefa2004-11-08 21:08:28 +0000925 } else if (F->getName() == "__assert_fail") {
926 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
927 AI != E; ++AI)
928 if (isPointerType((*AI)->getType()))
929 if (DSNode *N = getValueDest(**AI).getNode())
930 N->setReadMarker();
931 return;
Chris Lattner52fc8d72004-02-25 23:06:40 +0000932 } else if (F->getName() == "modf" && CS.arg_end()-CS.arg_begin() == 2) {
933 // This writes its second argument, and forces it to double.
Chris Lattnerfe781652004-12-08 16:22:26 +0000934 CallSite::arg_iterator compit = CS.arg_end();
935 DSNodeHandle H = getValueDest(**--compit);
Chris Lattner52fc8d72004-02-25 23:06:40 +0000936 if (DSNode *N = H.getNode()) {
937 N->setModifiedMarker();
938 N->mergeTypeInfo(Type::DoubleTy, H.getOffset());
939 }
940 return;
Chris Lattner339d8df2004-02-13 21:21:48 +0000941 } else {
Chris Lattner304e1432004-02-16 22:57:19 +0000942 // Unknown function, warn if it returns a pointer type or takes a
943 // pointer argument.
944 bool Warn = isPointerType(CS.getInstruction()->getType());
945 if (!Warn)
946 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
947 I != E; ++I)
948 if (isPointerType((*I)->getType())) {
949 Warn = true;
950 break;
951 }
952 if (Warn)
953 std::cerr << "WARNING: Call to unknown external function '"
954 << F->getName() << "' will cause pessimistic results!\n";
Chris Lattnera07b72f2004-02-13 16:09:54 +0000955 }
Chris Lattner894263b2003-09-20 16:50:46 +0000956 }
957
958
Chris Lattnerc314ac42002-07-11 20:32:02 +0000959 // Set up the return value...
Chris Lattner0969c502002-10-21 02:08:03 +0000960 DSNodeHandle RetVal;
Chris Lattner808a7ae2003-09-20 16:34:13 +0000961 Instruction *I = CS.getInstruction();
962 if (isPointerType(I->getType()))
963 RetVal = getValueDest(*I);
Chris Lattnerc314ac42002-07-11 20:32:02 +0000964
Chris Lattnercb582402004-02-26 22:07:22 +0000965 DSNode *CalleeNode = 0;
966 if (DisableDirectCallOpt || !isa<Function>(Callee)) {
967 CalleeNode = getValueDest(*Callee).getNode();
968 if (CalleeNode == 0) {
969 std::cerr << "WARNING: Program is calling through a null pointer?\n"<< *I;
Chris Lattnerfbc2d842003-09-24 23:42:58 +0000970 return; // Calling a null pointer?
971 }
972 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000973
Chris Lattner0969c502002-10-21 02:08:03 +0000974 std::vector<DSNodeHandle> Args;
Chris Lattner808a7ae2003-09-20 16:34:13 +0000975 Args.reserve(CS.arg_end()-CS.arg_begin());
Chris Lattner0969c502002-10-21 02:08:03 +0000976
977 // Calculate the arguments vector...
Chris Lattner808a7ae2003-09-20 16:34:13 +0000978 for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
979 if (isPointerType((*I)->getType()))
980 Args.push_back(getValueDest(**I));
Chris Lattner0969c502002-10-21 02:08:03 +0000981
982 // Add a new function call entry...
Chris Lattnercb582402004-02-26 22:07:22 +0000983 if (CalleeNode)
984 FunctionCalls->push_back(DSCallSite(CS, RetVal, CalleeNode, Args));
Chris Lattner923fc052003-02-05 21:59:58 +0000985 else
Chris Lattnercb582402004-02-26 22:07:22 +0000986 FunctionCalls->push_back(DSCallSite(CS, RetVal, cast<Function>(Callee),
Chris Lattner26c4fc32003-09-20 21:48:16 +0000987 Args));
Chris Lattnerc68c31b2002-07-10 22:38:08 +0000988}
Chris Lattner055dc2c2002-07-18 15:54:42 +0000989
Vikram S. Advebac06222002-12-06 21:17:10 +0000990void GraphBuilder::visitFreeInst(FreeInst &FI) {
Vikram S. Advebac06222002-12-06 21:17:10 +0000991 // Mark that the node is written to...
Chris Lattnerd5612092004-02-24 22:02:48 +0000992 if (DSNode *N = getValueDest(*FI.getOperand(0)).getNode())
993 N->setModifiedMarker()->setHeapNodeMarker();
Vikram S. Advebac06222002-12-06 21:17:10 +0000994}
995
Chris Lattnerfccd06f2002-10-01 22:33:50 +0000996/// Handle casts...
997void GraphBuilder::visitCastInst(CastInst &CI) {
Chris Lattner5af344d2002-11-02 00:36:03 +0000998 if (isPointerType(CI.getType()))
999 if (isPointerType(CI.getOperand(0)->getType())) {
Chris Lattner157b2522004-10-06 19:29:13 +00001000 DSNodeHandle Ptr = getValueDest(*CI.getOperand(0));
1001 if (Ptr.getNode() == 0) return;
1002
Chris Lattner5af344d2002-11-02 00:36:03 +00001003 // Cast one pointer to the other, just act like a copy instruction
Chris Lattner157b2522004-10-06 19:29:13 +00001004 setDestTo(CI, Ptr);
Chris Lattner5af344d2002-11-02 00:36:03 +00001005 } else {
1006 // Cast something (floating point, small integer) to a pointer. We need
1007 // to track the fact that the node points to SOMETHING, just something we
1008 // don't know about. Make an "Unknown" node.
1009 //
Chris Lattnerbd92b732003-06-19 21:15:11 +00001010 setDestTo(CI, createNode()->setUnknownNodeMarker());
Chris Lattner5af344d2002-11-02 00:36:03 +00001011 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001012}
Chris Lattner055dc2c2002-07-18 15:54:42 +00001013
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001014
Chris Lattner878e5212003-02-04 00:59:50 +00001015// visitInstruction - For all other instruction types, if we have any arguments
1016// that are of pointer type, make them have unknown composition bits, and merge
1017// the nodes together.
1018void GraphBuilder::visitInstruction(Instruction &Inst) {
1019 DSNodeHandle CurNode;
1020 if (isPointerType(Inst.getType()))
1021 CurNode = getValueDest(Inst);
1022 for (User::op_iterator I = Inst.op_begin(), E = Inst.op_end(); I != E; ++I)
1023 if (isPointerType((*I)->getType()))
1024 CurNode.mergeWith(getValueDest(**I));
1025
Chris Lattner62c3a952004-10-30 04:22:45 +00001026 if (DSNode *N = CurNode.getNode())
1027 N->setUnknownNodeMarker();
Chris Lattner878e5212003-02-04 00:59:50 +00001028}
1029
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001030
1031
1032//===----------------------------------------------------------------------===//
1033// LocalDataStructures Implementation
1034//===----------------------------------------------------------------------===//
1035
Chris Lattner26c4fc32003-09-20 21:48:16 +00001036// MergeConstantInitIntoNode - Merge the specified constant into the node
1037// pointed to by NH.
1038void GraphBuilder::MergeConstantInitIntoNode(DSNodeHandle &NH, Constant *C) {
1039 // Ensure a type-record exists...
Chris Lattner62c3a952004-10-30 04:22:45 +00001040 DSNode *NHN = NH.getNode();
1041 NHN->mergeTypeInfo(C->getType(), NH.getOffset());
Chris Lattner26c4fc32003-09-20 21:48:16 +00001042
1043 if (C->getType()->isFirstClassType()) {
1044 if (isPointerType(C->getType()))
1045 // Avoid adding edges from null, or processing non-"pointer" stores
1046 NH.addEdgeTo(getValueDest(*C));
1047 return;
1048 }
Chris Lattner15869aa2003-11-02 22:27:28 +00001049
1050 const TargetData &TD = NH.getNode()->getTargetData();
1051
Chris Lattner26c4fc32003-09-20 21:48:16 +00001052 if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) {
1053 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1054 // We don't currently do any indexing for arrays...
1055 MergeConstantInitIntoNode(NH, cast<Constant>(CA->getOperand(i)));
1056 } else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
1057 const StructLayout *SL = TD.getStructLayout(CS->getType());
1058 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
Chris Lattner62c3a952004-10-30 04:22:45 +00001059 DSNode *NHN = NH.getNode();
Chris Lattner507bdf92005-01-12 04:51:37 +00001060 DSNodeHandle NewNH(NHN, NH.getOffset()+(unsigned)SL->MemberOffsets[i]);
Chris Lattner26c4fc32003-09-20 21:48:16 +00001061 MergeConstantInitIntoNode(NewNH, cast<Constant>(CS->getOperand(i)));
1062 }
Chris Lattner48b2f6b2004-10-26 16:23:03 +00001063 } else if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) {
Chris Lattner896481e2004-02-15 05:53:42 +00001064 // Noop
Chris Lattner26c4fc32003-09-20 21:48:16 +00001065 } else {
1066 assert(0 && "Unknown constant type!");
1067 }
1068}
1069
1070void GraphBuilder::mergeInGlobalInitializer(GlobalVariable *GV) {
1071 assert(!GV->isExternal() && "Cannot merge in external global!");
1072 // Get a node handle to the global node and merge the initializer into it.
1073 DSNodeHandle NH = getValueDest(*GV);
1074 MergeConstantInitIntoNode(NH, GV->getInitializer());
1075}
1076
1077
Chris Lattner9b426bd2005-03-20 03:32:35 +00001078/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
1079/// contains multiple globals, DSA will never, ever, be able to tell the globals
1080/// apart. Instead of maintaining this information in all of the graphs
1081/// throughout the entire program, store only a single global (the "leader") in
1082/// the graphs, and build equivalence classes for the rest of the globals.
1083static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
1084 DSScalarMap &SM = GG.getScalarMap();
1085 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1086 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
1087 I != E; ++I) {
1088 if (I->getGlobalsList().size() <= 1) continue;
1089
1090 // First, build up the equivalence set for this block of globals.
1091 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
1092 GlobalValue *First = GVs[0];
1093 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
1094 GlobalECs.unionSets(First, GVs[i]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001095
Chris Lattner9b426bd2005-03-20 03:32:35 +00001096 // Next, get the leader element.
1097 assert(First == GlobalECs.getLeaderValue(First) &&
1098 "First did not end up being the leader?");
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001099
Chris Lattner9b426bd2005-03-20 03:32:35 +00001100 // Next, remove all globals from the scalar map that are not the leader.
1101 assert(GVs[0] == First && "First had to be at the front!");
1102 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
1103 ECGlobals.insert(GVs[i]);
1104 SM.erase(SM.find(GVs[i]));
1105 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001106
Chris Lattner9b426bd2005-03-20 03:32:35 +00001107 // Finally, change the global node to only contain the leader.
1108 I->clearGlobals();
1109 I->addGlobal(First);
1110 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001111
Chris Lattner9b426bd2005-03-20 03:32:35 +00001112 DEBUG(GG.AssertGraphOK());
1113}
1114
1115/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
1116/// really just equivalent to some other globals, remove the globals from the
1117/// specified DSGraph (if present), and merge any nodes with their leader nodes.
1118static void EliminateUsesOfECGlobals(DSGraph &G,
1119 const std::set<GlobalValue*> &ECGlobals) {
1120 DSScalarMap &SM = G.getScalarMap();
1121 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
1122
1123 bool MadeChange = false;
1124 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
1125 GI != E; ) {
1126 GlobalValue *GV = *GI++;
1127 if (!ECGlobals.count(GV)) continue;
1128
1129 const DSNodeHandle &GVNH = SM[GV];
1130 assert(!GVNH.isNull() && "Global has null NH!?");
1131
1132 // Okay, this global is in some equivalence class. Start by finding the
1133 // leader of the class.
1134 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
1135
1136 // If the leader isn't already in the graph, insert it into the node
1137 // corresponding to GV.
1138 if (!SM.global_count(Leader)) {
1139 GVNH.getNode()->addGlobal(Leader);
1140 SM[Leader] = GVNH;
1141 } else {
1142 // Otherwise, the leader is in the graph, make sure the nodes are the
1143 // merged in the specified graph.
1144 const DSNodeHandle &LNH = SM[Leader];
1145 if (LNH.getNode() != GVNH.getNode())
1146 LNH.mergeWith(GVNH);
1147 }
1148
1149 // Next step, remove the global from the DSNode.
1150 GVNH.getNode()->removeGlobal(GV);
1151
1152 // Finally, remove the global from the ScalarMap.
1153 SM.erase(GV);
1154 MadeChange = true;
1155 }
1156
1157 DEBUG(if(MadeChange) G.AssertGraphOK());
1158}
1159
Chris Lattnerb12914b2004-09-20 04:48:05 +00001160bool LocalDataStructures::runOnModule(Module &M) {
Chris Lattner15869aa2003-11-02 22:27:28 +00001161 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattneraa0b4682002-11-09 21:12:07 +00001162
Chris Lattnerf4f62272005-03-19 22:23:45 +00001163 // First step, build the globals graph.
1164 GlobalsGraph = new DSGraph(GlobalECs, TD);
Chris Lattnerc420ab62004-02-25 23:31:02 +00001165 {
1166 GraphBuilder GGB(*GlobalsGraph);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001167
Chris Lattnerf4f62272005-03-19 22:23:45 +00001168 // Add initializers for all of the globals to the globals graph.
1169 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1170 I != E; ++I)
Chris Lattnerc420ab62004-02-25 23:31:02 +00001171 if (!I->isExternal())
1172 GGB.mergeInGlobalInitializer(I);
1173 }
1174
Chris Lattnerf4f62272005-03-19 22:23:45 +00001175 // Next step, iterate through the nodes in the globals graph, unioning
1176 // together the globals into equivalence classes.
Chris Lattner9b426bd2005-03-20 03:32:35 +00001177 std::set<GlobalValue*> ECGlobals;
1178 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1179 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1180 ECGlobals.clear();
Chris Lattnerf4f62272005-03-19 22:23:45 +00001181
Chris Lattneraa0b4682002-11-09 21:12:07 +00001182 // Calculate all of the graphs...
1183 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1184 if (!I->isExternal())
Chris Lattnerf4f62272005-03-19 22:23:45 +00001185 DSInfo.insert(std::make_pair(I, new DSGraph(GlobalECs, TD, *I,
1186 GlobalsGraph)));
Chris Lattner26c4fc32003-09-20 21:48:16 +00001187
Chris Lattnerc3f5f772004-02-08 01:51:48 +00001188 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattner26c4fc32003-09-20 21:48:16 +00001189 GlobalsGraph->markIncompleteNodes(DSGraph::MarkFormalArgs);
Chris Lattner9b426bd2005-03-20 03:32:35 +00001190
1191 // Now that we've computed all of the graphs, and merged all of the info into
1192 // the globals graph, see if we have further constrained the globals in the
1193 // program if so, update GlobalECs and remove the extraneous globals from the
1194 // program.
1195 BuildGlobalECs(*GlobalsGraph, ECGlobals);
1196 if (!ECGlobals.empty()) {
1197 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
1198 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1199 E = DSInfo.end(); I != E; ++I)
1200 EliminateUsesOfECGlobals(*I->second, ECGlobals);
1201 }
1202
Chris Lattneraa0b4682002-11-09 21:12:07 +00001203 return false;
1204}
1205
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001206// releaseMemory - If the pass pipeline is done with this pass, we can release
1207// our memory... here...
1208//
1209void LocalDataStructures::releaseMemory() {
Chris Lattner81d924d2003-06-30 04:53:27 +00001210 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
1211 E = DSInfo.end(); I != E; ++I) {
1212 I->second->getReturnNodes().erase(I->first);
1213 if (I->second->getReturnNodes().empty())
1214 delete I->second;
1215 }
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001216
1217 // Empty map so next time memory is released, data structures are not
1218 // re-deleted.
1219 DSInfo.clear();
Chris Lattner2e4f9bf2002-11-09 20:01:01 +00001220 delete GlobalsGraph;
1221 GlobalsGraph = 0;
Chris Lattnerfccd06f2002-10-01 22:33:50 +00001222}
Brian Gaeked0fde302003-11-11 22:41:34 +00001223