blob: 0f45a989c0cb30cd9ff4f6635028e780be23dbf5 [file] [log] [blame]
Chris Lattner55c10582002-10-03 20:38:41 +00001//===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner0d9bab82002-07-18 00:12:30 +00009//
10// This file implements the BUDataStructures class, which represents the
11// Bottom-Up Interprocedural closure of the data structure graph over the
12// program. This is useful for applications like pool allocation, but **not**
Chris Lattner55c10582002-10-03 20:38:41 +000013// applications like alias analysis.
Chris Lattner0d9bab82002-07-18 00:12:30 +000014//
15//===----------------------------------------------------------------------===//
16
Chris Lattner8adbec82004-07-07 06:35:22 +000017#include "llvm/Analysis/DataStructure/DataStructure.h"
Chris Lattner6b9eb352005-03-20 02:42:07 +000018#include "llvm/Analysis/DataStructure/DSGraph.h"
Chris Lattner0d9bab82002-07-18 00:12:30 +000019#include "llvm/Module.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/ADT/Statistic.h"
21#include "llvm/Support/Debug.h"
Chris Lattner9a927292003-11-12 23:11:14 +000022using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000023
Chris Lattnerae5f6032002-11-17 22:16:28 +000024namespace {
25 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
Chris Lattnerd391d702003-07-02 20:24:42 +000026 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
Chris Lattner6c874612003-07-02 23:42:48 +000027 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
Chris Lattnerae5f6032002-11-17 22:16:28 +000028
29 RegisterAnalysis<BUDataStructures>
Chris Lattner312edd32003-06-28 22:14:55 +000030 X("budatastructure", "Bottom-up Data Structure Analysis");
Chris Lattnerae5f6032002-11-17 22:16:28 +000031}
Chris Lattner0d9bab82002-07-18 00:12:30 +000032
Chris Lattner33b42762005-03-25 16:45:43 +000033/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
34/// contains multiple globals, DSA will never, ever, be able to tell the globals
35/// apart. Instead of maintaining this information in all of the graphs
36/// throughout the entire program, store only a single global (the "leader") in
37/// the graphs, and build equivalence classes for the rest of the globals.
38static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
39 DSScalarMap &SM = GG.getScalarMap();
40 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
41 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
42 I != E; ++I) {
43 if (I->getGlobalsList().size() <= 1) continue;
44
45 // First, build up the equivalence set for this block of globals.
46 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
47 GlobalValue *First = GVs[0];
48 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
49 GlobalECs.unionSets(First, GVs[i]);
50
51 // Next, get the leader element.
52 assert(First == GlobalECs.getLeaderValue(First) &&
53 "First did not end up being the leader?");
54
55 // Next, remove all globals from the scalar map that are not the leader.
56 assert(GVs[0] == First && "First had to be at the front!");
57 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
58 ECGlobals.insert(GVs[i]);
59 SM.erase(SM.find(GVs[i]));
60 }
61
62 // Finally, change the global node to only contain the leader.
63 I->clearGlobals();
64 I->addGlobal(First);
65 }
66
67 DEBUG(GG.AssertGraphOK());
68}
69
70/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
71/// really just equivalent to some other globals, remove the globals from the
72/// specified DSGraph (if present), and merge any nodes with their leader nodes.
73static void EliminateUsesOfECGlobals(DSGraph &G,
74 const std::set<GlobalValue*> &ECGlobals) {
75 DSScalarMap &SM = G.getScalarMap();
76 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
77
78 bool MadeChange = false;
79 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
80 GI != E; ) {
81 GlobalValue *GV = *GI++;
82 if (!ECGlobals.count(GV)) continue;
83
84 const DSNodeHandle &GVNH = SM[GV];
85 assert(!GVNH.isNull() && "Global has null NH!?");
86
87 // Okay, this global is in some equivalence class. Start by finding the
88 // leader of the class.
89 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
90
91 // If the leader isn't already in the graph, insert it into the node
92 // corresponding to GV.
93 if (!SM.global_count(Leader)) {
94 GVNH.getNode()->addGlobal(Leader);
95 SM[Leader] = GVNH;
96 } else {
97 // Otherwise, the leader is in the graph, make sure the nodes are the
98 // merged in the specified graph.
99 const DSNodeHandle &LNH = SM[Leader];
100 if (LNH.getNode() != GVNH.getNode())
101 LNH.mergeWith(GVNH);
102 }
103
104 // Next step, remove the global from the DSNode.
105 GVNH.getNode()->removeGlobal(GV);
106
107 // Finally, remove the global from the ScalarMap.
108 SM.erase(GV);
109 MadeChange = true;
110 }
111
112 DEBUG(if(MadeChange) G.AssertGraphOK());
113}
114
Chris Lattneraa0b4682002-11-09 21:12:07 +0000115// run - Calculate the bottom up data structure graphs for each function in the
116// program.
117//
Chris Lattnerb12914b2004-09-20 04:48:05 +0000118bool BUDataStructures::runOnModule(Module &M) {
Chris Lattner312edd32003-06-28 22:14:55 +0000119 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
Chris Lattnerf4f62272005-03-19 22:23:45 +0000120 GlobalECs = LocalDSA.getGlobalECs();
121
122 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
Chris Lattner20167e32003-02-03 19:11:38 +0000123 GlobalsGraph->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000124
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000125 IndCallGraphMap = new std::map<std::vector<Function*>,
126 std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
127
Chris Lattnerf189bce2005-02-01 17:35:52 +0000128 std::vector<Function*> Stack;
129 hash_map<Function*, unsigned> ValMap;
130 unsigned NextID = 1;
131
Chris Lattnera9c9c022002-11-11 21:35:13 +0000132 Function *MainFunc = M.getMainFunction();
133 if (MainFunc)
Chris Lattnerf189bce2005-02-01 17:35:52 +0000134 calculateGraphs(MainFunc, Stack, NextID, ValMap);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000135
136 // Calculate the graphs for any functions that are unreachable from main...
Chris Lattneraa0b4682002-11-09 21:12:07 +0000137 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner5d5b6d62003-07-01 16:04:18 +0000138 if (!I->isExternal() && !DSInfo.count(I)) {
Chris Lattnerae5f6032002-11-17 22:16:28 +0000139#ifndef NDEBUG
Chris Lattnera9c9c022002-11-11 21:35:13 +0000140 if (MainFunc)
141 std::cerr << "*** Function unreachable from main: "
142 << I->getName() << "\n";
Chris Lattnerae5f6032002-11-17 22:16:28 +0000143#endif
Chris Lattnerf189bce2005-02-01 17:35:52 +0000144 calculateGraphs(I, Stack, NextID, ValMap); // Calculate all graphs.
Chris Lattnera9c9c022002-11-11 21:35:13 +0000145 }
Chris Lattner6c874612003-07-02 23:42:48 +0000146
147 NumCallEdges += ActualCallees.size();
Chris Lattnerec157b72003-09-20 23:27:05 +0000148
Chris Lattner86db3642005-02-04 19:59:49 +0000149 // If we computed any temporary indcallgraphs, free them now.
150 for (std::map<std::vector<Function*>,
151 std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000152 IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
Chris Lattner86db3642005-02-04 19:59:49 +0000153 I->second.second.clear(); // Drop arg refs into the graph.
154 delete I->second.first;
155 }
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000156 delete IndCallGraphMap;
Chris Lattner86db3642005-02-04 19:59:49 +0000157
Chris Lattnerec157b72003-09-20 23:27:05 +0000158 // At the end of the bottom-up pass, the globals graph becomes complete.
159 // FIXME: This is not the right way to do this, but it is sorta better than
Chris Lattner11fc9302003-09-20 23:58:33 +0000160 // nothing! In particular, externally visible globals and unresolvable call
161 // nodes at the end of the BU phase should make things that they point to
162 // incomplete in the globals graph.
163 //
Chris Lattnerc3f5f772004-02-08 01:51:48 +0000164 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattnerec157b72003-09-20 23:27:05 +0000165 GlobalsGraph->maskIncompleteMarkers();
Chris Lattnera66e3532005-03-13 20:15:06 +0000166
Chris Lattner9547ade2005-03-22 22:10:22 +0000167 // Mark external globals incomplete.
168 GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
169
Chris Lattner33b42762005-03-25 16:45:43 +0000170 // Grow the equivalence classes for the globals to include anything that we
171 // now know to be aliased.
172 std::set<GlobalValue*> ECGlobals;
173 BuildGlobalECs(*GlobalsGraph, ECGlobals);
174 if (!ECGlobals.empty()) {
175 DEBUG(std::cerr << "Eliminating " << ECGlobals.size() << " EC Globals!\n");
176 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
177 E = DSInfo.end(); I != E; ++I)
178 EliminateUsesOfECGlobals(*I->second, ECGlobals);
179 }
180
Chris Lattnera66e3532005-03-13 20:15:06 +0000181 // Merge the globals variables (not the calls) from the globals graph back
182 // into the main function's graph so that the main function contains all of
183 // the information about global pools and GV usage in the program.
Chris Lattner49e88e82005-03-15 22:10:04 +0000184 if (MainFunc && !MainFunc->isExternal()) {
Chris Lattnera66e3532005-03-13 20:15:06 +0000185 DSGraph &MainGraph = getOrCreateGraph(MainFunc);
186 const DSGraph &GG = *MainGraph.getGlobalsGraph();
187 ReachabilityCloner RC(MainGraph, GG,
188 DSGraph::DontCloneCallNodes |
189 DSGraph::DontCloneAuxCallNodes);
190
191 // Clone the global nodes into this graph.
192 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
193 E = GG.getScalarMap().global_end(); I != E; ++I)
194 if (isa<GlobalVariable>(*I))
195 RC.getClonedNH(GG.getNodeForValue(*I));
196
Chris Lattner270cf502005-03-13 20:32:26 +0000197 MainGraph.maskIncompleteMarkers();
Chris Lattnera66e3532005-03-13 20:15:06 +0000198 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
199 DSGraph::IgnoreGlobals);
200 }
201
Chris Lattneraa0b4682002-11-09 21:12:07 +0000202 return false;
203}
Chris Lattner55c10582002-10-03 20:38:41 +0000204
Chris Lattnera9c9c022002-11-11 21:35:13 +0000205DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
206 // Has the graph already been created?
207 DSGraph *&Graph = DSInfo[F];
208 if (Graph) return *Graph;
209
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000210 DSGraph &LocGraph = getAnalysis<LocalDataStructures>().getDSGraph(*F);
211
212 // Steal the local graph.
213 Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
214 Graph->spliceFrom(LocGraph);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000215
216 Graph->setGlobalsGraph(GlobalsGraph);
217 Graph->setPrintAuxCalls();
218
219 // Start with a copy of the original call sites...
220 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
221 return *Graph;
222}
223
Chris Lattner6b9eb352005-03-20 02:42:07 +0000224static bool isVAHackFn(const Function *F) {
225 return F->getName() == "printf" || F->getName() == "sscanf" ||
226 F->getName() == "fprintf" || F->getName() == "open" ||
227 F->getName() == "sprintf" || F->getName() == "fputs" ||
228 F->getName() == "fscanf";
229}
230
231static bool isResolvableFunc(const Function* callee) {
232 return !callee->isExternal() || isVAHackFn(callee);
233}
234
235static void GetAllCallees(const DSCallSite &CS,
236 std::vector<Function*> &Callees) {
237 if (CS.isDirectCall()) {
238 if (isResolvableFunc(CS.getCalleeFunc()))
239 Callees.push_back(CS.getCalleeFunc());
240 } else if (!CS.getCalleeNode()->isIncomplete()) {
241 // Get all callees.
242 unsigned OldSize = Callees.size();
243 CS.getCalleeNode()->addFullFunctionList(Callees);
244
245 // If any of the callees are unresolvable, remove the whole batch!
246 for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
247 if (!isResolvableFunc(Callees[i])) {
248 Callees.erase(Callees.begin()+OldSize, Callees.end());
249 return;
250 }
251 }
252}
253
254
255/// GetAllAuxCallees - Return a list containing all of the resolvable callees in
256/// the aux list for the specified graph in the Callees vector.
257static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
258 Callees.clear();
259 for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
260 GetAllCallees(*I, Callees);
261}
262
Chris Lattnera9c9c022002-11-11 21:35:13 +0000263unsigned BUDataStructures::calculateGraphs(Function *F,
264 std::vector<Function*> &Stack,
265 unsigned &NextID,
Chris Lattner41c04f72003-02-01 04:52:08 +0000266 hash_map<Function*, unsigned> &ValMap) {
Chris Lattner6acfe922003-11-13 05:04:19 +0000267 assert(!ValMap.count(F) && "Shouldn't revisit functions!");
Chris Lattnera9c9c022002-11-11 21:35:13 +0000268 unsigned Min = NextID++, MyID = Min;
269 ValMap[F] = Min;
270 Stack.push_back(F);
271
Chris Lattner16437ff2004-03-04 17:05:28 +0000272 // FIXME! This test should be generalized to be any function that we have
273 // already processed, in the case when there isn't a main or there are
274 // unreachable functions!
Chris Lattnera9c9c022002-11-11 21:35:13 +0000275 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
276 // No callees!
277 Stack.pop_back();
278 ValMap[F] = ~0;
279 return Min;
280 }
281
282 DSGraph &Graph = getOrCreateGraph(F);
283
Chris Lattner6b9eb352005-03-20 02:42:07 +0000284 // Find all callee functions.
285 std::vector<Function*> CalleeFunctions;
286 GetAllAuxCallees(Graph, CalleeFunctions);
287
Chris Lattnera9c9c022002-11-11 21:35:13 +0000288 // The edges out of the current node are the call site targets...
Chris Lattner6b9eb352005-03-20 02:42:07 +0000289 for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
290 Function *Callee = CalleeFunctions[i];
Chris Lattnera9c9c022002-11-11 21:35:13 +0000291 unsigned M;
292 // Have we visited the destination function yet?
Chris Lattner41c04f72003-02-01 04:52:08 +0000293 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000294 if (It == ValMap.end()) // No, visit it now.
295 M = calculateGraphs(Callee, Stack, NextID, ValMap);
296 else // Yes, get it's number.
297 M = It->second;
298 if (M < Min) Min = M;
299 }
300
301 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
302 if (Min != MyID)
303 return Min; // This is part of a larger SCC!
304
305 // If this is a new SCC, process it now.
306 if (Stack.back() == F) { // Special case the single "SCC" case here.
307 DEBUG(std::cerr << "Visiting single node SCC #: " << MyID << " fn: "
308 << F->getName() << "\n");
309 Stack.pop_back();
Chris Lattner0eea6182003-06-30 05:09:58 +0000310 DSGraph &G = getDSGraph(*F);
311 DEBUG(std::cerr << " [BU] Calculating graph for: " << F->getName()<< "\n");
312 calculateGraph(G);
313 DEBUG(std::cerr << " [BU] Done inlining: " << F->getName() << " ["
314 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
315 << "]\n");
Chris Lattnera9c9c022002-11-11 21:35:13 +0000316
Chris Lattnerae5f6032002-11-17 22:16:28 +0000317 if (MaxSCC < 1) MaxSCC = 1;
318
Chris Lattner6b9eb352005-03-20 02:42:07 +0000319 // Should we revisit the graph? Only do it if there are now new resolvable
320 // callees.
321 GetAllAuxCallees(Graph, CalleeFunctions);
322 if (!CalleeFunctions.empty()) {
Chris Lattnera9c9c022002-11-11 21:35:13 +0000323 ValMap.erase(F);
324 return calculateGraphs(F, Stack, NextID, ValMap);
325 } else {
326 ValMap[F] = ~0U;
327 }
328 return MyID;
329
330 } else {
331 // SCCFunctions - Keep track of the functions in the current SCC
332 //
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000333 std::vector<DSGraph*> SCCGraphs;
Chris Lattnera9c9c022002-11-11 21:35:13 +0000334
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000335 unsigned SCCSize = 1;
336 Function *NF = Stack.back();
337 ValMap[NF] = ~0U;
338 DSGraph &SCCGraph = getDSGraph(*NF);
Chris Lattner0eea6182003-06-30 05:09:58 +0000339
Chris Lattner0eea6182003-06-30 05:09:58 +0000340 // First thing first, collapse all of the DSGraphs into a single graph for
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000341 // the entire SCC. Splice all of the graphs into one and discard all of the
342 // old graphs.
Chris Lattner0eea6182003-06-30 05:09:58 +0000343 //
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000344 while (NF != F) {
345 Stack.pop_back();
346 NF = Stack.back();
347 ValMap[NF] = ~0U;
Chris Lattnera2197132005-03-22 00:36:51 +0000348
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000349 DSGraph &NFG = getDSGraph(*NF);
350
351 // Update the Function -> DSG map.
352 for (DSGraph::retnodes_iterator I = NFG.retnodes_begin(),
353 E = NFG.retnodes_end(); I != E; ++I)
354 DSInfo[I->first] = &SCCGraph;
355
356 SCCGraph.spliceFrom(NFG);
357 delete &NFG;
358
359 ++SCCSize;
Chris Lattner0eea6182003-06-30 05:09:58 +0000360 }
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000361 Stack.pop_back();
Chris Lattner20da24c2005-03-25 00:06:09 +0000362
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000363 std::cerr << "Calculating graph for SCC #: " << MyID << " of size: "
364 << SCCSize << "\n";
365
366 // Compute the Max SCC Size.
367 if (MaxSCC < SCCSize)
368 MaxSCC = SCCSize;
Chris Lattnera9c9c022002-11-11 21:35:13 +0000369
Chris Lattner744f9392003-07-02 04:37:48 +0000370 // Clean up the graph before we start inlining a bunch again...
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000371 SCCGraph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattner744f9392003-07-02 04:37:48 +0000372
Chris Lattner0eea6182003-06-30 05:09:58 +0000373 // Now that we have one big happy family, resolve all of the call sites in
374 // the graph...
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000375 calculateGraph(SCCGraph);
376 DEBUG(std::cerr << " [BU] Done inlining SCC [" << SCCGraph.getGraphSize()
377 << "+" << SCCGraph.getAuxFunctionCalls().size() << "]\n");
Chris Lattnera9c9c022002-11-11 21:35:13 +0000378
379 std::cerr << "DONE with SCC #: " << MyID << "\n";
380
381 // We never have to revisit "SCC" processed functions...
Chris Lattnera9c9c022002-11-11 21:35:13 +0000382 return MyID;
383 }
384
385 return MyID; // == Min
386}
387
388
Chris Lattner0d9bab82002-07-18 00:12:30 +0000389// releaseMemory - If the pass pipeline is done with this pass, we can release
390// our memory... here...
391//
Chris Lattner65512d22005-03-23 21:59:34 +0000392void BUDataStructures::releaseMyMemory() {
Chris Lattner0eea6182003-06-30 05:09:58 +0000393 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
394 E = DSInfo.end(); I != E; ++I) {
395 I->second->getReturnNodes().erase(I->first);
396 if (I->second->getReturnNodes().empty())
397 delete I->second;
398 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000399
400 // Empty map so next time memory is released, data structures are not
401 // re-deleted.
402 DSInfo.clear();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000403 delete GlobalsGraph;
404 GlobalsGraph = 0;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000405}
406
Chris Lattner0eea6182003-06-30 05:09:58 +0000407void BUDataStructures::calculateGraph(DSGraph &Graph) {
Chris Lattnera9c9c022002-11-11 21:35:13 +0000408 // Move our call site list into TempFCs so that inline call sites go into the
409 // new call site list and doesn't invalidate our iterators!
Chris Lattnera9548d92005-01-30 23:51:02 +0000410 std::list<DSCallSite> TempFCs;
411 std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
Chris Lattnera9c9c022002-11-11 21:35:13 +0000412 TempFCs.swap(AuxCallsList);
Chris Lattner8a5db462002-11-11 00:01:34 +0000413
Chris Lattner0eea6182003-06-30 05:09:58 +0000414 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
415
Chris Lattnerf189bce2005-02-01 17:35:52 +0000416 bool Printed = false;
Chris Lattner86db3642005-02-04 19:59:49 +0000417 std::vector<Function*> CalledFuncs;
Chris Lattneraf8650e2005-02-01 21:37:27 +0000418 while (!TempFCs.empty()) {
419 DSCallSite &CS = *TempFCs.begin();
Chris Lattnerf189bce2005-02-01 17:35:52 +0000420
Chris Lattner86db3642005-02-04 19:59:49 +0000421 CalledFuncs.clear();
Chris Lattnera9548d92005-01-30 23:51:02 +0000422
Chris Lattner5021b8c2005-03-18 23:19:47 +0000423 // Fast path for noop calls. Note that we don't care about merging globals
424 // in the callee with nodes in the caller here.
425 if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0) {
426 TempFCs.erase(TempFCs.begin());
427 continue;
Chris Lattner6b9eb352005-03-20 02:42:07 +0000428 } else if (CS.isDirectCall() && isVAHackFn(CS.getCalleeFunc())) {
429 TempFCs.erase(TempFCs.begin());
430 continue;
Chris Lattner5021b8c2005-03-18 23:19:47 +0000431 }
432
Chris Lattner6b9eb352005-03-20 02:42:07 +0000433 GetAllCallees(CS, CalledFuncs);
Chris Lattner0321b682004-02-27 20:05:15 +0000434
Chris Lattneraf8650e2005-02-01 21:37:27 +0000435 if (CalledFuncs.empty()) {
436 // Remember that we could not resolve this yet!
437 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
Chris Lattner20cd1362005-02-01 21:49:43 +0000438 continue;
Chris Lattneraf8650e2005-02-01 21:37:27 +0000439 } else {
Chris Lattner86db3642005-02-04 19:59:49 +0000440 DSGraph *GI;
Chris Lattnereb144f52005-03-21 20:20:49 +0000441 Instruction *TheCall = CS.getCallSite().getInstruction();
Chris Lattnera9548d92005-01-30 23:51:02 +0000442
Chris Lattner86db3642005-02-04 19:59:49 +0000443 if (CalledFuncs.size() == 1) {
444 Function *Callee = CalledFuncs[0];
Chris Lattnereb144f52005-03-21 20:20:49 +0000445 ActualCallees.insert(std::make_pair(TheCall, Callee));
Chris Lattner86db3642005-02-04 19:59:49 +0000446
Chris Lattner20cd1362005-02-01 21:49:43 +0000447 // Get the data structure graph for the called function.
Chris Lattner86db3642005-02-04 19:59:49 +0000448 GI = &getDSGraph(*Callee); // Graph to inline
449 DEBUG(std::cerr << " Inlining graph for " << Callee->getName());
450
451 DEBUG(std::cerr << "[" << GI->getGraphSize() << "+"
452 << GI->getAuxFunctionCalls().size() << "] into '"
Chris Lattner20cd1362005-02-01 21:49:43 +0000453 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
454 << Graph.getAuxFunctionCalls().size() << "]\n");
Chris Lattner86db3642005-02-04 19:59:49 +0000455 Graph.mergeInGraph(CS, *Callee, *GI,
Chris Lattner20cd1362005-02-01 21:49:43 +0000456 DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
457 ++NumBUInlines;
Chris Lattner86db3642005-02-04 19:59:49 +0000458 } else {
459 if (!Printed)
460 std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
461 std::cerr << " calls " << CalledFuncs.size()
462 << " fns from site: " << CS.getCallSite().getInstruction()
463 << " " << *CS.getCallSite().getInstruction();
Chris Lattner86db3642005-02-04 19:59:49 +0000464 std::cerr << " Fns =";
Chris Lattnereb144f52005-03-21 20:20:49 +0000465 unsigned NumPrinted = 0;
466
Chris Lattner86db3642005-02-04 19:59:49 +0000467 for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
Chris Lattnereb144f52005-03-21 20:20:49 +0000468 E = CalledFuncs.end(); I != E; ++I) {
469 if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName();
470
471 // Add the call edges to the call graph.
472 ActualCallees.insert(std::make_pair(TheCall, *I));
473 }
Chris Lattner86db3642005-02-04 19:59:49 +0000474 std::cerr << "\n";
475
476 // See if we already computed a graph for this set of callees.
477 std::sort(CalledFuncs.begin(), CalledFuncs.end());
478 std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000479 (*IndCallGraphMap)[CalledFuncs];
Chris Lattner86db3642005-02-04 19:59:49 +0000480
481 if (IndCallGraph.first == 0) {
482 std::vector<Function*>::iterator I = CalledFuncs.begin(),
483 E = CalledFuncs.end();
484
485 // Start with a copy of the first graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000486 GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
Chris Lattner86db3642005-02-04 19:59:49 +0000487 GI->setGlobalsGraph(Graph.getGlobalsGraph());
488 std::vector<DSNodeHandle> &Args = IndCallGraph.second;
489
490 // Get the argument nodes for the first callee. The return value is
491 // the 0th index in the vector.
492 GI->getFunctionArgumentsForCall(*I, Args);
493
494 // Merge all of the other callees into this graph.
495 for (++I; I != E; ++I) {
496 // If the graph already contains the nodes for the function, don't
497 // bother merging it in again.
498 if (!GI->containsFunction(*I)) {
Chris Lattnera2197132005-03-22 00:36:51 +0000499 GI->cloneInto(getDSGraph(**I));
Chris Lattner86db3642005-02-04 19:59:49 +0000500 ++NumBUInlines;
501 }
502
503 std::vector<DSNodeHandle> NextArgs;
504 GI->getFunctionArgumentsForCall(*I, NextArgs);
505 unsigned i = 0, e = Args.size();
506 for (; i != e; ++i) {
507 if (i == NextArgs.size()) break;
508 Args[i].mergeWith(NextArgs[i]);
509 }
510 for (e = NextArgs.size(); i != e; ++i)
511 Args.push_back(NextArgs[i]);
512 }
513
514 // Clean up the final graph!
515 GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
516 } else {
517 std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n";
518 }
519
520 GI = IndCallGraph.first;
521
522 // Merge the unified graph into this graph now.
523 DEBUG(std::cerr << " Inlining multi callee graph "
524 << "[" << GI->getGraphSize() << "+"
525 << GI->getAuxFunctionCalls().size() << "] into '"
526 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
527 << Graph.getAuxFunctionCalls().size() << "]\n");
528
529 Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
Chris Lattner86db3642005-02-04 19:59:49 +0000530 DSGraph::StripAllocaBit |
531 DSGraph::DontCloneCallNodes);
532 ++NumBUInlines;
Chris Lattneraf8650e2005-02-01 21:37:27 +0000533 }
Chris Lattnera9548d92005-01-30 23:51:02 +0000534 }
Chris Lattner20cd1362005-02-01 21:49:43 +0000535 TempFCs.erase(TempFCs.begin());
Chris Lattnera9548d92005-01-30 23:51:02 +0000536 }
Chris Lattnera9c9c022002-11-11 21:35:13 +0000537
Vikram S. Adve1da1d322003-07-16 21:42:03 +0000538 // Recompute the Incomplete markers
Chris Lattnera9c9c022002-11-11 21:35:13 +0000539 Graph.maskIncompleteMarkers();
Chris Lattner394471f2003-01-23 22:05:33 +0000540 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
Vikram S. Adve1da1d322003-07-16 21:42:03 +0000541
542 // Delete dead nodes. Treat globals that are unreachable but that can
543 // reach live nodes as live.
Chris Lattner394471f2003-01-23 22:05:33 +0000544 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000545
Chris Lattner35679372004-02-21 00:30:28 +0000546 // When this graph is finalized, clone the globals in the graph into the
547 // globals graph to make sure it has everything, from all graphs.
548 DSScalarMap &MainSM = Graph.getScalarMap();
549 ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
550
Chris Lattner3b7b81b2004-10-31 21:54:51 +0000551 // Clone everything reachable from globals in the function graph into the
Chris Lattner35679372004-02-21 00:30:28 +0000552 // globals graph.
553 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
554 E = MainSM.global_end(); I != E; ++I)
555 RC.getClonedNH(MainSM[*I]);
556
Chris Lattnera9c9c022002-11-11 21:35:13 +0000557 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
Chris Lattnera9c9c022002-11-11 21:35:13 +0000558}
Chris Lattner851b5342005-01-24 20:00:14 +0000559
560static const Function *getFnForValue(const Value *V) {
561 if (const Instruction *I = dyn_cast<Instruction>(V))
562 return I->getParent()->getParent();
563 else if (const Argument *A = dyn_cast<Argument>(V))
564 return A->getParent();
565 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
566 return BB->getParent();
567 return 0;
568}
569
570/// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
571/// These correspond to the interfaces defined in the AliasAnalysis class.
572void BUDataStructures::deleteValue(Value *V) {
573 if (const Function *F = getFnForValue(V)) { // Function local value?
574 // If this is a function local value, just delete it from the scalar map!
575 getDSGraph(*F).getScalarMap().eraseIfExists(V);
576 return;
577 }
578
Chris Lattnercff8ac22005-01-31 00:10:45 +0000579 if (Function *F = dyn_cast<Function>(V)) {
Chris Lattner851b5342005-01-24 20:00:14 +0000580 assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
581 "cannot handle scc's");
582 delete DSInfo[F];
583 DSInfo.erase(F);
584 return;
585 }
586
587 assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
588}
589
590void BUDataStructures::copyValue(Value *From, Value *To) {
591 if (From == To) return;
592 if (const Function *F = getFnForValue(From)) { // Function local value?
593 // If this is a function local value, just delete it from the scalar map!
594 getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
595 return;
596 }
597
598 if (Function *FromF = dyn_cast<Function>(From)) {
599 Function *ToF = cast<Function>(To);
600 assert(!DSInfo.count(ToF) && "New Function already exists!");
Chris Lattnerf4f62272005-03-19 22:23:45 +0000601 DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
Chris Lattner851b5342005-01-24 20:00:14 +0000602 DSInfo[ToF] = NG;
603 assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
604
605 // Change the Function* is the returnnodes map to the ToF.
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000606 DSNodeHandle Ret = NG->retnodes_begin()->second;
Chris Lattner851b5342005-01-24 20:00:14 +0000607 NG->getReturnNodes().clear();
608 NG->getReturnNodes()[ToF] = Ret;
609 return;
610 }
611
Chris Lattnerc5132e62005-03-24 04:22:04 +0000612 if (const Function *F = getFnForValue(To)) {
613 DSGraph &G = getDSGraph(*F);
614 G.getScalarMap().copyScalarIfExists(From, To);
615 return;
616 }
617
618 std::cerr << *From;
619 std::cerr << *To;
620 assert(0 && "Do not know how to copy this yet!");
621 abort();
Chris Lattner851b5342005-01-24 20:00:14 +0000622}