blob: 69d7673547853b529f47a81a306d8e144efd9f39 [file] [log] [blame]
Chris Lattnerf7e95942003-08-31 01:54:59 +00001//===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerf7e95942003-08-31 01:54:59 +00009//
10// This file implements the CallGraphSCCPass class, which is used for passes
11// which are implemented as bottom-up traversals on the call graph. Because
12// there may be cycles in the call graph, passes of this type operate on the
13// call-graph in SCC order: that is, they process function bottom-up, except for
14// recursive functions, which they process all at once.
15//
16//===----------------------------------------------------------------------===//
17
Chandler Carruth839a98e2013-01-07 15:26:48 +000018#include "llvm/Analysis/CallGraphSCCPass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/ADT/SCCIterator.h"
Chris Lattner6fbe7042010-04-21 00:47:40 +000020#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/CallGraph.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Function.h"
23#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzka34390c72014-05-16 02:33:15 +000024#include "llvm/IR/LLVMContext.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000025#include "llvm/IR/LegacyPassManagers.h"
Andrew Kayloraa641a52016-04-22 22:06:11 +000026#include "llvm/IR/OptBisect.h"
Chris Lattner6fbe7042010-04-21 00:47:40 +000027#include "llvm/Support/CommandLine.h"
Chris Lattnereedcd842009-08-31 07:23:46 +000028#include "llvm/Support/Debug.h"
Chris Lattner707431c2010-03-30 04:03:22 +000029#include "llvm/Support/Timer.h"
Chris Lattner13626022009-08-23 06:03:38 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattner8d083812004-04-20 21:30:06 +000031using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000032
Chandler Carruthf1221bd2014-04-22 02:48:03 +000033#define DEBUG_TYPE "cgscc-passmgr"
34
Chris Lattner6fbe7042010-04-21 00:47:40 +000035static cl::opt<unsigned>
Chris Lattnerfc8d9ee2010-05-01 01:15:56 +000036MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4));
Chris Lattner6fbe7042010-04-21 00:47:40 +000037
38STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
39
Devang Patel48537a02007-01-17 21:45:01 +000040//===----------------------------------------------------------------------===//
41// CGPassManager
42//
Dale Johannesen50f03762009-09-10 22:01:32 +000043/// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
Devang Patel48537a02007-01-17 21:45:01 +000044
Dan Gohmand78c4002008-05-13 00:00:25 +000045namespace {
46
Devang Patel48537a02007-01-17 21:45:01 +000047class CGPassManager : public ModulePass, public PMDataManager {
Devang Patel48537a02007-01-17 21:45:01 +000048public:
Devang Patel8c78a0b2007-05-03 01:11:54 +000049 static char ID;
Andrew Trick08966212011-08-29 17:07:00 +000050 explicit CGPassManager()
51 : ModulePass(ID), PMDataManager() { }
Devang Patel48537a02007-01-17 21:45:01 +000052
Sanjay Pateld45a3f12015-03-10 03:48:14 +000053 /// Execute all of the passes scheduled for execution. Keep track of
Devang Patel48537a02007-01-17 21:45:01 +000054 /// whether any of the passes modifies the module, and if so, return true.
Craig Toppere9ba7592014-03-05 07:30:04 +000055 bool runOnModule(Module &M) override;
Devang Patel48537a02007-01-17 21:45:01 +000056
Owen Anderson1aa27512012-11-15 00:14:15 +000057 using ModulePass::doInitialization;
58 using ModulePass::doFinalization;
59
Bill Wendling5f14a012009-02-11 18:19:24 +000060 bool doInitialization(CallGraph &CG);
61 bool doFinalization(CallGraph &CG);
Devang Patel48537a02007-01-17 21:45:01 +000062
63 /// Pass Manager itself does not invalidate any analysis info.
Craig Toppere9ba7592014-03-05 07:30:04 +000064 void getAnalysisUsage(AnalysisUsage &Info) const override {
Devang Patel48537a02007-01-17 21:45:01 +000065 // CGPassManager walks SCC and it needs CallGraph.
Chandler Carruth6378cf52013-11-26 04:19:30 +000066 Info.addRequired<CallGraphWrapperPass>();
Devang Patel48537a02007-01-17 21:45:01 +000067 Info.setPreservesAll();
68 }
69
Craig Toppere9ba7592014-03-05 07:30:04 +000070 const char *getPassName() const override {
Devang Patelf7fea8a2007-02-01 22:09:37 +000071 return "CallGraph Pass Manager";
72 }
73
Craig Toppere9ba7592014-03-05 07:30:04 +000074 PMDataManager *getAsPMDataManager() override { return this; }
75 Pass *getAsPass() override { return this; }
Chris Lattner2fa26e52010-01-22 05:24:46 +000076
Devang Patel48537a02007-01-17 21:45:01 +000077 // Print passes managed by this manager
Craig Toppere9ba7592014-03-05 07:30:04 +000078 void dumpPassStructure(unsigned Offset) override {
David Greene3d646312009-12-23 23:09:39 +000079 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
Devang Patel48537a02007-01-17 21:45:01 +000080 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
81 Pass *P = getContainedPass(Index);
Dan Gohmanf71c5212010-08-19 01:29:07 +000082 P->dumpPassStructure(Offset + 1);
Devang Patel48537a02007-01-17 21:45:01 +000083 dumpLastUses(P, Offset+1);
84 }
85 }
86
87 Pass *getContainedPass(unsigned N) {
Chris Lattner13626022009-08-23 06:03:38 +000088 assert(N < PassVector.size() && "Pass number out of range!");
89 return static_cast<Pass *>(PassVector[N]);
Devang Patel48537a02007-01-17 21:45:01 +000090 }
91
Craig Toppere9ba7592014-03-05 07:30:04 +000092 PassManagerType getPassManagerType() const override {
Devang Patel48537a02007-01-17 21:45:01 +000093 return PMT_CallGraphPassManager;
94 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +000095
96private:
Chris Lattner6fbe7042010-04-21 00:47:40 +000097 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
98 bool &DevirtualizedCall);
99
Chris Lattner4422d312010-04-16 22:42:17 +0000100 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
Chris Lattner6fbe7042010-04-21 00:47:40 +0000101 CallGraph &CG, bool &CallGraphUpToDate,
102 bool &DevirtualizedCall);
103 bool RefreshCallGraph(CallGraphSCC &CurSCC, CallGraph &CG,
Chris Lattnere33167a2009-09-01 18:32:03 +0000104 bool IsCheckingMode);
Devang Patel48537a02007-01-17 21:45:01 +0000105};
106
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000107} // end anonymous namespace.
Dan Gohmand78c4002008-05-13 00:00:25 +0000108
Devang Patel8c78a0b2007-05-03 01:11:54 +0000109char CGPassManager::ID = 0;
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000110
David Greene9b063df2010-04-02 23:17:14 +0000111
Chris Lattner4422d312010-04-16 22:42:17 +0000112bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
Chris Lattner6fbe7042010-04-21 00:47:40 +0000113 CallGraph &CG, bool &CallGraphUpToDate,
114 bool &DevirtualizedCall) {
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000115 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000116 PMDataManager *PM = P->getAsPMDataManager();
117
Craig Topper353eda42014-04-24 06:44:33 +0000118 if (!PM) {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000119 CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
Chris Lattnereedcd842009-08-31 07:23:46 +0000120 if (!CallGraphUpToDate) {
Chris Lattner6fbe7042010-04-21 00:47:40 +0000121 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
Chris Lattnereedcd842009-08-31 07:23:46 +0000122 CallGraphUpToDate = true;
123 }
Chris Lattner339c82d2009-09-01 20:33:43 +0000124
Chris Lattner707431c2010-03-30 04:03:22 +0000125 {
126 TimeRegion PassTimer(getPassTimer(CGSP));
127 Changed = CGSP->runOnSCC(CurSCC);
128 }
Chris Lattnere33167a2009-09-01 18:32:03 +0000129
130 // After the CGSCCPass is done, when assertions are enabled, use
131 // RefreshCallGraph to verify that the callgraph was correctly updated.
132#ifndef NDEBUG
133 if (Changed)
134 RefreshCallGraph(CurSCC, CG, true);
135#endif
136
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000137 return Changed;
138 }
139
Chris Lattner0b1c7232010-01-22 05:46:59 +0000140
141 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
142 "Invalid CGPassManager member");
143 FPPassManager *FPP = (FPPassManager*)P;
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000144
145 // Run pass P on all functions in the current SCC.
Sanjay Patelc6012542015-03-10 03:26:39 +0000146 for (CallGraphNode *CGN : CurSCC) {
147 if (Function *F = CGN->getFunction()) {
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000148 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
Juergen Ributzka34390c72014-05-16 02:33:15 +0000149 {
150 TimeRegion PassTimer(getPassTimer(FPP));
151 Changed |= FPP->runOnFunction(*F);
152 }
153 F->getContext().yield();
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000154 }
155 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000156
Chris Lattnera9262bb2009-08-31 17:08:30 +0000157 // The function pass(es) modified the IR, they may have clobbered the
Chris Lattnereedcd842009-08-31 07:23:46 +0000158 // callgraph.
159 if (Changed && CallGraphUpToDate) {
David Greenef8ed9912009-12-23 20:10:59 +0000160 DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
Chris Lattnereedcd842009-08-31 07:23:46 +0000161 << P->getPassName() << '\n');
162 CallGraphUpToDate = false;
163 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000164 return Changed;
165}
166
Chris Lattnere33167a2009-09-01 18:32:03 +0000167
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000168/// Scan the functions in the specified CFG and resync the
Chris Lattnere33167a2009-09-01 18:32:03 +0000169/// callgraph with the call sites found in it. This is used after
170/// FunctionPasses have potentially munged the callgraph, and can be used after
171/// CallGraphSCC passes to verify that they correctly updated the callgraph.
172///
Chris Lattner6fbe7042010-04-21 00:47:40 +0000173/// This function returns true if it devirtualized an existing function call,
174/// meaning it turned an indirect call into a direct call. This happens when
175/// a function pass like GVN optimizes away stuff feeding the indirect call.
176/// This never happens in checking mode.
177///
178bool CGPassManager::RefreshCallGraph(CallGraphSCC &CurSCC,
Chris Lattnere33167a2009-09-01 18:32:03 +0000179 CallGraph &CG, bool CheckingMode) {
Chris Lattner063d0652009-09-01 06:31:31 +0000180 DenseMap<Value*, CallGraphNode*> CallSites;
Chris Lattnereedcd842009-08-31 07:23:46 +0000181
David Greenef8ed9912009-12-23 20:10:59 +0000182 DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
Chris Lattnereedcd842009-08-31 07:23:46 +0000183 << " nodes:\n";
Sanjay Patelc6012542015-03-10 03:26:39 +0000184 for (CallGraphNode *CGN : CurSCC)
185 CGN->dump();
Chris Lattnereedcd842009-08-31 07:23:46 +0000186 );
187
188 bool MadeChange = false;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000189 bool DevirtualizedCall = false;
Chris Lattnereedcd842009-08-31 07:23:46 +0000190
191 // Scan all functions in the SCC.
Chris Lattner4422d312010-04-16 22:42:17 +0000192 unsigned FunctionNo = 0;
193 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
194 SCCIdx != E; ++SCCIdx, ++FunctionNo) {
195 CallGraphNode *CGN = *SCCIdx;
Chris Lattnereedcd842009-08-31 07:23:46 +0000196 Function *F = CGN->getFunction();
Craig Topper353eda42014-04-24 06:44:33 +0000197 if (!F || F->isDeclaration()) continue;
Chris Lattnereedcd842009-08-31 07:23:46 +0000198
199 // Walk the function body looking for call sites. Sync up the call sites in
200 // CGN with those actually in the function.
Chris Lattner532112b2010-05-01 06:38:43 +0000201
202 // Keep track of the number of direct and indirect calls that were
203 // invalidated and removed.
204 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000205
Chris Lattnereedcd842009-08-31 07:23:46 +0000206 // Get the set of call sites currently in the function.
Duncan Sands5632d962009-09-02 03:48:41 +0000207 for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
Chris Lattner063d0652009-09-01 06:31:31 +0000208 // If this call site is null, then the function pass deleted the call
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000209 // entirely and the WeakVH nulled it out.
Craig Topper353eda42014-04-24 06:44:33 +0000210 if (!I->first ||
Chris Lattner063d0652009-09-01 06:31:31 +0000211 // If we've already seen this call site, then the FunctionPass RAUW'd
212 // one call with another, which resulted in two "uses" in the edge
213 // list of the same call.
214 CallSites.count(I->first) ||
215
Chad Rosier7a20ed72015-04-14 15:52:57 +0000216 // If the call edge is not from a call or invoke, or it is a
217 // instrinsic call, then the function pass RAUW'd a call with
218 // another value. This can happen when constant folding happens
219 // of well known functions etc.
220 !CallSite(I->first) ||
Sanjoy Dasc65d43e2015-06-18 19:28:26 +0000221 (CallSite(I->first).getCalledFunction() &&
222 CallSite(I->first).getCalledFunction()->isIntrinsic() &&
223 Intrinsic::isLeaf(
224 CallSite(I->first).getCalledFunction()->getIntrinsicID()))) {
Chris Lattnere33167a2009-09-01 18:32:03 +0000225 assert(!CheckingMode &&
226 "CallGraphSCCPass did not update the CallGraph correctly!");
227
Chris Lattner532112b2010-05-01 06:38:43 +0000228 // If this was an indirect call site, count it.
Craig Topper353eda42014-04-24 06:44:33 +0000229 if (!I->second->getFunction())
Chris Lattner532112b2010-05-01 06:38:43 +0000230 ++NumIndirectRemoved;
231 else
232 ++NumDirectRemoved;
233
Chris Lattner65fb5972009-09-02 04:39:04 +0000234 // Just remove the edge from the set of callees, keep track of whether
235 // I points to the last element of the vector.
236 bool WasLast = I + 1 == E;
Chris Lattner063d0652009-09-01 06:31:31 +0000237 CGN->removeCallEdge(I);
Chris Lattner8f232762009-09-02 04:34:06 +0000238
Chris Lattner65fb5972009-09-02 04:39:04 +0000239 // If I pointed to the last element of the vector, we have to bail out:
240 // iterator checking rejects comparisons of the resultant pointer with
241 // end.
242 if (WasLast)
243 break;
Chris Lattner063d0652009-09-01 06:31:31 +0000244 E = CGN->end();
Chris Lattner063d0652009-09-01 06:31:31 +0000245 continue;
246 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000247
Chris Lattner063d0652009-09-01 06:31:31 +0000248 assert(!CallSites.count(I->first) &&
Chris Lattnereedcd842009-08-31 07:23:46 +0000249 "Call site occurs in node multiple times");
Sanjay Patel4c219fd2014-11-12 18:25:47 +0000250
251 CallSite CS(I->first);
252 if (CS) {
253 Function *Callee = CS.getCalledFunction();
254 // Ignore intrinsics because they're not really function calls.
255 if (!Callee || !(Callee->isIntrinsic()))
256 CallSites.insert(std::make_pair(I->first, I->second));
257 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000258 ++I;
Chris Lattnereedcd842009-08-31 07:23:46 +0000259 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000260
Chris Lattnereedcd842009-08-31 07:23:46 +0000261 // Loop over all of the instructions in the function, getting the callsites.
Chris Lattner532112b2010-05-01 06:38:43 +0000262 // Keep track of the number of direct/indirect calls added.
263 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
Benjamin Krameraa209152016-06-26 17:27:42 +0000264
265 for (BasicBlock &BB : *F)
266 for (Instruction &I : BB) {
267 CallSite CS(&I);
Nuno Lopes674acc12012-06-29 17:49:32 +0000268 if (!CS) continue;
269 Function *Callee = CS.getCalledFunction();
270 if (Callee && Callee->isIntrinsic()) continue;
Chris Lattnereedcd842009-08-31 07:23:46 +0000271
272 // If this call site already existed in the callgraph, just verify it
273 // matches up to expectations and remove it from CallSites.
Chris Lattner063d0652009-09-01 06:31:31 +0000274 DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
Chris Lattnereedcd842009-08-31 07:23:46 +0000275 CallSites.find(CS.getInstruction());
276 if (ExistingIt != CallSites.end()) {
277 CallGraphNode *ExistingNode = ExistingIt->second;
278
279 // Remove from CallSites since we have now seen it.
280 CallSites.erase(ExistingIt);
281
282 // Verify that the callee is right.
283 if (ExistingNode->getFunction() == CS.getCalledFunction())
284 continue;
285
Chris Lattnere33167a2009-09-01 18:32:03 +0000286 // If we are in checking mode, we are not allowed to actually mutate
287 // the callgraph. If this is a case where we can infer that the
288 // callgraph is less precise than it could be (e.g. an indirect call
289 // site could be turned direct), don't reject it in checking mode, and
290 // don't tweak it to be more precise.
291 if (CheckingMode && CS.getCalledFunction() &&
Craig Topper353eda42014-04-24 06:44:33 +0000292 ExistingNode->getFunction() == nullptr)
Chris Lattnere33167a2009-09-01 18:32:03 +0000293 continue;
294
295 assert(!CheckingMode &&
296 "CallGraphSCCPass did not update the CallGraph correctly!");
297
Chris Lattnereedcd842009-08-31 07:23:46 +0000298 // If not, we either went from a direct call to indirect, indirect to
299 // direct, or direct to different direct.
300 CallGraphNode *CalleeNode;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000301 if (Function *Callee = CS.getCalledFunction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000302 CalleeNode = CG.getOrInsertFunction(Callee);
Chris Lattner6fbe7042010-04-21 00:47:40 +0000303 // Keep track of whether we turned an indirect call into a direct
304 // one.
Craig Topper353eda42014-04-24 06:44:33 +0000305 if (!ExistingNode->getFunction()) {
Chris Lattner6fbe7042010-04-21 00:47:40 +0000306 DevirtualizedCall = true;
307 DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
308 << Callee->getName() << "'\n");
309 }
310 } else {
Chris Lattnereedcd842009-08-31 07:23:46 +0000311 CalleeNode = CG.getCallsExternalNode();
Chris Lattner6fbe7042010-04-21 00:47:40 +0000312 }
Chris Lattner339c82d2009-09-01 20:33:43 +0000313
314 // Update the edge target in CGN.
Chris Lattner055cf262010-04-22 20:42:33 +0000315 CGN->replaceCallEdge(CS, CS, CalleeNode);
Chris Lattnereedcd842009-08-31 07:23:46 +0000316 MadeChange = true;
317 continue;
318 }
319
Chris Lattnere33167a2009-09-01 18:32:03 +0000320 assert(!CheckingMode &&
321 "CallGraphSCCPass did not update the CallGraph correctly!");
322
Chris Lattner532112b2010-05-01 06:38:43 +0000323 // If the call site didn't exist in the CGN yet, add it.
Chris Lattnereedcd842009-08-31 07:23:46 +0000324 CallGraphNode *CalleeNode;
Chris Lattner532112b2010-05-01 06:38:43 +0000325 if (Function *Callee = CS.getCalledFunction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000326 CalleeNode = CG.getOrInsertFunction(Callee);
Chris Lattner532112b2010-05-01 06:38:43 +0000327 ++NumDirectAdded;
328 } else {
Chris Lattnereedcd842009-08-31 07:23:46 +0000329 CalleeNode = CG.getCallsExternalNode();
Chris Lattner532112b2010-05-01 06:38:43 +0000330 ++NumIndirectAdded;
331 }
Chris Lattnereedcd842009-08-31 07:23:46 +0000332
333 CGN->addCalledFunction(CS, CalleeNode);
334 MadeChange = true;
335 }
336
Chris Lattner532112b2010-05-01 06:38:43 +0000337 // We scanned the old callgraph node, removing invalidated call sites and
338 // then added back newly found call sites. One thing that can happen is
339 // that an old indirect call site was deleted and replaced with a new direct
340 // call. In this case, we have devirtualized a call, and CGSCCPM would like
341 // to iteratively optimize the new code. Unfortunately, we don't really
342 // have a great way to detect when this happens. As an approximation, we
343 // just look at whether the number of indirect calls is reduced and the
344 // number of direct calls is increased. There are tons of ways to fool this
345 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
346 // direct call) but this is close enough.
347 if (NumIndirectRemoved > NumIndirectAdded &&
348 NumDirectRemoved < NumDirectAdded)
349 DevirtualizedCall = true;
350
Chris Lattnereedcd842009-08-31 07:23:46 +0000351 // After scanning this function, if we still have entries in callsites, then
Chris Lattner063d0652009-09-01 06:31:31 +0000352 // they are dangling pointers. WeakVH should save us for this, so abort if
353 // this happens.
354 assert(CallSites.empty() && "Dangling pointers found in call sites map");
Chris Lattnereedcd842009-08-31 07:23:46 +0000355
Chris Lattner063d0652009-09-01 06:31:31 +0000356 // Periodically do an explicit clear to remove tombstones when processing
357 // large scc's.
Chris Lattner4422d312010-04-16 22:42:17 +0000358 if ((FunctionNo & 15) == 15)
Chris Lattner063d0652009-09-01 06:31:31 +0000359 CallSites.clear();
Chris Lattnereedcd842009-08-31 07:23:46 +0000360 }
361
362 DEBUG(if (MadeChange) {
David Greenef8ed9912009-12-23 20:10:59 +0000363 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
Sanjay Patelc6012542015-03-10 03:26:39 +0000364 for (CallGraphNode *CGN : CurSCC)
365 CGN->dump();
Chris Lattner532112b2010-05-01 06:38:43 +0000366 if (DevirtualizedCall)
367 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
368
Chris Lattnereedcd842009-08-31 07:23:46 +0000369 } else {
David Greenef8ed9912009-12-23 20:10:59 +0000370 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
Chris Lattnereedcd842009-08-31 07:23:46 +0000371 }
372 );
Duncan Sandsa41634e2011-08-12 14:54:45 +0000373 (void)MadeChange;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000374
375 return DevirtualizedCall;
376}
377
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000378/// Execute the body of the entire pass manager on the specified SCC.
379/// This keeps track of whether a function pass devirtualizes
Chris Lattner6fbe7042010-04-21 00:47:40 +0000380/// any calls and returns it in DevirtualizedCall.
381bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
382 bool &DevirtualizedCall) {
383 bool Changed = false;
384
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000385 // Keep track of whether the callgraph is known to be up-to-date or not.
386 // The CGSSC pass manager runs two types of passes:
Chris Lattner6fbe7042010-04-21 00:47:40 +0000387 // CallGraphSCC Passes and other random function passes. Because other
388 // random function passes are not CallGraph aware, they may clobber the
389 // call graph by introducing new calls or deleting other ones. This flag
390 // is set to false when we run a function pass so that we know to clean up
391 // the callgraph when we need to run a CGSCCPass again.
392 bool CallGraphUpToDate = true;
393
394 // Run all passes on current SCC.
395 for (unsigned PassNo = 0, e = getNumContainedPasses();
396 PassNo != e; ++PassNo) {
397 Pass *P = getContainedPass(PassNo);
398
399 // If we're in -debug-pass=Executions mode, construct the SCC node list,
400 // otherwise avoid constructing this string as it is expensive.
401 if (isPassDebuggingExecutionsOrMore()) {
402 std::string Functions;
403 #ifndef NDEBUG
404 raw_string_ostream OS(Functions);
405 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
406 I != E; ++I) {
407 if (I != CurSCC.begin()) OS << ", ";
408 (*I)->print(OS);
409 }
410 OS.flush();
411 #endif
412 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
413 }
414 dumpRequiredSet(P);
415
416 initializeAnalysisImpl(P);
417
418 // Actually run this pass on the current SCC.
419 Changed |= RunPassOnSCC(P, CurSCC, CG,
420 CallGraphUpToDate, DevirtualizedCall);
421
422 if (Changed)
423 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
424 dumpPreservedSet(P);
425
426 verifyPreservedAnalysis(P);
427 removeNotPreservedAnalysis(P);
428 recordAvailableAnalysis(P);
429 removeDeadPasses(P, "", ON_CG_MSG);
430 }
431
432 // If the callgraph was left out of date (because the last pass run was a
433 // functionpass), refresh it before we move on to the next SCC.
434 if (!CallGraphUpToDate)
435 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
436 return Changed;
Chris Lattnereedcd842009-08-31 07:23:46 +0000437}
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000438
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000439/// Execute all of the passes scheduled for execution. Keep track of
Devang Patel48537a02007-01-17 21:45:01 +0000440/// whether any of the passes modifies the module, and if so, return true.
441bool CGPassManager::runOnModule(Module &M) {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000442 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
Bill Wendling5f14a012009-02-11 18:19:24 +0000443 bool Changed = doInitialization(CG);
Chris Lattner6fbe7042010-04-21 00:47:40 +0000444
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000445 // Walk the callgraph in bottom-up SCC order.
Chris Lattner5518b812010-04-16 22:59:24 +0000446 scc_iterator<CallGraph*> CGI = scc_begin(&CG);
447
Andrew Kayloraa641a52016-04-22 22:06:11 +0000448 CallGraphSCC CurSCC(CG, &CGI);
Chris Lattner5518b812010-04-16 22:59:24 +0000449 while (!CGI.isAtEnd()) {
Chris Lattner305b1152009-08-31 00:19:58 +0000450 // Copy the current SCC and increment past it so that the pass can hack
451 // on the SCC if it wants to without invalidating our iterator.
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000452 const std::vector<CallGraphNode *> &NodeVec = *CGI;
453 CurSCC.initialize(NodeVec.data(), NodeVec.data() + NodeVec.size());
Chris Lattner305b1152009-08-31 00:19:58 +0000454 ++CGI;
Yaron Kerenafe39832015-07-02 14:17:12 +0000455
Chris Lattner6fbe7042010-04-21 00:47:40 +0000456 // At the top level, we run all the passes in this pass manager on the
457 // functions in this SCC. However, we support iterative compilation in the
458 // case where a function pass devirtualizes a call to a function. For
459 // example, it is very common for a function pass (often GVN or instcombine)
460 // to eliminate the addressing that feeds into a call. With that improved
461 // information, we would like the call to be an inline candidate, infer
462 // mod-ref information etc.
463 //
464 // Because of this, we allow iteration up to a specified iteration count.
465 // This only happens in the case of a devirtualized call, so we only burn
466 // compile time in the case that we're making progress. We also have a hard
467 // iteration count limit in case there is crazy code.
468 unsigned Iteration = 0;
469 bool DevirtualizedCall = false;
470 do {
Chris Lattner055cf262010-04-22 20:42:33 +0000471 DEBUG(if (Iteration)
472 dbgs() << " SCCPASSMGR: Re-visiting SCC, iteration #"
473 << Iteration << '\n');
Chris Lattner6fbe7042010-04-21 00:47:40 +0000474 DevirtualizedCall = false;
475 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
476 } while (Iteration++ < MaxIterations && DevirtualizedCall);
Chris Lattnereedcd842009-08-31 07:23:46 +0000477
Chris Lattner6fbe7042010-04-21 00:47:40 +0000478 if (DevirtualizedCall)
479 DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " << Iteration
480 << " times, due to -max-cg-scc-iterations\n");
Chris Lattnereedcd842009-08-31 07:23:46 +0000481
Chris Lattner6fbe7042010-04-21 00:47:40 +0000482 if (Iteration > MaxSCCIterations)
483 MaxSCCIterations = Iteration;
484
Devang Patel48537a02007-01-17 21:45:01 +0000485 }
Bill Wendling5f14a012009-02-11 18:19:24 +0000486 Changed |= doFinalization(CG);
Devang Patel48537a02007-01-17 21:45:01 +0000487 return Changed;
488}
489
Chris Lattner6fbe7042010-04-21 00:47:40 +0000490
Devang Patel48537a02007-01-17 21:45:01 +0000491/// Initialize CG
Bill Wendling5f14a012009-02-11 18:19:24 +0000492bool CGPassManager::doInitialization(CallGraph &CG) {
Devang Patel48537a02007-01-17 21:45:01 +0000493 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000494 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
495 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
496 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
497 "Invalid CGPassManager member");
498 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000499 } else {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000500 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000501 }
Devang Patel48537a02007-01-17 21:45:01 +0000502 }
503 return Changed;
504}
505
506/// Finalize CG
Bill Wendling5f14a012009-02-11 18:19:24 +0000507bool CGPassManager::doFinalization(CallGraph &CG) {
Devang Patel48537a02007-01-17 21:45:01 +0000508 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000509 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
510 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
511 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
512 "Invalid CGPassManager member");
513 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000514 } else {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000515 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000516 }
Devang Patel48537a02007-01-17 21:45:01 +0000517 }
518 return Changed;
519}
520
Chris Lattner6d1208f2010-04-16 21:43:55 +0000521//===----------------------------------------------------------------------===//
Chris Lattner4422d312010-04-16 22:42:17 +0000522// CallGraphSCC Implementation
523//===----------------------------------------------------------------------===//
524
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000525/// This informs the SCC and the pass manager that the specified
Chris Lattner5518b812010-04-16 22:59:24 +0000526/// Old node has been deleted, and New is to be used in its place.
527void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
528 assert(Old != New && "Should not replace node with self");
529 for (unsigned i = 0; ; ++i) {
530 assert(i != Nodes.size() && "Node not in SCC");
531 if (Nodes[i] != Old) continue;
532 Nodes[i] = New;
533 break;
534 }
Chris Lattnerde023a32010-04-16 23:04:30 +0000535
536 // Update the active scc_iterator so that it doesn't contain dangling
537 // pointers to the old CallGraphNode.
538 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
539 CGI->ReplaceNode(Old, New);
Chris Lattner5518b812010-04-16 22:59:24 +0000540}
Chris Lattner4422d312010-04-16 22:42:17 +0000541
542
543//===----------------------------------------------------------------------===//
Chris Lattner6d1208f2010-04-16 21:43:55 +0000544// CallGraphSCCPass Implementation
545//===----------------------------------------------------------------------===//
David Greene9b063df2010-04-02 23:17:14 +0000546
Devang Patel020f4f22007-01-23 21:55:17 +0000547/// Assign pass manager to manage this pass.
Devang Patel1f8200b2007-01-23 21:52:35 +0000548void CallGraphSCCPass::assignPassManager(PMStack &PMS,
Anton Korobeynikovfb801512007-04-16 18:10:23 +0000549 PassManagerType PreferredType) {
Devang Patel1f8200b2007-01-23 21:52:35 +0000550 // Find CGPassManager
Duncan Sands60f28bf2007-07-19 09:42:01 +0000551 while (!PMS.empty() &&
552 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
553 PMS.pop();
Devang Patel1f8200b2007-01-23 21:52:35 +0000554
Chris Lattner9efd4fc2010-01-22 05:37:10 +0000555 assert(!PMS.empty() && "Unable to handle Call Graph Pass");
556 CGPassManager *CGP;
557
558 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
559 CGP = (CGPassManager*)PMS.top();
560 else {
561 // Create new Call Graph SCC Pass Manager if it does not exist.
562 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
Devang Patel1f8200b2007-01-23 21:52:35 +0000563 PMDataManager *PMD = PMS.top();
564
565 // [1] Create new Call Graph Pass Manager
Andrew Trick08966212011-08-29 17:07:00 +0000566 CGP = new CGPassManager();
Devang Patel1f8200b2007-01-23 21:52:35 +0000567
568 // [2] Set up new manager's top level manager
569 PMTopLevelManager *TPM = PMD->getTopLevelManager();
570 TPM->addIndirectPassManager(CGP);
571
572 // [3] Assign manager to manage this new manager. This may create
573 // and push new managers into PMS
Chris Lattner9efd4fc2010-01-22 05:37:10 +0000574 Pass *P = CGP;
Devang Patel703de8f2007-06-21 22:29:02 +0000575 TPM->schedulePass(P);
Devang Patel1f8200b2007-01-23 21:52:35 +0000576
577 // [4] Push new manager into PMS
578 PMS.push(CGP);
579 }
580
581 CGP->add(this);
582}
583
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000584/// For this class, we declare that we require and preserve the call graph.
585/// If the derived class implements this method, it should
Chris Lattnerf7e95942003-08-31 01:54:59 +0000586/// always explicitly call the implementation here.
587void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000588 AU.addRequired<CallGraphWrapperPass>();
589 AU.addPreserved<CallGraphWrapperPass>();
Chris Lattnerf7e95942003-08-31 01:54:59 +0000590}
Chris Lattner6d1208f2010-04-16 21:43:55 +0000591
592
593//===----------------------------------------------------------------------===//
594// PrintCallGraphPass Implementation
595//===----------------------------------------------------------------------===//
596
597namespace {
598 /// PrintCallGraphPass - Print a Module corresponding to a call graph.
599 ///
600 class PrintCallGraphPass : public CallGraphSCCPass {
601 std::string Banner;
602 raw_ostream &Out; // raw_ostream to print on.
603
604 public:
605 static char ID;
Chris Lattner6d1208f2010-04-16 21:43:55 +0000606 PrintCallGraphPass(const std::string &B, raw_ostream &o)
Owen Andersona7aed182010-08-06 18:33:48 +0000607 : CallGraphSCCPass(ID), Banner(B), Out(o) {}
Craig Toppere9ba7592014-03-05 07:30:04 +0000608
609 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner6d1208f2010-04-16 21:43:55 +0000610 AU.setPreservesAll();
611 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000612
613 bool runOnSCC(CallGraphSCC &SCC) override {
Chris Lattner6d1208f2010-04-16 21:43:55 +0000614 Out << Banner;
Sanjay Patelc6012542015-03-10 03:26:39 +0000615 for (CallGraphNode *CGN : SCC) {
Weiming Zhao0f1762c2016-01-06 22:55:03 +0000616 if (CGN->getFunction()) {
617 if (isFunctionInPrintList(CGN->getFunction()->getName()))
618 CGN->getFunction()->print(Out);
619 } else
Richard Trieuf2a79522014-07-03 02:11:49 +0000620 Out << "\nPrinting <null> Function\n";
Richard Trieua23043c2014-06-09 22:53:16 +0000621 }
Chris Lattner6d1208f2010-04-16 21:43:55 +0000622 return false;
623 }
624 };
625
626} // end anonymous namespace.
627
628char PrintCallGraphPass::ID = 0;
629
630Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &O,
631 const std::string &Banner) const {
632 return new PrintCallGraphPass(Banner, O);
633}
634
Andrew Kayloraa641a52016-04-22 22:06:11 +0000635bool CallGraphSCCPass::skipSCC(CallGraphSCC &SCC) const {
636 return !SCC.getCallGraph().getModule()
637 .getContext()
638 .getOptBisect()
639 .shouldRunPass(this, SCC);
640}
Mehdi Aminibbacddf2016-06-10 16:19:46 +0000641
642char DummyCGSCCPass::ID = 0;
643INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false,
644 false)