1 //===- DataStructure.cpp - Implement the core data structure analysis -----===//
3 // This file implements the core data structure functionality.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Module.h"
8 #include "llvm/DerivedTypes.h"
9 #include "Support/STLExtras.h"
10 #include "Support/StatisticReporter.h"
12 #include "llvm/Analysis/DataStructure.h"
14 AnalysisID LocalDataStructures::ID(AnalysisID::create<LocalDataStructures>());
16 //===----------------------------------------------------------------------===//
17 // DSNode Implementation
18 //===----------------------------------------------------------------------===//
20 DSNode::DSNode(enum NodeTy NT, const Type *T) : Ty(T), NodeType(NT) {
21 // If this node has any fields, allocate them now, but leave them null.
22 switch (T->getPrimitiveID()) {
23 case Type::PointerTyID: Links.resize(1); break;
24 case Type::ArrayTyID: Links.resize(1); break;
25 case Type::StructTyID:
26 Links.resize(cast<StructType>(T)->getNumContainedTypes());
32 // DSNode copy constructor... do not copy over the referrers list!
33 DSNode::DSNode(const DSNode &N)
34 : Ty(N.Ty), Links(N.Links), Globals(N.Globals), NodeType(N.NodeType) {
37 void DSNode::removeReferrer(DSNodeHandle *H) {
38 // Search backwards, because we depopulate the list from the back for
39 // efficiency (because it's a vector).
40 std::vector<DSNodeHandle*>::reverse_iterator I =
41 std::find(Referrers.rbegin(), Referrers.rend(), H);
42 assert(I != Referrers.rend() && "Referrer not pointing to node!");
43 Referrers.erase(I.base()-1);
46 // addGlobal - Add an entry for a global value to the Globals list. This also
47 // marks the node with the 'G' flag if it does not already have it.
49 void DSNode::addGlobal(GlobalValue *GV) {
50 // Keep the list sorted.
51 std::vector<GlobalValue*>::iterator I =
52 std::lower_bound(Globals.begin(), Globals.end(), GV);
54 if (I == Globals.end() || *I != GV) {
55 assert(GV->getType()->getElementType() == Ty);
56 Globals.insert(I, GV);
57 NodeType |= GlobalNode;
62 // addEdgeTo - Add an edge from the current node to the specified node. This
63 // can cause merging of nodes in the graph.
65 void DSNode::addEdgeTo(unsigned LinkNo, DSNode *N) {
66 assert(LinkNo < Links.size() && "LinkNo out of range!");
67 if (N == 0 || Links[LinkNo] == N) return; // Nothing to do
68 if (Links[LinkNo] == 0) { // No merging to perform
73 // Merge the two nodes...
74 Links[LinkNo]->mergeWith(N);
78 // mergeWith - Merge this node into the specified node, moving all links to and
79 // from the argument node into the current node. The specified node may be a
80 // null pointer (in which case, nothing happens).
82 void DSNode::mergeWith(DSNode *N) {
83 if (N == 0 || N == this) return; // Noop
84 assert(N->Ty == Ty && N->Links.size() == Links.size() &&
85 "Cannot merge nodes of two different types!");
87 // Remove all edges pointing at N, causing them to point to 'this' instead.
88 while (!N->Referrers.empty())
89 *N->Referrers.back() = this;
91 // Make all of the outgoing links of N now be outgoing links of this. This
92 // can cause recursive merging!
94 for (unsigned i = 0, e = Links.size(); i != e; ++i) {
95 addEdgeTo(i, N->Links[i]);
96 N->Links[i] = 0; // Reduce unneccesary edges in graph. N is dead
99 // Merge the node types
100 NodeType |= N->NodeType;
101 N->NodeType = 0; // N is now a dead node.
103 // Merge the globals list...
104 if (!N->Globals.empty()) {
105 // Save the current globals off to the side...
106 std::vector<GlobalValue*> OldGlobals(Globals);
108 // Resize the globals vector to be big enough to hold both of them...
109 Globals.resize(Globals.size()+N->Globals.size());
111 // Merge the two sorted globals lists together...
112 std::merge(OldGlobals.begin(), OldGlobals.end(),
113 N->Globals.begin(), N->Globals.end(), Globals.begin());
115 // Erase duplicate entries from the globals list...
116 Globals.erase(std::unique(Globals.begin(), Globals.end()), Globals.end());
118 // Delete the globals from the old node...
123 //===----------------------------------------------------------------------===//
124 // DSGraph Implementation
125 //===----------------------------------------------------------------------===//
127 DSGraph::DSGraph(const DSGraph &G) : Func(G.Func) {
128 std::map<const DSNode*, DSNode*> NodeMap; // ignored
129 RetNode = cloneInto(G, ValueMap, NodeMap, false);
132 DSGraph::~DSGraph() {
133 FunctionCalls.clear();
134 OrigFunctionCalls.clear();
139 // Drop all intra-node references, so that assertions don't fail...
140 std::for_each(Nodes.begin(), Nodes.end(),
141 std::mem_fun(&DSNode::dropAllReferences));
144 // Delete all of the nodes themselves...
145 std::for_each(Nodes.begin(), Nodes.end(), deleter<DSNode>);
148 // dump - Allow inspection of graph in a debugger.
149 void DSGraph::dump() const { print(std::cerr); }
152 // Helper function used to clone a function list.
153 // Each call really shd have an explicit representation as a separate class.
155 CopyFunctionCallsList(const std::vector<std::vector<DSNodeHandle> >& fromCalls,
156 std::vector<std::vector<DSNodeHandle> >& toCalls,
157 std::map<const DSNode*, DSNode*>& NodeMap) {
159 unsigned FC = toCalls.size(); // FirstCall
160 toCalls.reserve(FC+fromCalls.size());
161 for (unsigned i = 0, ei = fromCalls.size(); i != ei; ++i) {
162 toCalls.push_back(std::vector<DSNodeHandle>());
163 toCalls[FC+i].reserve(fromCalls[i].size());
164 for (unsigned j = 0, ej = fromCalls[i].size(); j != ej; ++j)
165 toCalls[FC+i].push_back(NodeMap[fromCalls[i][j]]);
170 // cloneInto - Clone the specified DSGraph into the current graph, returning the
171 // Return node of the graph. The translated ValueMap for the old function is
172 // filled into the OldValMap member. If StripLocals is set to true, Scalar and
173 // Alloca markers are removed from the graph, as the graph is being cloned into
174 // a calling function's graph.
176 DSNode *DSGraph::cloneInto(const DSGraph &G,
177 std::map<Value*, DSNodeHandle> &OldValMap,
178 std::map<const DSNode*, DSNode*>& OldNodeMap,
181 assert(OldNodeMap.size()==0 && "Return argument OldNodeMap should be empty");
183 OldNodeMap[0] = 0; // Null pointer maps to null
185 unsigned FN = Nodes.size(); // FirstNode...
187 // Duplicate all of the nodes, populating the node map...
188 Nodes.reserve(FN+G.Nodes.size());
189 for (unsigned i = 0, e = G.Nodes.size(); i != e; ++i) {
190 DSNode *Old = G.Nodes[i], *New = new DSNode(*Old);
191 Nodes.push_back(New);
192 OldNodeMap[Old] = New;
195 // Rewrite the links in the nodes to point into the current graph now.
196 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
197 for (unsigned j = 0, e = Nodes[i]->getNumLinks(); j != e; ++j)
198 Nodes[i]->setLink(j, OldNodeMap[Nodes[i]->getLink(j)]);
200 // If we are inlining this graph into the called function graph, remove local
203 for (unsigned i = FN, e = Nodes.size(); i != e; ++i)
204 Nodes[i]->NodeType &= ~(DSNode::AllocaNode | DSNode::ScalarNode);
206 // Copy the value map...
207 for (std::map<Value*, DSNodeHandle>::const_iterator I = G.ValueMap.begin(),
208 E = G.ValueMap.end(); I != E; ++I)
209 OldValMap[I->first] = OldNodeMap[I->second];
211 // Copy the current function calls list and the orig function calls list ...
212 CopyFunctionCallsList(G.FunctionCalls, FunctionCalls, OldNodeMap);
213 CopyFunctionCallsList(G.OrigFunctionCalls, OrigFunctionCalls, OldNodeMap);
215 // Copy the list of unresolved callers
216 PendingCallers.insert(PendingCallers.end(),
217 G.PendingCallers.begin(), G.PendingCallers.end());
219 // Return the returned node pointer...
220 return OldNodeMap[G.RetNode];
224 // markIncompleteNodes - Mark the specified node as having contents that are not
225 // known with the current analysis we have performed. Because a node makes all
226 // of the nodes it can reach imcomplete if the node itself is incomplete, we
227 // must recursively traverse the data structure graph, marking all reachable
228 // nodes as incomplete.
230 static void markIncompleteNode(DSNode *N) {
231 // Stop recursion if no node, or if node already marked...
232 if (N == 0 || (N->NodeType & DSNode::Incomplete)) return;
234 // Actually mark the node
235 N->NodeType |= DSNode::Incomplete;
237 // Recusively process children...
238 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
239 markIncompleteNode(N->getLink(i));
243 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
244 // modified by other functions that have not been resolved yet. This marks
245 // nodes that are reachable through three sources of "unknownness":
247 // Global Variables, Function Calls, and Incoming Arguments
249 // For any node that may have unknown components (because something outside the
250 // scope of current analysis may have modified it), the 'Incomplete' flag is
251 // added to the NodeType.
253 void DSGraph::markIncompleteNodes() {
254 // Mark any incoming arguments as incomplete...
255 for (Function::aiterator I = Func.abegin(), E = Func.aend(); I != E; ++I)
256 if (isa<PointerType>(I->getType()))
257 markIncompleteNode(ValueMap[I]->getLink(0));
259 // Mark stuff passed into functions calls as being incomplete...
260 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i) {
261 std::vector<DSNodeHandle> &Args = FunctionCalls[i];
262 if (Args[0]) // If the call returns a pointer...
263 // Then the return value is certainly incomplete!
264 markIncompleteNode(Args[0]);
266 // The call does not make the function argument incomplete...
268 // All arguments to the function call are incomplete though!
269 for (unsigned i = 2, e = Args.size(); i != e; ++i)
270 markIncompleteNode(Args[i]);
273 // Mark all of the nodes pointed to by global or cast nodes as incomplete...
274 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
275 if (Nodes[i]->NodeType & (DSNode::GlobalNode | DSNode::CastNode)) {
276 DSNode *N = Nodes[i];
277 for (unsigned i = 0, e = N->getNumLinks(); i != e; ++i)
278 markIncompleteNode(N->getLink(i));
282 // isNodeDead - This method checks to see if a node is dead, and if it isn't, it
283 // checks to see if there are simple transformations that it can do to make it
286 bool DSGraph::isNodeDead(DSNode *N) {
287 // Is it a trivially dead shadow node...
288 if (N->getReferrers().empty() && N->NodeType == 0)
291 // Is it a function node or some other trivially unused global?
292 if ((N->NodeType & ~DSNode::GlobalNode) == 0 &&
293 N->getNumLinks() == 0 &&
294 N->getReferrers().size() == N->getGlobals().size()) {
296 // Remove the globals from the valuemap, so that the referrer count will go
298 while (!N->getGlobals().empty()) {
299 GlobalValue *GV = N->getGlobals().back();
300 N->getGlobals().pop_back();
303 assert(N->getReferrers().empty() && "Referrers should all be gone now!");
311 // removeDeadNodes - After the graph has been constructed, this method removes
312 // all unreachable nodes that are created because they got merged with other
313 // nodes in the graph. These nodes will all be trivially unreachable, so we
314 // don't have to perform any non-trivial analysis here.
316 void DSGraph::removeDeadNodes() {
317 for (unsigned i = 0; i != Nodes.size(); ++i)
318 if (isNodeDead(Nodes[i])) { // This node is dead!
319 delete Nodes[i]; // Free memory...
320 Nodes.erase(Nodes.begin()+i--); // Remove from node list...
323 // Remove identical function calls
324 unsigned NumFns = FunctionCalls.size();
325 std::sort(FunctionCalls.begin(), FunctionCalls.end());
326 FunctionCalls.erase(std::unique(FunctionCalls.begin(), FunctionCalls.end()),
327 FunctionCalls.end());
329 DEBUG(if (NumFns != FunctionCalls.size())
330 std::cerr << "Merged " << (NumFns-FunctionCalls.size())
331 << " call nodes in " << Func.getName() << "\n";);
335 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
336 // is useful for clearing out markers like Scalar or Incomplete.
338 void DSGraph::maskNodeTypes(unsigned char Mask) {
339 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
340 Nodes[i]->NodeType &= Mask;
344 //===----------------------------------------------------------------------===//
345 // LocalDataStructures Implementation
346 //===----------------------------------------------------------------------===//
348 // releaseMemory - If the pass pipeline is done with this pass, we can release
349 // our memory... here...
351 void LocalDataStructures::releaseMemory() {
352 for (std::map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
353 E = DSInfo.end(); I != E; ++I)
356 // Empty map so next time memory is released, data structures are not
361 bool LocalDataStructures::run(Module &M) {
362 // Calculate all of the graphs...
363 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
364 if (!I->isExternal())
365 DSInfo.insert(std::make_pair(&*I, new DSGraph(*I)));