blob: 0f48850ae9eae3a89d757fbcb46c4ec42cf84d68 [file] [log] [blame]
Chris Lattner55c10582002-10-03 20:38:41 +00001//===- BottomUpClosure.cpp - Compute bottom-up interprocedural closure ----===//
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 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//===----------------------------------------------------------------------===//
Andrew Lenharthab390d02006-06-19 18:23:36 +000016#define DEBUG_TYPE "bu_dsa"
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"
Andrew Lenharthab390d02006-06-19 18:23:36 +000020#include "llvm/DerivedTypes.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/ADT/Statistic.h"
Andrew Lenharthab390d02006-06-19 18:23:36 +000022#include "llvm/Support/CommandLine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Chris Lattnera5ed1bd2005-04-21 16:09:43 +000024#include "llvm/Support/Timer.h"
Chris Lattner72382102006-01-22 23:19:18 +000025#include <iostream>
Chris Lattner9a927292003-11-12 23:11:14 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chris Lattnerae5f6032002-11-17 22:16:28 +000028namespace {
29 Statistic<> MaxSCC("budatastructure", "Maximum SCC Size in Call Graph");
Chris Lattnerd391d702003-07-02 20:24:42 +000030 Statistic<> NumBUInlines("budatastructures", "Number of graphs inlined");
Chris Lattner6c874612003-07-02 23:42:48 +000031 Statistic<> NumCallEdges("budatastructures", "Number of 'actual' call edges");
Misha Brukman2b37d7c2005-04-21 21:13:18 +000032
Andrew Lenharthab390d02006-06-19 18:23:36 +000033 cl::opt<bool>
Andrew Lenharth12711df2006-10-23 19:55:24 +000034 AddGlobals("budatastructures-annotate-calls", cl::Hidden,
Andrew Lenharthab390d02006-06-19 18:23:36 +000035 cl::desc("Annotate call sites with functions as they are resolved"));
36 cl::opt<bool>
Andrew Lenharth12711df2006-10-23 19:55:24 +000037 UpdateGlobals("budatastructures-update-from-globals", cl::Hidden,
Andrew Lenharthab390d02006-06-19 18:23:36 +000038 cl::desc("Update local graph from global graph when processing function"));
39
Chris Lattner5d8925c2006-08-27 22:30:17 +000040 RegisterPass<BUDataStructures>
Chris Lattner312edd32003-06-28 22:14:55 +000041 X("budatastructure", "Bottom-up Data Structure Analysis");
Chris Lattnerae5f6032002-11-17 22:16:28 +000042}
Chris Lattner0d9bab82002-07-18 00:12:30 +000043
Andrew Lenharth72be6e62006-10-23 19:53:37 +000044static bool GetAllCalleesN(const DSCallSite &CS,
Andrew Lenharthab390d02006-06-19 18:23:36 +000045 std::vector<Function*> &Callees);
46
Chris Lattner33b42762005-03-25 16:45:43 +000047/// BuildGlobalECs - Look at all of the nodes in the globals graph. If any node
48/// contains multiple globals, DSA will never, ever, be able to tell the globals
49/// apart. Instead of maintaining this information in all of the graphs
50/// throughout the entire program, store only a single global (the "leader") in
51/// the graphs, and build equivalence classes for the rest of the globals.
52static void BuildGlobalECs(DSGraph &GG, std::set<GlobalValue*> &ECGlobals) {
53 DSScalarMap &SM = GG.getScalarMap();
54 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
55 for (DSGraph::node_iterator I = GG.node_begin(), E = GG.node_end();
56 I != E; ++I) {
57 if (I->getGlobalsList().size() <= 1) continue;
58
59 // First, build up the equivalence set for this block of globals.
60 const std::vector<GlobalValue*> &GVs = I->getGlobalsList();
61 GlobalValue *First = GVs[0];
62 for (unsigned i = 1, e = GVs.size(); i != e; ++i)
63 GlobalECs.unionSets(First, GVs[i]);
Misha Brukman2b37d7c2005-04-21 21:13:18 +000064
Chris Lattner33b42762005-03-25 16:45:43 +000065 // Next, get the leader element.
66 assert(First == GlobalECs.getLeaderValue(First) &&
67 "First did not end up being the leader?");
Misha Brukman2b37d7c2005-04-21 21:13:18 +000068
Chris Lattner33b42762005-03-25 16:45:43 +000069 // Next, remove all globals from the scalar map that are not the leader.
70 assert(GVs[0] == First && "First had to be at the front!");
71 for (unsigned i = 1, e = GVs.size(); i != e; ++i) {
72 ECGlobals.insert(GVs[i]);
73 SM.erase(SM.find(GVs[i]));
74 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +000075
Chris Lattner33b42762005-03-25 16:45:43 +000076 // Finally, change the global node to only contain the leader.
77 I->clearGlobals();
78 I->addGlobal(First);
79 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +000080
Chris Lattner33b42762005-03-25 16:45:43 +000081 DEBUG(GG.AssertGraphOK());
82}
83
84/// EliminateUsesOfECGlobals - Once we have determined that some globals are in
85/// really just equivalent to some other globals, remove the globals from the
86/// specified DSGraph (if present), and merge any nodes with their leader nodes.
87static void EliminateUsesOfECGlobals(DSGraph &G,
88 const std::set<GlobalValue*> &ECGlobals) {
89 DSScalarMap &SM = G.getScalarMap();
90 EquivalenceClasses<GlobalValue*> &GlobalECs = SM.getGlobalECs();
91
92 bool MadeChange = false;
93 for (DSScalarMap::global_iterator GI = SM.global_begin(), E = SM.global_end();
94 GI != E; ) {
95 GlobalValue *GV = *GI++;
96 if (!ECGlobals.count(GV)) continue;
97
98 const DSNodeHandle &GVNH = SM[GV];
99 assert(!GVNH.isNull() && "Global has null NH!?");
100
101 // Okay, this global is in some equivalence class. Start by finding the
102 // leader of the class.
103 GlobalValue *Leader = GlobalECs.getLeaderValue(GV);
104
105 // If the leader isn't already in the graph, insert it into the node
106 // corresponding to GV.
107 if (!SM.global_count(Leader)) {
108 GVNH.getNode()->addGlobal(Leader);
109 SM[Leader] = GVNH;
110 } else {
111 // Otherwise, the leader is in the graph, make sure the nodes are the
112 // merged in the specified graph.
113 const DSNodeHandle &LNH = SM[Leader];
114 if (LNH.getNode() != GVNH.getNode())
115 LNH.mergeWith(GVNH);
116 }
117
118 // Next step, remove the global from the DSNode.
119 GVNH.getNode()->removeGlobal(GV);
120
121 // Finally, remove the global from the ScalarMap.
122 SM.erase(GV);
123 MadeChange = true;
124 }
125
126 DEBUG(if(MadeChange) G.AssertGraphOK());
127}
128
Andrew Lenharthab390d02006-06-19 18:23:36 +0000129static void AddGlobalToNode(BUDataStructures* B, DSCallSite D, Function* F) {
130 if(!AddGlobals)
131 return;
132 if(D.isIndirectCall()) {
133 DSGraph* GI = &B->getDSGraph(D.getCaller());
134 DSNodeHandle& NHF = GI->getNodeForValue(F);
135 DSCallSite DL = GI->getDSCallSiteForCallSite(D.getCallSite());
136 if (DL.getCalleeNode() != NHF.getNode() || NHF.isNull()) {
137 if (NHF.isNull()) {
138 DSNode *N = new DSNode(F->getType()->getElementType(), GI); // Create the node
139 N->addGlobal(F);
140 NHF.setTo(N,0);
Bill Wendling5294fb02006-11-17 07:33:59 +0000141 DOUT << "Adding " << F->getName() << " to a call node in "
142 << D.getCaller().getName() << "\n";
Andrew Lenharthab390d02006-06-19 18:23:36 +0000143 }
144 DL.getCalleeNode()->mergeWith(NHF, 0);
145 }
146 }
147}
148
Chris Lattneraa0b4682002-11-09 21:12:07 +0000149// run - Calculate the bottom up data structure graphs for each function in the
150// program.
151//
Chris Lattnerb12914b2004-09-20 04:48:05 +0000152bool BUDataStructures::runOnModule(Module &M) {
Chris Lattner312edd32003-06-28 22:14:55 +0000153 LocalDataStructures &LocalDSA = getAnalysis<LocalDataStructures>();
Chris Lattnerf4f62272005-03-19 22:23:45 +0000154 GlobalECs = LocalDSA.getGlobalECs();
155
156 GlobalsGraph = new DSGraph(LocalDSA.getGlobalsGraph(), GlobalECs);
Chris Lattner20167e32003-02-03 19:11:38 +0000157 GlobalsGraph->setPrintAuxCalls();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000158
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000159 IndCallGraphMap = new std::map<std::vector<Function*>,
160 std::pair<DSGraph*, std::vector<DSNodeHandle> > >();
161
Chris Lattnerf189bce2005-02-01 17:35:52 +0000162 std::vector<Function*> Stack;
163 hash_map<Function*, unsigned> ValMap;
164 unsigned NextID = 1;
165
Chris Lattnera9c9c022002-11-11 21:35:13 +0000166 Function *MainFunc = M.getMainFunction();
167 if (MainFunc)
Chris Lattnerf189bce2005-02-01 17:35:52 +0000168 calculateGraphs(MainFunc, Stack, NextID, ValMap);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000169
170 // Calculate the graphs for any functions that are unreachable from main...
Chris Lattneraa0b4682002-11-09 21:12:07 +0000171 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner5d5b6d62003-07-01 16:04:18 +0000172 if (!I->isExternal() && !DSInfo.count(I)) {
Chris Lattnera9c9c022002-11-11 21:35:13 +0000173 if (MainFunc)
Bill Wendling5294fb02006-11-17 07:33:59 +0000174 DOUT << "*** BU: Function unreachable from main: "
175 << I->getName() << "\n";
Chris Lattnerf189bce2005-02-01 17:35:52 +0000176 calculateGraphs(I, Stack, NextID, ValMap); // Calculate all graphs.
Chris Lattnera9c9c022002-11-11 21:35:13 +0000177 }
Chris Lattner6c874612003-07-02 23:42:48 +0000178
Chris Lattner86db3642005-02-04 19:59:49 +0000179 // If we computed any temporary indcallgraphs, free them now.
180 for (std::map<std::vector<Function*>,
181 std::pair<DSGraph*, std::vector<DSNodeHandle> > >::iterator I =
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000182 IndCallGraphMap->begin(), E = IndCallGraphMap->end(); I != E; ++I) {
Chris Lattner86db3642005-02-04 19:59:49 +0000183 I->second.second.clear(); // Drop arg refs into the graph.
184 delete I->second.first;
185 }
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000186 delete IndCallGraphMap;
Chris Lattner86db3642005-02-04 19:59:49 +0000187
Chris Lattnerec157b72003-09-20 23:27:05 +0000188 // At the end of the bottom-up pass, the globals graph becomes complete.
189 // FIXME: This is not the right way to do this, but it is sorta better than
Chris Lattner11fc9302003-09-20 23:58:33 +0000190 // nothing! In particular, externally visible globals and unresolvable call
191 // nodes at the end of the BU phase should make things that they point to
192 // incomplete in the globals graph.
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000193 //
Chris Lattnerc3f5f772004-02-08 01:51:48 +0000194 GlobalsGraph->removeTriviallyDeadNodes();
Chris Lattnerec157b72003-09-20 23:27:05 +0000195 GlobalsGraph->maskIncompleteMarkers();
Chris Lattnera66e3532005-03-13 20:15:06 +0000196
Chris Lattner9547ade2005-03-22 22:10:22 +0000197 // Mark external globals incomplete.
198 GlobalsGraph->markIncompleteNodes(DSGraph::IgnoreGlobals);
199
Chris Lattner33b42762005-03-25 16:45:43 +0000200 // Grow the equivalence classes for the globals to include anything that we
201 // now know to be aliased.
202 std::set<GlobalValue*> ECGlobals;
203 BuildGlobalECs(*GlobalsGraph, ECGlobals);
204 if (!ECGlobals.empty()) {
Chris Lattnera5ed1bd2005-04-21 16:09:43 +0000205 NamedRegionTimer X("Bottom-UP EC Cleanup");
Bill Wendling5294fb02006-11-17 07:33:59 +0000206 DOUT << "Eliminating " << ECGlobals.size() << " EC Globals!\n";
Chris Lattner33b42762005-03-25 16:45:43 +0000207 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
208 E = DSInfo.end(); I != E; ++I)
209 EliminateUsesOfECGlobals(*I->second, ECGlobals);
210 }
211
Chris Lattnera66e3532005-03-13 20:15:06 +0000212 // Merge the globals variables (not the calls) from the globals graph back
213 // into the main function's graph so that the main function contains all of
214 // the information about global pools and GV usage in the program.
Chris Lattner49e88e82005-03-15 22:10:04 +0000215 if (MainFunc && !MainFunc->isExternal()) {
Chris Lattnera66e3532005-03-13 20:15:06 +0000216 DSGraph &MainGraph = getOrCreateGraph(MainFunc);
217 const DSGraph &GG = *MainGraph.getGlobalsGraph();
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000218 ReachabilityCloner RC(MainGraph, GG,
219 DSGraph::DontCloneCallNodes |
220 DSGraph::DontCloneAuxCallNodes);
Chris Lattnera66e3532005-03-13 20:15:06 +0000221
222 // Clone the global nodes into this graph.
223 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
224 E = GG.getScalarMap().global_end(); I != E; ++I)
225 if (isa<GlobalVariable>(*I))
226 RC.getClonedNH(GG.getNodeForValue(*I));
227
Chris Lattner270cf502005-03-13 20:32:26 +0000228 MainGraph.maskIncompleteMarkers();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000229 MainGraph.markIncompleteNodes(DSGraph::MarkFormalArgs |
Chris Lattnera66e3532005-03-13 20:15:06 +0000230 DSGraph::IgnoreGlobals);
Andrew Lenharthab390d02006-06-19 18:23:36 +0000231
232 //Debug messages if along the way we didn't resolve a call site
233 //also update the call graph and callsites we did find.
234 for(DSGraph::afc_iterator ii = MainGraph.afc_begin(),
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000235 ee = MainGraph.afc_end(); ii != ee; ++ii) {
Andrew Lenharthab390d02006-06-19 18:23:36 +0000236 std::vector<Function*> Funcs;
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000237 GetAllCalleesN(*ii, Funcs);
Bill Wendling5294fb02006-11-17 07:33:59 +0000238 DOUT << "Lost site\n";
Andrew Lenharth7445ea62006-10-13 17:38:22 +0000239 DEBUG(ii->getCallSite().getInstruction()->dump());
Andrew Lenharthab390d02006-06-19 18:23:36 +0000240 for (std::vector<Function*>::iterator iif = Funcs.begin(), eef = Funcs.end();
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000241 iif != eef; ++iif) {
242 AddGlobalToNode(this, *ii, *iif);
Bill Wendling5294fb02006-11-17 07:33:59 +0000243 DOUT << "Adding\n";
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000244 ActualCallees.insert(std::make_pair(ii->getCallSite().getInstruction(), *iif));
Andrew Lenharthab390d02006-06-19 18:23:36 +0000245 }
246 }
247
Chris Lattnera66e3532005-03-13 20:15:06 +0000248 }
249
Andrew Lenharthab390d02006-06-19 18:23:36 +0000250 NumCallEdges += ActualCallees.size();
251
Chris Lattneraa0b4682002-11-09 21:12:07 +0000252 return false;
253}
Chris Lattner55c10582002-10-03 20:38:41 +0000254
Chris Lattnera9c9c022002-11-11 21:35:13 +0000255DSGraph &BUDataStructures::getOrCreateGraph(Function *F) {
256 // Has the graph already been created?
257 DSGraph *&Graph = DSInfo[F];
258 if (Graph) return *Graph;
259
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000260 DSGraph &LocGraph = getAnalysis<LocalDataStructures>().getDSGraph(*F);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000261
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000262 // Steal the local graph.
263 Graph = new DSGraph(GlobalECs, LocGraph.getTargetData());
264 Graph->spliceFrom(LocGraph);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000265
266 Graph->setGlobalsGraph(GlobalsGraph);
267 Graph->setPrintAuxCalls();
268
269 // Start with a copy of the original call sites...
270 Graph->getAuxFunctionCalls() = Graph->getFunctionCalls();
271 return *Graph;
272}
273
Chris Lattner6b9eb352005-03-20 02:42:07 +0000274static bool isVAHackFn(const Function *F) {
275 return F->getName() == "printf" || F->getName() == "sscanf" ||
276 F->getName() == "fprintf" || F->getName() == "open" ||
277 F->getName() == "sprintf" || F->getName() == "fputs" ||
Chris Lattnera5ed1bd2005-04-21 16:09:43 +0000278 F->getName() == "fscanf" || F->getName() == "malloc" ||
279 F->getName() == "free";
Chris Lattner6b9eb352005-03-20 02:42:07 +0000280}
281
282static bool isResolvableFunc(const Function* callee) {
283 return !callee->isExternal() || isVAHackFn(callee);
284}
285
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000286static void GetAllCallees(const DSCallSite &CS,
287 std::vector<Function*> &Callees) {
288 if (CS.isDirectCall()) {
289 if (isResolvableFunc(CS.getCalleeFunc()))
290 Callees.push_back(CS.getCalleeFunc());
291 } else if (!CS.getCalleeNode()->isIncomplete()) {
292 // Get all callees.
293 unsigned OldSize = Callees.size();
294 CS.getCalleeNode()->addFullFunctionList(Callees);
295
296 // If any of the callees are unresolvable, remove the whole batch!
297 for (unsigned i = OldSize, e = Callees.size(); i != e; ++i)
298 if (!isResolvableFunc(Callees[i])) {
299 Callees.erase(Callees.begin()+OldSize, Callees.end());
300 return;
301 }
302 }
303}
304
Andrew Lenharthab390d02006-06-19 18:23:36 +0000305//returns true if all callees were resolved
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000306static bool GetAllCalleesN(const DSCallSite &CS,
Chris Lattner6b9eb352005-03-20 02:42:07 +0000307 std::vector<Function*> &Callees) {
308 if (CS.isDirectCall()) {
Andrew Lenharthab390d02006-06-19 18:23:36 +0000309 if (isResolvableFunc(CS.getCalleeFunc())) {
Chris Lattner6b9eb352005-03-20 02:42:07 +0000310 Callees.push_back(CS.getCalleeFunc());
Andrew Lenharthab390d02006-06-19 18:23:36 +0000311 return true;
312 } else
313 return false;
314 } else {
Chris Lattner6b9eb352005-03-20 02:42:07 +0000315 // Get all callees.
Andrew Lenharthab390d02006-06-19 18:23:36 +0000316 bool retval = CS.getCalleeNode()->isComplete();
Chris Lattner6b9eb352005-03-20 02:42:07 +0000317 unsigned OldSize = Callees.size();
318 CS.getCalleeNode()->addFullFunctionList(Callees);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000319
Andrew Lenharthab390d02006-06-19 18:23:36 +0000320 // If any of the callees are unresolvable, remove that one
321 for (unsigned i = OldSize; i != Callees.size(); ++i)
Chris Lattner6b9eb352005-03-20 02:42:07 +0000322 if (!isResolvableFunc(Callees[i])) {
Andrew Lenharthab390d02006-06-19 18:23:36 +0000323 Callees.erase(Callees.begin()+i);
324 --i;
325 retval = false;
Chris Lattner6b9eb352005-03-20 02:42:07 +0000326 }
Andrew Lenharthab390d02006-06-19 18:23:36 +0000327 return retval;
328 //return false;
Chris Lattner6b9eb352005-03-20 02:42:07 +0000329 }
330}
331
Chris Lattner6b9eb352005-03-20 02:42:07 +0000332/// GetAllAuxCallees - Return a list containing all of the resolvable callees in
333/// the aux list for the specified graph in the Callees vector.
334static void GetAllAuxCallees(DSGraph &G, std::vector<Function*> &Callees) {
335 Callees.clear();
336 for (DSGraph::afc_iterator I = G.afc_begin(), E = G.afc_end(); I != E; ++I)
337 GetAllCallees(*I, Callees);
338}
339
Chris Lattnera9c9c022002-11-11 21:35:13 +0000340unsigned BUDataStructures::calculateGraphs(Function *F,
341 std::vector<Function*> &Stack,
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000342 unsigned &NextID,
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000343 hash_map<Function*, unsigned> &ValMap) {
Chris Lattner6acfe922003-11-13 05:04:19 +0000344 assert(!ValMap.count(F) && "Shouldn't revisit functions!");
Chris Lattnera9c9c022002-11-11 21:35:13 +0000345 unsigned Min = NextID++, MyID = Min;
346 ValMap[F] = Min;
347 Stack.push_back(F);
348
Chris Lattner16437ff2004-03-04 17:05:28 +0000349 // FIXME! This test should be generalized to be any function that we have
350 // already processed, in the case when there isn't a main or there are
351 // unreachable functions!
Chris Lattnera9c9c022002-11-11 21:35:13 +0000352 if (F->isExternal()) { // sprintf, fprintf, sscanf, etc...
353 // No callees!
354 Stack.pop_back();
355 ValMap[F] = ~0;
356 return Min;
357 }
358
359 DSGraph &Graph = getOrCreateGraph(F);
Andrew Lenharthab390d02006-06-19 18:23:36 +0000360 if (UpdateGlobals)
361 Graph.updateFromGlobalGraph();
Chris Lattnera9c9c022002-11-11 21:35:13 +0000362
Chris Lattner6b9eb352005-03-20 02:42:07 +0000363 // Find all callee functions.
364 std::vector<Function*> CalleeFunctions;
365 GetAllAuxCallees(Graph, CalleeFunctions);
366
Chris Lattnera9c9c022002-11-11 21:35:13 +0000367 // The edges out of the current node are the call site targets...
Chris Lattner6b9eb352005-03-20 02:42:07 +0000368 for (unsigned i = 0, e = CalleeFunctions.size(); i != e; ++i) {
369 Function *Callee = CalleeFunctions[i];
Chris Lattnera9c9c022002-11-11 21:35:13 +0000370 unsigned M;
371 // Have we visited the destination function yet?
Chris Lattner41c04f72003-02-01 04:52:08 +0000372 hash_map<Function*, unsigned>::iterator It = ValMap.find(Callee);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000373 if (It == ValMap.end()) // No, visit it now.
374 M = calculateGraphs(Callee, Stack, NextID, ValMap);
375 else // Yes, get it's number.
376 M = It->second;
377 if (M < Min) Min = M;
378 }
379
380 assert(ValMap[F] == MyID && "SCC construction assumption wrong!");
381 if (Min != MyID)
382 return Min; // This is part of a larger SCC!
383
384 // If this is a new SCC, process it now.
385 if (Stack.back() == F) { // Special case the single "SCC" case here.
Bill Wendling5294fb02006-11-17 07:33:59 +0000386 DOUT << "Visiting single node SCC #: " << MyID << " fn: "
387 << F->getName() << "\n";
Chris Lattnera9c9c022002-11-11 21:35:13 +0000388 Stack.pop_back();
Chris Lattner0eea6182003-06-30 05:09:58 +0000389 DSGraph &G = getDSGraph(*F);
Bill Wendling5294fb02006-11-17 07:33:59 +0000390 DOUT << " [BU] Calculating graph for: " << F->getName()<< "\n";
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000391 calculateGraph(G);
Bill Wendling5294fb02006-11-17 07:33:59 +0000392 DOUT << " [BU] Done inlining: " << F->getName() << " ["
393 << G.getGraphSize() << "+" << G.getAuxFunctionCalls().size()
394 << "]\n";
Chris Lattnera9c9c022002-11-11 21:35:13 +0000395
Chris Lattnerae5f6032002-11-17 22:16:28 +0000396 if (MaxSCC < 1) MaxSCC = 1;
397
Chris Lattner6b9eb352005-03-20 02:42:07 +0000398 // Should we revisit the graph? Only do it if there are now new resolvable
399 // callees.
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000400 GetAllAuxCallees(Graph, CalleeFunctions);
401 if (!CalleeFunctions.empty()) {
Bill Wendling5294fb02006-11-17 07:33:59 +0000402 DOUT << "Recalculating " << F->getName() << " due to new knowledge\n";
Chris Lattnera9c9c022002-11-11 21:35:13 +0000403 ValMap.erase(F);
404 return calculateGraphs(F, Stack, NextID, ValMap);
405 } else {
406 ValMap[F] = ~0U;
407 }
408 return MyID;
409
410 } else {
411 // SCCFunctions - Keep track of the functions in the current SCC
412 //
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000413 std::vector<DSGraph*> SCCGraphs;
Chris Lattnera9c9c022002-11-11 21:35:13 +0000414
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000415 unsigned SCCSize = 1;
416 Function *NF = Stack.back();
417 ValMap[NF] = ~0U;
418 DSGraph &SCCGraph = getDSGraph(*NF);
Chris Lattner0eea6182003-06-30 05:09:58 +0000419
Chris Lattner0eea6182003-06-30 05:09:58 +0000420 // First thing first, collapse all of the DSGraphs into a single graph for
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000421 // the entire SCC. Splice all of the graphs into one and discard all of the
422 // old graphs.
Chris Lattner0eea6182003-06-30 05:09:58 +0000423 //
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000424 while (NF != F) {
425 Stack.pop_back();
426 NF = Stack.back();
427 ValMap[NF] = ~0U;
Chris Lattnera2197132005-03-22 00:36:51 +0000428
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000429 DSGraph &NFG = getDSGraph(*NF);
430
431 // Update the Function -> DSG map.
432 for (DSGraph::retnodes_iterator I = NFG.retnodes_begin(),
433 E = NFG.retnodes_end(); I != E; ++I)
434 DSInfo[I->first] = &SCCGraph;
435
436 SCCGraph.spliceFrom(NFG);
437 delete &NFG;
438
439 ++SCCSize;
Chris Lattner0eea6182003-06-30 05:09:58 +0000440 }
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000441 Stack.pop_back();
Chris Lattner20da24c2005-03-25 00:06:09 +0000442
Bill Wendling5294fb02006-11-17 07:33:59 +0000443 DOUT << "Calculating graph for SCC #: " << MyID << " of size: "
444 << SCCSize << "\n";
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000445
446 // Compute the Max SCC Size.
447 if (MaxSCC < SCCSize)
448 MaxSCC = SCCSize;
Chris Lattnera9c9c022002-11-11 21:35:13 +0000449
Chris Lattner744f9392003-07-02 04:37:48 +0000450 // Clean up the graph before we start inlining a bunch again...
Chris Lattnerb2dbdc12005-03-25 00:05:04 +0000451 SCCGraph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattner744f9392003-07-02 04:37:48 +0000452
Chris Lattner0eea6182003-06-30 05:09:58 +0000453 // Now that we have one big happy family, resolve all of the call sites in
454 // the graph...
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000455 calculateGraph(SCCGraph);
Bill Wendling5294fb02006-11-17 07:33:59 +0000456 DOUT << " [BU] Done inlining SCC [" << SCCGraph.getGraphSize()
457 << "+" << SCCGraph.getAuxFunctionCalls().size() << "]\n"
458 << "DONE with SCC #: " << MyID << "\n";
Chris Lattnera9c9c022002-11-11 21:35:13 +0000459
460 // We never have to revisit "SCC" processed functions...
Chris Lattnera9c9c022002-11-11 21:35:13 +0000461 return MyID;
462 }
463
464 return MyID; // == Min
465}
466
467
Chris Lattner0d9bab82002-07-18 00:12:30 +0000468// releaseMemory - If the pass pipeline is done with this pass, we can release
469// our memory... here...
470//
Chris Lattner65512d22005-03-23 21:59:34 +0000471void BUDataStructures::releaseMyMemory() {
Chris Lattner0eea6182003-06-30 05:09:58 +0000472 for (hash_map<Function*, DSGraph*>::iterator I = DSInfo.begin(),
473 E = DSInfo.end(); I != E; ++I) {
474 I->second->getReturnNodes().erase(I->first);
475 if (I->second->getReturnNodes().empty())
476 delete I->second;
477 }
Chris Lattner0d9bab82002-07-18 00:12:30 +0000478
479 // Empty map so next time memory is released, data structures are not
480 // re-deleted.
481 DSInfo.clear();
Chris Lattneraa0b4682002-11-09 21:12:07 +0000482 delete GlobalsGraph;
483 GlobalsGraph = 0;
Chris Lattner0d9bab82002-07-18 00:12:30 +0000484}
485
Chris Lattnera5ed1bd2005-04-21 16:09:43 +0000486DSGraph &BUDataStructures::CreateGraphForExternalFunction(const Function &Fn) {
487 Function *F = const_cast<Function*>(&Fn);
488 DSGraph *DSG = new DSGraph(GlobalECs, GlobalsGraph->getTargetData());
489 DSInfo[F] = DSG;
490 DSG->setGlobalsGraph(GlobalsGraph);
491 DSG->setPrintAuxCalls();
492
493 // Add function to the graph.
494 DSG->getReturnNodes().insert(std::make_pair(F, DSNodeHandle()));
495
496 if (F->getName() == "free") { // Taking the address of free.
Jeff Cohen00b168892005-07-27 06:12:32 +0000497
Chris Lattnera5ed1bd2005-04-21 16:09:43 +0000498 // Free should take a single pointer argument, mark it as heap memory.
499 DSNode *N = new DSNode(0, DSG);
500 N->setHeapNodeMarker();
501 DSG->getNodeForValue(F->arg_begin()).mergeWith(N);
502
503 } else {
504 std::cerr << "Unrecognized external function: " << F->getName() << "\n";
505 abort();
506 }
507
508 return *DSG;
509}
510
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000511void BUDataStructures::calculateGraph(DSGraph &Graph) {
Chris Lattnera1198b52005-04-25 19:16:31 +0000512 // If this graph contains the main function, clone the globals graph into this
513 // graph before we inline callees and other fun stuff.
514 bool ContainsMain = false;
515 DSGraph::ReturnNodesTy &ReturnNodes = Graph.getReturnNodes();
516
517 for (DSGraph::ReturnNodesTy::iterator I = ReturnNodes.begin(),
518 E = ReturnNodes.end(); I != E; ++I)
519 if (I->first->hasExternalLinkage() && I->first->getName() == "main") {
520 ContainsMain = true;
521 break;
522 }
523
524 // If this graph contains main, copy the contents of the globals graph over.
525 // Note that this is *required* for correctness. If a callee contains a use
526 // of a global, we have to make sure to link up nodes due to global-argument
527 // bindings.
528 if (ContainsMain) {
529 const DSGraph &GG = *Graph.getGlobalsGraph();
530 ReachabilityCloner RC(Graph, GG,
531 DSGraph::DontCloneCallNodes |
532 DSGraph::DontCloneAuxCallNodes);
533
534 // Clone the global nodes into this graph.
535 for (DSScalarMap::global_iterator I = GG.getScalarMap().global_begin(),
536 E = GG.getScalarMap().global_end(); I != E; ++I)
537 if (isa<GlobalVariable>(*I))
538 RC.getClonedNH(GG.getNodeForValue(*I));
539 }
540
541
Chris Lattnera9c9c022002-11-11 21:35:13 +0000542 // Move our call site list into TempFCs so that inline call sites go into the
543 // new call site list and doesn't invalidate our iterators!
Chris Lattnera9548d92005-01-30 23:51:02 +0000544 std::list<DSCallSite> TempFCs;
545 std::list<DSCallSite> &AuxCallsList = Graph.getAuxFunctionCalls();
Chris Lattnera9c9c022002-11-11 21:35:13 +0000546 TempFCs.swap(AuxCallsList);
Chris Lattner8a5db462002-11-11 00:01:34 +0000547
Chris Lattnerf189bce2005-02-01 17:35:52 +0000548 bool Printed = false;
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000549 std::vector<Function*> CalledFuncs;
Chris Lattneraf8650e2005-02-01 21:37:27 +0000550 while (!TempFCs.empty()) {
551 DSCallSite &CS = *TempFCs.begin();
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000552
553 CalledFuncs.clear();
Chris Lattnera9548d92005-01-30 23:51:02 +0000554
Chris Lattner5021b8c2005-03-18 23:19:47 +0000555 // Fast path for noop calls. Note that we don't care about merging globals
556 // in the callee with nodes in the caller here.
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000557 if (CS.getRetVal().isNull() && CS.getNumPtrArgs() == 0) {
558 TempFCs.erase(TempFCs.begin());
559 continue;
560 } else if (CS.isDirectCall() && isVAHackFn(CS.getCalleeFunc())) {
561 TempFCs.erase(TempFCs.begin());
562 continue;
563 }
564
565 GetAllCallees(CS, CalledFuncs);
566
567 if (CalledFuncs.empty()) {
568 // Remember that we could not resolve this yet!
569 AuxCallsList.splice(AuxCallsList.end(), TempFCs, TempFCs.begin());
570 continue;
571 } else {
572 DSGraph *GI;
573 Instruction *TheCall = CS.getCallSite().getInstruction();
574
575 if (CalledFuncs.size() == 1) {
576 Function *Callee = CalledFuncs[0];
Chris Lattnereb144f52005-03-21 20:20:49 +0000577 ActualCallees.insert(std::make_pair(TheCall, Callee));
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000578
579 // Get the data structure graph for the called function.
Chris Lattner86db3642005-02-04 19:59:49 +0000580 GI = &getDSGraph(*Callee); // Graph to inline
Bill Wendling5294fb02006-11-17 07:33:59 +0000581 DOUT << " Inlining graph for " << Callee->getName()
582 << "[" << GI->getGraphSize() << "+"
583 << GI->getAuxFunctionCalls().size() << "] into '"
584 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
585 << Graph.getAuxFunctionCalls().size() << "]\n";
Chris Lattner86db3642005-02-04 19:59:49 +0000586 Graph.mergeInGraph(CS, *Callee, *GI,
Chris Lattner20cd1362005-02-01 21:49:43 +0000587 DSGraph::StripAllocaBit|DSGraph::DontCloneCallNodes);
588 ++NumBUInlines;
Chris Lattner86db3642005-02-04 19:59:49 +0000589 } else {
590 if (!Printed)
591 std::cerr << "In Fns: " << Graph.getFunctionNames() << "\n";
592 std::cerr << " calls " << CalledFuncs.size()
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000593 << " fns from site: " << CS.getCallSite().getInstruction()
Chris Lattner86db3642005-02-04 19:59:49 +0000594 << " " << *CS.getCallSite().getInstruction();
Chris Lattner86db3642005-02-04 19:59:49 +0000595 std::cerr << " Fns =";
Chris Lattnereb144f52005-03-21 20:20:49 +0000596 unsigned NumPrinted = 0;
597
Chris Lattner86db3642005-02-04 19:59:49 +0000598 for (std::vector<Function*>::iterator I = CalledFuncs.begin(),
Chris Lattnereb144f52005-03-21 20:20:49 +0000599 E = CalledFuncs.end(); I != E; ++I) {
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000600 if (NumPrinted++ < 8) std::cerr << " " << (*I)->getName();
Chris Lattnereb144f52005-03-21 20:20:49 +0000601
602 // Add the call edges to the call graph.
603 ActualCallees.insert(std::make_pair(TheCall, *I));
604 }
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000605 std::cerr << "\n";
Chris Lattner86db3642005-02-04 19:59:49 +0000606
607 // See if we already computed a graph for this set of callees.
608 std::sort(CalledFuncs.begin(), CalledFuncs.end());
609 std::pair<DSGraph*, std::vector<DSNodeHandle> > &IndCallGraph =
Chris Lattnerbcc70bc2005-02-07 16:09:15 +0000610 (*IndCallGraphMap)[CalledFuncs];
Chris Lattner86db3642005-02-04 19:59:49 +0000611
612 if (IndCallGraph.first == 0) {
613 std::vector<Function*>::iterator I = CalledFuncs.begin(),
614 E = CalledFuncs.end();
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000615
Chris Lattner86db3642005-02-04 19:59:49 +0000616 // Start with a copy of the first graph.
Chris Lattnerf4f62272005-03-19 22:23:45 +0000617 GI = IndCallGraph.first = new DSGraph(getDSGraph(**I), GlobalECs);
Chris Lattner86db3642005-02-04 19:59:49 +0000618 GI->setGlobalsGraph(Graph.getGlobalsGraph());
619 std::vector<DSNodeHandle> &Args = IndCallGraph.second;
620
621 // Get the argument nodes for the first callee. The return value is
622 // the 0th index in the vector.
623 GI->getFunctionArgumentsForCall(*I, Args);
624
625 // Merge all of the other callees into this graph.
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000626 for (++I; I != E; ++I) {
Chris Lattner86db3642005-02-04 19:59:49 +0000627 // If the graph already contains the nodes for the function, don't
628 // bother merging it in again.
629 if (!GI->containsFunction(*I)) {
Chris Lattnera2197132005-03-22 00:36:51 +0000630 GI->cloneInto(getDSGraph(**I));
Chris Lattner86db3642005-02-04 19:59:49 +0000631 ++NumBUInlines;
632 }
633
634 std::vector<DSNodeHandle> NextArgs;
635 GI->getFunctionArgumentsForCall(*I, NextArgs);
636 unsigned i = 0, e = Args.size();
637 for (; i != e; ++i) {
638 if (i == NextArgs.size()) break;
639 Args[i].mergeWith(NextArgs[i]);
640 }
641 for (e = NextArgs.size(); i != e; ++i)
642 Args.push_back(NextArgs[i]);
643 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000644
Chris Lattner86db3642005-02-04 19:59:49 +0000645 // Clean up the final graph!
646 GI->removeDeadNodes(DSGraph::KeepUnreachableGlobals);
647 } else {
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000648 std::cerr << "***\n*** RECYCLED GRAPH ***\n***\n";
Chris Lattner86db3642005-02-04 19:59:49 +0000649 }
650
651 GI = IndCallGraph.first;
652
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000653 // Merge the unified graph into this graph now.
Bill Wendling5294fb02006-11-17 07:33:59 +0000654 DOUT << " Inlining multi callee graph "
655 << "[" << GI->getGraphSize() << "+"
656 << GI->getAuxFunctionCalls().size() << "] into '"
657 << Graph.getFunctionNames() << "' [" << Graph.getGraphSize() <<"+"
658 << Graph.getAuxFunctionCalls().size() << "]\n";
Chris Lattner86db3642005-02-04 19:59:49 +0000659
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000660 Graph.mergeInGraph(CS, IndCallGraph.second, *GI,
661 DSGraph::StripAllocaBit |
662 DSGraph::DontCloneCallNodes);
663 ++NumBUInlines;
Chris Lattneraf8650e2005-02-01 21:37:27 +0000664 }
Chris Lattnera9548d92005-01-30 23:51:02 +0000665 }
Andrew Lenharth72be6e62006-10-23 19:53:37 +0000666 TempFCs.erase(TempFCs.begin());
Chris Lattnera9548d92005-01-30 23:51:02 +0000667 }
Chris Lattnera9c9c022002-11-11 21:35:13 +0000668
Vikram S. Adve1da1d322003-07-16 21:42:03 +0000669 // Recompute the Incomplete markers
Chris Lattnera9c9c022002-11-11 21:35:13 +0000670 Graph.maskIncompleteMarkers();
Chris Lattner394471f2003-01-23 22:05:33 +0000671 Graph.markIncompleteNodes(DSGraph::MarkFormalArgs);
Vikram S. Adve1da1d322003-07-16 21:42:03 +0000672
673 // Delete dead nodes. Treat globals that are unreachable but that can
674 // reach live nodes as live.
Chris Lattner394471f2003-01-23 22:05:33 +0000675 Graph.removeDeadNodes(DSGraph::KeepUnreachableGlobals);
Chris Lattnera9c9c022002-11-11 21:35:13 +0000676
Chris Lattner35679372004-02-21 00:30:28 +0000677 // When this graph is finalized, clone the globals in the graph into the
678 // globals graph to make sure it has everything, from all graphs.
679 DSScalarMap &MainSM = Graph.getScalarMap();
680 ReachabilityCloner RC(*GlobalsGraph, Graph, DSGraph::StripAllocaBit);
681
Chris Lattner3b7b81b2004-10-31 21:54:51 +0000682 // Clone everything reachable from globals in the function graph into the
Chris Lattner35679372004-02-21 00:30:28 +0000683 // globals graph.
684 for (DSScalarMap::global_iterator I = MainSM.global_begin(),
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000685 E = MainSM.global_end(); I != E; ++I)
Chris Lattner35679372004-02-21 00:30:28 +0000686 RC.getClonedNH(MainSM[*I]);
687
Chris Lattnera9c9c022002-11-11 21:35:13 +0000688 //Graph.writeGraphToFile(std::cerr, "bu_" + F.getName());
Chris Lattnera9c9c022002-11-11 21:35:13 +0000689}
Chris Lattner851b5342005-01-24 20:00:14 +0000690
691static const Function *getFnForValue(const Value *V) {
692 if (const Instruction *I = dyn_cast<Instruction>(V))
693 return I->getParent()->getParent();
694 else if (const Argument *A = dyn_cast<Argument>(V))
695 return A->getParent();
696 else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
697 return BB->getParent();
698 return 0;
699}
700
701/// deleteValue/copyValue - Interfaces to update the DSGraphs in the program.
702/// These correspond to the interfaces defined in the AliasAnalysis class.
703void BUDataStructures::deleteValue(Value *V) {
704 if (const Function *F = getFnForValue(V)) { // Function local value?
705 // If this is a function local value, just delete it from the scalar map!
706 getDSGraph(*F).getScalarMap().eraseIfExists(V);
707 return;
708 }
709
Chris Lattnercff8ac22005-01-31 00:10:45 +0000710 if (Function *F = dyn_cast<Function>(V)) {
Chris Lattner851b5342005-01-24 20:00:14 +0000711 assert(getDSGraph(*F).getReturnNodes().size() == 1 &&
712 "cannot handle scc's");
713 delete DSInfo[F];
714 DSInfo.erase(F);
715 return;
716 }
717
718 assert(!isa<GlobalVariable>(V) && "Do not know how to delete GV's yet!");
719}
720
721void BUDataStructures::copyValue(Value *From, Value *To) {
722 if (From == To) return;
723 if (const Function *F = getFnForValue(From)) { // Function local value?
724 // If this is a function local value, just delete it from the scalar map!
725 getDSGraph(*F).getScalarMap().copyScalarIfExists(From, To);
726 return;
727 }
728
729 if (Function *FromF = dyn_cast<Function>(From)) {
730 Function *ToF = cast<Function>(To);
731 assert(!DSInfo.count(ToF) && "New Function already exists!");
Chris Lattnerf4f62272005-03-19 22:23:45 +0000732 DSGraph *NG = new DSGraph(getDSGraph(*FromF), GlobalECs);
Chris Lattner851b5342005-01-24 20:00:14 +0000733 DSInfo[ToF] = NG;
734 assert(NG->getReturnNodes().size() == 1 && "Cannot copy SCC's yet!");
735
736 // Change the Function* is the returnnodes map to the ToF.
Chris Lattnera5f47ea2005-03-15 16:55:04 +0000737 DSNodeHandle Ret = NG->retnodes_begin()->second;
Chris Lattner851b5342005-01-24 20:00:14 +0000738 NG->getReturnNodes().clear();
739 NG->getReturnNodes()[ToF] = Ret;
740 return;
741 }
742
Chris Lattnerc5132e62005-03-24 04:22:04 +0000743 if (const Function *F = getFnForValue(To)) {
744 DSGraph &G = getDSGraph(*F);
745 G.getScalarMap().copyScalarIfExists(From, To);
746 return;
747 }
748
749 std::cerr << *From;
750 std::cerr << *To;
751 assert(0 && "Do not know how to copy this yet!");
752 abort();
Chris Lattner851b5342005-01-24 20:00:14 +0000753}