blob: 1c84cf5c6b076e446afcea9dd7b547396dd66ea6 [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
Mehdi Amini117296c2016-10-01 02:56:57 +000070 StringRef getPassName() const override { return "CallGraph Pass Manager"; }
Devang Patelf7fea8a2007-02-01 22:09:37 +000071
Craig Toppere9ba7592014-03-05 07:30:04 +000072 PMDataManager *getAsPMDataManager() override { return this; }
73 Pass *getAsPass() override { return this; }
Chris Lattner2fa26e52010-01-22 05:24:46 +000074
Devang Patel48537a02007-01-17 21:45:01 +000075 // Print passes managed by this manager
Craig Toppere9ba7592014-03-05 07:30:04 +000076 void dumpPassStructure(unsigned Offset) override {
David Greene3d646312009-12-23 23:09:39 +000077 errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
Devang Patel48537a02007-01-17 21:45:01 +000078 for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
79 Pass *P = getContainedPass(Index);
Dan Gohmanf71c5212010-08-19 01:29:07 +000080 P->dumpPassStructure(Offset + 1);
Devang Patel48537a02007-01-17 21:45:01 +000081 dumpLastUses(P, Offset+1);
82 }
83 }
84
85 Pass *getContainedPass(unsigned N) {
Chris Lattner13626022009-08-23 06:03:38 +000086 assert(N < PassVector.size() && "Pass number out of range!");
87 return static_cast<Pass *>(PassVector[N]);
Devang Patel48537a02007-01-17 21:45:01 +000088 }
89
Craig Toppere9ba7592014-03-05 07:30:04 +000090 PassManagerType getPassManagerType() const override {
Devang Patel48537a02007-01-17 21:45:01 +000091 return PMT_CallGraphPassManager;
92 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +000093
94private:
Chris Lattner6fbe7042010-04-21 00:47:40 +000095 bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
96 bool &DevirtualizedCall);
97
Chris Lattner4422d312010-04-16 22:42:17 +000098 bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
Chris Lattner6fbe7042010-04-21 00:47:40 +000099 CallGraph &CG, bool &CallGraphUpToDate,
100 bool &DevirtualizedCall);
Mehdi Aminic137c282016-08-08 18:51:05 +0000101 bool RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
Chris Lattnere33167a2009-09-01 18:32:03 +0000102 bool IsCheckingMode);
Devang Patel48537a02007-01-17 21:45:01 +0000103};
104
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000105} // end anonymous namespace.
Dan Gohmand78c4002008-05-13 00:00:25 +0000106
Devang Patel8c78a0b2007-05-03 01:11:54 +0000107char CGPassManager::ID = 0;
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000108
David Greene9b063df2010-04-02 23:17:14 +0000109
Chris Lattner4422d312010-04-16 22:42:17 +0000110bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
Chris Lattner6fbe7042010-04-21 00:47:40 +0000111 CallGraph &CG, bool &CallGraphUpToDate,
112 bool &DevirtualizedCall) {
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000113 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000114 PMDataManager *PM = P->getAsPMDataManager();
115
Craig Topper353eda42014-04-24 06:44:33 +0000116 if (!PM) {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000117 CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
Chris Lattnereedcd842009-08-31 07:23:46 +0000118 if (!CallGraphUpToDate) {
Chris Lattner6fbe7042010-04-21 00:47:40 +0000119 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
Chris Lattnereedcd842009-08-31 07:23:46 +0000120 CallGraphUpToDate = true;
121 }
Chris Lattner339c82d2009-09-01 20:33:43 +0000122
Chris Lattner707431c2010-03-30 04:03:22 +0000123 {
124 TimeRegion PassTimer(getPassTimer(CGSP));
125 Changed = CGSP->runOnSCC(CurSCC);
126 }
Chris Lattnere33167a2009-09-01 18:32:03 +0000127
128 // After the CGSCCPass is done, when assertions are enabled, use
129 // RefreshCallGraph to verify that the callgraph was correctly updated.
130#ifndef NDEBUG
131 if (Changed)
132 RefreshCallGraph(CurSCC, CG, true);
133#endif
134
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000135 return Changed;
136 }
137
Chris Lattner0b1c7232010-01-22 05:46:59 +0000138
139 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
140 "Invalid CGPassManager member");
141 FPPassManager *FPP = (FPPassManager*)P;
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000142
143 // Run pass P on all functions in the current SCC.
Sanjay Patelc6012542015-03-10 03:26:39 +0000144 for (CallGraphNode *CGN : CurSCC) {
145 if (Function *F = CGN->getFunction()) {
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000146 dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
Juergen Ributzka34390c72014-05-16 02:33:15 +0000147 {
148 TimeRegion PassTimer(getPassTimer(FPP));
149 Changed |= FPP->runOnFunction(*F);
150 }
151 F->getContext().yield();
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000152 }
153 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000154
Chris Lattnera9262bb2009-08-31 17:08:30 +0000155 // The function pass(es) modified the IR, they may have clobbered the
Chris Lattnereedcd842009-08-31 07:23:46 +0000156 // callgraph.
157 if (Changed && CallGraphUpToDate) {
David Greenef8ed9912009-12-23 20:10:59 +0000158 DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
Chris Lattnereedcd842009-08-31 07:23:46 +0000159 << P->getPassName() << '\n');
160 CallGraphUpToDate = false;
161 }
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000162 return Changed;
163}
164
Chris Lattnere33167a2009-09-01 18:32:03 +0000165
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000166/// Scan the functions in the specified CFG and resync the
Chris Lattnere33167a2009-09-01 18:32:03 +0000167/// callgraph with the call sites found in it. This is used after
168/// FunctionPasses have potentially munged the callgraph, and can be used after
169/// CallGraphSCC passes to verify that they correctly updated the callgraph.
170///
Chris Lattner6fbe7042010-04-21 00:47:40 +0000171/// This function returns true if it devirtualized an existing function call,
172/// meaning it turned an indirect call into a direct call. This happens when
173/// a function pass like GVN optimizes away stuff feeding the indirect call.
174/// This never happens in checking mode.
175///
Mehdi Aminic137c282016-08-08 18:51:05 +0000176bool CGPassManager::RefreshCallGraph(const CallGraphSCC &CurSCC, CallGraph &CG,
177 bool CheckingMode) {
Chris Lattner063d0652009-09-01 06:31:31 +0000178 DenseMap<Value*, CallGraphNode*> CallSites;
Chris Lattnereedcd842009-08-31 07:23:46 +0000179
David Greenef8ed9912009-12-23 20:10:59 +0000180 DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
Chris Lattnereedcd842009-08-31 07:23:46 +0000181 << " nodes:\n";
Sanjay Patelc6012542015-03-10 03:26:39 +0000182 for (CallGraphNode *CGN : CurSCC)
183 CGN->dump();
Chris Lattnereedcd842009-08-31 07:23:46 +0000184 );
185
186 bool MadeChange = false;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000187 bool DevirtualizedCall = false;
Chris Lattnereedcd842009-08-31 07:23:46 +0000188
189 // Scan all functions in the SCC.
Chris Lattner4422d312010-04-16 22:42:17 +0000190 unsigned FunctionNo = 0;
191 for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
192 SCCIdx != E; ++SCCIdx, ++FunctionNo) {
193 CallGraphNode *CGN = *SCCIdx;
Chris Lattnereedcd842009-08-31 07:23:46 +0000194 Function *F = CGN->getFunction();
Craig Topper353eda42014-04-24 06:44:33 +0000195 if (!F || F->isDeclaration()) continue;
Chris Lattnereedcd842009-08-31 07:23:46 +0000196
197 // Walk the function body looking for call sites. Sync up the call sites in
198 // CGN with those actually in the function.
Chris Lattner532112b2010-05-01 06:38:43 +0000199
200 // Keep track of the number of direct and indirect calls that were
201 // invalidated and removed.
202 unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000203
Chris Lattnereedcd842009-08-31 07:23:46 +0000204 // Get the set of call sites currently in the function.
Duncan Sands5632d962009-09-02 03:48:41 +0000205 for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
Chris Lattner063d0652009-09-01 06:31:31 +0000206 // If this call site is null, then the function pass deleted the call
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000207 // entirely and the WeakVH nulled it out.
Craig Topper353eda42014-04-24 06:44:33 +0000208 if (!I->first ||
Chris Lattner063d0652009-09-01 06:31:31 +0000209 // If we've already seen this call site, then the FunctionPass RAUW'd
210 // one call with another, which resulted in two "uses" in the edge
211 // list of the same call.
212 CallSites.count(I->first) ||
213
Chad Rosier7a20ed72015-04-14 15:52:57 +0000214 // If the call edge is not from a call or invoke, or it is a
215 // instrinsic call, then the function pass RAUW'd a call with
216 // another value. This can happen when constant folding happens
217 // of well known functions etc.
218 !CallSite(I->first) ||
Sanjoy Dasc65d43e2015-06-18 19:28:26 +0000219 (CallSite(I->first).getCalledFunction() &&
220 CallSite(I->first).getCalledFunction()->isIntrinsic() &&
221 Intrinsic::isLeaf(
222 CallSite(I->first).getCalledFunction()->getIntrinsicID()))) {
Chris Lattnere33167a2009-09-01 18:32:03 +0000223 assert(!CheckingMode &&
224 "CallGraphSCCPass did not update the CallGraph correctly!");
225
Chris Lattner532112b2010-05-01 06:38:43 +0000226 // If this was an indirect call site, count it.
Craig Topper353eda42014-04-24 06:44:33 +0000227 if (!I->second->getFunction())
Chris Lattner532112b2010-05-01 06:38:43 +0000228 ++NumIndirectRemoved;
229 else
230 ++NumDirectRemoved;
231
Chris Lattner65fb5972009-09-02 04:39:04 +0000232 // Just remove the edge from the set of callees, keep track of whether
233 // I points to the last element of the vector.
234 bool WasLast = I + 1 == E;
Chris Lattner063d0652009-09-01 06:31:31 +0000235 CGN->removeCallEdge(I);
Chris Lattner8f232762009-09-02 04:34:06 +0000236
Chris Lattner65fb5972009-09-02 04:39:04 +0000237 // If I pointed to the last element of the vector, we have to bail out:
238 // iterator checking rejects comparisons of the resultant pointer with
239 // end.
240 if (WasLast)
241 break;
Chris Lattner063d0652009-09-01 06:31:31 +0000242 E = CGN->end();
Chris Lattner063d0652009-09-01 06:31:31 +0000243 continue;
244 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000245
Chris Lattner063d0652009-09-01 06:31:31 +0000246 assert(!CallSites.count(I->first) &&
Chris Lattnereedcd842009-08-31 07:23:46 +0000247 "Call site occurs in node multiple times");
Sanjay Patel4c219fd2014-11-12 18:25:47 +0000248
249 CallSite CS(I->first);
250 if (CS) {
251 Function *Callee = CS.getCalledFunction();
252 // Ignore intrinsics because they're not really function calls.
253 if (!Callee || !(Callee->isIntrinsic()))
254 CallSites.insert(std::make_pair(I->first, I->second));
255 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000256 ++I;
Chris Lattnereedcd842009-08-31 07:23:46 +0000257 }
Chris Lattner3f7b3d12009-09-01 18:13:40 +0000258
Chris Lattnereedcd842009-08-31 07:23:46 +0000259 // Loop over all of the instructions in the function, getting the callsites.
Chris Lattner532112b2010-05-01 06:38:43 +0000260 // Keep track of the number of direct/indirect calls added.
261 unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
Benjamin Krameraa209152016-06-26 17:27:42 +0000262
263 for (BasicBlock &BB : *F)
264 for (Instruction &I : BB) {
265 CallSite CS(&I);
Nuno Lopes674acc12012-06-29 17:49:32 +0000266 if (!CS) continue;
267 Function *Callee = CS.getCalledFunction();
268 if (Callee && Callee->isIntrinsic()) continue;
Chris Lattnereedcd842009-08-31 07:23:46 +0000269
270 // If this call site already existed in the callgraph, just verify it
271 // matches up to expectations and remove it from CallSites.
Chris Lattner063d0652009-09-01 06:31:31 +0000272 DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
Chris Lattnereedcd842009-08-31 07:23:46 +0000273 CallSites.find(CS.getInstruction());
274 if (ExistingIt != CallSites.end()) {
275 CallGraphNode *ExistingNode = ExistingIt->second;
276
277 // Remove from CallSites since we have now seen it.
278 CallSites.erase(ExistingIt);
279
280 // Verify that the callee is right.
281 if (ExistingNode->getFunction() == CS.getCalledFunction())
282 continue;
283
Chris Lattnere33167a2009-09-01 18:32:03 +0000284 // If we are in checking mode, we are not allowed to actually mutate
285 // the callgraph. If this is a case where we can infer that the
286 // callgraph is less precise than it could be (e.g. an indirect call
287 // site could be turned direct), don't reject it in checking mode, and
288 // don't tweak it to be more precise.
289 if (CheckingMode && CS.getCalledFunction() &&
Craig Topper353eda42014-04-24 06:44:33 +0000290 ExistingNode->getFunction() == nullptr)
Chris Lattnere33167a2009-09-01 18:32:03 +0000291 continue;
292
293 assert(!CheckingMode &&
294 "CallGraphSCCPass did not update the CallGraph correctly!");
295
Chris Lattnereedcd842009-08-31 07:23:46 +0000296 // If not, we either went from a direct call to indirect, indirect to
297 // direct, or direct to different direct.
298 CallGraphNode *CalleeNode;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000299 if (Function *Callee = CS.getCalledFunction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000300 CalleeNode = CG.getOrInsertFunction(Callee);
Chris Lattner6fbe7042010-04-21 00:47:40 +0000301 // Keep track of whether we turned an indirect call into a direct
302 // one.
Craig Topper353eda42014-04-24 06:44:33 +0000303 if (!ExistingNode->getFunction()) {
Chris Lattner6fbe7042010-04-21 00:47:40 +0000304 DevirtualizedCall = true;
305 DEBUG(dbgs() << " CGSCCPASSMGR: Devirtualized call to '"
306 << Callee->getName() << "'\n");
307 }
308 } else {
Chris Lattnereedcd842009-08-31 07:23:46 +0000309 CalleeNode = CG.getCallsExternalNode();
Chris Lattner6fbe7042010-04-21 00:47:40 +0000310 }
Chris Lattner339c82d2009-09-01 20:33:43 +0000311
312 // Update the edge target in CGN.
Chris Lattner055cf262010-04-22 20:42:33 +0000313 CGN->replaceCallEdge(CS, CS, CalleeNode);
Chris Lattnereedcd842009-08-31 07:23:46 +0000314 MadeChange = true;
315 continue;
316 }
317
Chris Lattnere33167a2009-09-01 18:32:03 +0000318 assert(!CheckingMode &&
319 "CallGraphSCCPass did not update the CallGraph correctly!");
320
Chris Lattner532112b2010-05-01 06:38:43 +0000321 // If the call site didn't exist in the CGN yet, add it.
Chris Lattnereedcd842009-08-31 07:23:46 +0000322 CallGraphNode *CalleeNode;
Chris Lattner532112b2010-05-01 06:38:43 +0000323 if (Function *Callee = CS.getCalledFunction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000324 CalleeNode = CG.getOrInsertFunction(Callee);
Chris Lattner532112b2010-05-01 06:38:43 +0000325 ++NumDirectAdded;
326 } else {
Chris Lattnereedcd842009-08-31 07:23:46 +0000327 CalleeNode = CG.getCallsExternalNode();
Chris Lattner532112b2010-05-01 06:38:43 +0000328 ++NumIndirectAdded;
329 }
Chris Lattnereedcd842009-08-31 07:23:46 +0000330
331 CGN->addCalledFunction(CS, CalleeNode);
332 MadeChange = true;
333 }
334
Chris Lattner532112b2010-05-01 06:38:43 +0000335 // We scanned the old callgraph node, removing invalidated call sites and
336 // then added back newly found call sites. One thing that can happen is
337 // that an old indirect call site was deleted and replaced with a new direct
338 // call. In this case, we have devirtualized a call, and CGSCCPM would like
339 // to iteratively optimize the new code. Unfortunately, we don't really
340 // have a great way to detect when this happens. As an approximation, we
341 // just look at whether the number of indirect calls is reduced and the
342 // number of direct calls is increased. There are tons of ways to fool this
343 // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
344 // direct call) but this is close enough.
345 if (NumIndirectRemoved > NumIndirectAdded &&
346 NumDirectRemoved < NumDirectAdded)
347 DevirtualizedCall = true;
348
Chris Lattnereedcd842009-08-31 07:23:46 +0000349 // After scanning this function, if we still have entries in callsites, then
Chris Lattner063d0652009-09-01 06:31:31 +0000350 // they are dangling pointers. WeakVH should save us for this, so abort if
351 // this happens.
352 assert(CallSites.empty() && "Dangling pointers found in call sites map");
Chris Lattnereedcd842009-08-31 07:23:46 +0000353
Chris Lattner063d0652009-09-01 06:31:31 +0000354 // Periodically do an explicit clear to remove tombstones when processing
355 // large scc's.
Chris Lattner4422d312010-04-16 22:42:17 +0000356 if ((FunctionNo & 15) == 15)
Chris Lattner063d0652009-09-01 06:31:31 +0000357 CallSites.clear();
Chris Lattnereedcd842009-08-31 07:23:46 +0000358 }
359
360 DEBUG(if (MadeChange) {
David Greenef8ed9912009-12-23 20:10:59 +0000361 dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
Sanjay Patelc6012542015-03-10 03:26:39 +0000362 for (CallGraphNode *CGN : CurSCC)
363 CGN->dump();
Chris Lattner532112b2010-05-01 06:38:43 +0000364 if (DevirtualizedCall)
365 dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
366
Chris Lattnereedcd842009-08-31 07:23:46 +0000367 } else {
David Greenef8ed9912009-12-23 20:10:59 +0000368 dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
Chris Lattnereedcd842009-08-31 07:23:46 +0000369 }
370 );
Duncan Sandsa41634e2011-08-12 14:54:45 +0000371 (void)MadeChange;
Chris Lattner6fbe7042010-04-21 00:47:40 +0000372
373 return DevirtualizedCall;
374}
375
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000376/// Execute the body of the entire pass manager on the specified SCC.
377/// This keeps track of whether a function pass devirtualizes
Chris Lattner6fbe7042010-04-21 00:47:40 +0000378/// any calls and returns it in DevirtualizedCall.
379bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
380 bool &DevirtualizedCall) {
381 bool Changed = false;
382
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000383 // Keep track of whether the callgraph is known to be up-to-date or not.
384 // The CGSSC pass manager runs two types of passes:
Chris Lattner6fbe7042010-04-21 00:47:40 +0000385 // CallGraphSCC Passes and other random function passes. Because other
386 // random function passes are not CallGraph aware, they may clobber the
387 // call graph by introducing new calls or deleting other ones. This flag
388 // is set to false when we run a function pass so that we know to clean up
389 // the callgraph when we need to run a CGSCCPass again.
390 bool CallGraphUpToDate = true;
391
392 // Run all passes on current SCC.
393 for (unsigned PassNo = 0, e = getNumContainedPasses();
394 PassNo != e; ++PassNo) {
395 Pass *P = getContainedPass(PassNo);
396
397 // If we're in -debug-pass=Executions mode, construct the SCC node list,
398 // otherwise avoid constructing this string as it is expensive.
399 if (isPassDebuggingExecutionsOrMore()) {
400 std::string Functions;
401 #ifndef NDEBUG
402 raw_string_ostream OS(Functions);
403 for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
404 I != E; ++I) {
405 if (I != CurSCC.begin()) OS << ", ";
406 (*I)->print(OS);
407 }
408 OS.flush();
409 #endif
410 dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
411 }
412 dumpRequiredSet(P);
413
414 initializeAnalysisImpl(P);
415
416 // Actually run this pass on the current SCC.
417 Changed |= RunPassOnSCC(P, CurSCC, CG,
418 CallGraphUpToDate, DevirtualizedCall);
419
420 if (Changed)
421 dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
422 dumpPreservedSet(P);
423
424 verifyPreservedAnalysis(P);
425 removeNotPreservedAnalysis(P);
426 recordAvailableAnalysis(P);
427 removeDeadPasses(P, "", ON_CG_MSG);
428 }
429
430 // If the callgraph was left out of date (because the last pass run was a
431 // functionpass), refresh it before we move on to the next SCC.
432 if (!CallGraphUpToDate)
433 DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
434 return Changed;
Chris Lattnereedcd842009-08-31 07:23:46 +0000435}
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000436
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000437/// Execute all of the passes scheduled for execution. Keep track of
Devang Patel48537a02007-01-17 21:45:01 +0000438/// whether any of the passes modifies the module, and if so, return true.
439bool CGPassManager::runOnModule(Module &M) {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000440 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
Bill Wendling5f14a012009-02-11 18:19:24 +0000441 bool Changed = doInitialization(CG);
Chris Lattner6fbe7042010-04-21 00:47:40 +0000442
Chris Lattner7e4fbdd2009-08-31 06:01:21 +0000443 // Walk the callgraph in bottom-up SCC order.
Chris Lattner5518b812010-04-16 22:59:24 +0000444 scc_iterator<CallGraph*> CGI = scc_begin(&CG);
445
Andrew Kayloraa641a52016-04-22 22:06:11 +0000446 CallGraphSCC CurSCC(CG, &CGI);
Chris Lattner5518b812010-04-16 22:59:24 +0000447 while (!CGI.isAtEnd()) {
Chris Lattner305b1152009-08-31 00:19:58 +0000448 // Copy the current SCC and increment past it so that the pass can hack
449 // on the SCC if it wants to without invalidating our iterator.
Duncan P. N. Exon Smithd2b2fac2014-04-25 18:24:50 +0000450 const std::vector<CallGraphNode *> &NodeVec = *CGI;
David Majnemer1665d862016-08-06 06:21:02 +0000451 CurSCC.initialize(NodeVec);
Chris Lattner305b1152009-08-31 00:19:58 +0000452 ++CGI;
Yaron Kerenafe39832015-07-02 14:17:12 +0000453
Chris Lattner6fbe7042010-04-21 00:47:40 +0000454 // At the top level, we run all the passes in this pass manager on the
455 // functions in this SCC. However, we support iterative compilation in the
456 // case where a function pass devirtualizes a call to a function. For
457 // example, it is very common for a function pass (often GVN or instcombine)
458 // to eliminate the addressing that feeds into a call. With that improved
459 // information, we would like the call to be an inline candidate, infer
460 // mod-ref information etc.
461 //
462 // Because of this, we allow iteration up to a specified iteration count.
463 // This only happens in the case of a devirtualized call, so we only burn
464 // compile time in the case that we're making progress. We also have a hard
465 // iteration count limit in case there is crazy code.
466 unsigned Iteration = 0;
467 bool DevirtualizedCall = false;
468 do {
Chris Lattner055cf262010-04-22 20:42:33 +0000469 DEBUG(if (Iteration)
470 dbgs() << " SCCPASSMGR: Re-visiting SCC, iteration #"
471 << Iteration << '\n');
Chris Lattner6fbe7042010-04-21 00:47:40 +0000472 DevirtualizedCall = false;
473 Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
474 } while (Iteration++ < MaxIterations && DevirtualizedCall);
Chris Lattnereedcd842009-08-31 07:23:46 +0000475
Chris Lattner6fbe7042010-04-21 00:47:40 +0000476 if (DevirtualizedCall)
477 DEBUG(dbgs() << " CGSCCPASSMGR: Stopped iteration after " << Iteration
478 << " times, due to -max-cg-scc-iterations\n");
Chris Lattnereedcd842009-08-31 07:23:46 +0000479
Chris Lattner6fbe7042010-04-21 00:47:40 +0000480 if (Iteration > MaxSCCIterations)
481 MaxSCCIterations = Iteration;
482
Devang Patel48537a02007-01-17 21:45:01 +0000483 }
Bill Wendling5f14a012009-02-11 18:19:24 +0000484 Changed |= doFinalization(CG);
Devang Patel48537a02007-01-17 21:45:01 +0000485 return Changed;
486}
487
Chris Lattner6fbe7042010-04-21 00:47:40 +0000488
Devang Patel48537a02007-01-17 21:45:01 +0000489/// Initialize CG
Bill Wendling5f14a012009-02-11 18:19:24 +0000490bool CGPassManager::doInitialization(CallGraph &CG) {
Devang Patel48537a02007-01-17 21:45:01 +0000491 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000492 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
493 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
494 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
495 "Invalid CGPassManager member");
496 Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000497 } else {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000498 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000499 }
Devang Patel48537a02007-01-17 21:45:01 +0000500 }
501 return Changed;
502}
503
504/// Finalize CG
Bill Wendling5f14a012009-02-11 18:19:24 +0000505bool CGPassManager::doFinalization(CallGraph &CG) {
Devang Patel48537a02007-01-17 21:45:01 +0000506 bool Changed = false;
Chris Lattner0b1c7232010-01-22 05:46:59 +0000507 for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
508 if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
509 assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
510 "Invalid CGPassManager member");
511 Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000512 } else {
Chris Lattner0b1c7232010-01-22 05:46:59 +0000513 Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
Nick Lewyckycdccffe2009-02-13 07:15:53 +0000514 }
Devang Patel48537a02007-01-17 21:45:01 +0000515 }
516 return Changed;
517}
518
Chris Lattner6d1208f2010-04-16 21:43:55 +0000519//===----------------------------------------------------------------------===//
Chris Lattner4422d312010-04-16 22:42:17 +0000520// CallGraphSCC Implementation
521//===----------------------------------------------------------------------===//
522
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000523/// This informs the SCC and the pass manager that the specified
Chris Lattner5518b812010-04-16 22:59:24 +0000524/// Old node has been deleted, and New is to be used in its place.
525void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
526 assert(Old != New && "Should not replace node with self");
527 for (unsigned i = 0; ; ++i) {
528 assert(i != Nodes.size() && "Node not in SCC");
529 if (Nodes[i] != Old) continue;
530 Nodes[i] = New;
531 break;
532 }
Chris Lattnerde023a32010-04-16 23:04:30 +0000533
534 // Update the active scc_iterator so that it doesn't contain dangling
535 // pointers to the old CallGraphNode.
536 scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
537 CGI->ReplaceNode(Old, New);
Chris Lattner5518b812010-04-16 22:59:24 +0000538}
Chris Lattner4422d312010-04-16 22:42:17 +0000539
540
541//===----------------------------------------------------------------------===//
Chris Lattner6d1208f2010-04-16 21:43:55 +0000542// CallGraphSCCPass Implementation
543//===----------------------------------------------------------------------===//
David Greene9b063df2010-04-02 23:17:14 +0000544
Devang Patel020f4f22007-01-23 21:55:17 +0000545/// Assign pass manager to manage this pass.
Devang Patel1f8200b2007-01-23 21:52:35 +0000546void CallGraphSCCPass::assignPassManager(PMStack &PMS,
Anton Korobeynikovfb801512007-04-16 18:10:23 +0000547 PassManagerType PreferredType) {
Devang Patel1f8200b2007-01-23 21:52:35 +0000548 // Find CGPassManager
Duncan Sands60f28bf2007-07-19 09:42:01 +0000549 while (!PMS.empty() &&
550 PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
551 PMS.pop();
Devang Patel1f8200b2007-01-23 21:52:35 +0000552
Chris Lattner9efd4fc2010-01-22 05:37:10 +0000553 assert(!PMS.empty() && "Unable to handle Call Graph Pass");
554 CGPassManager *CGP;
555
556 if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
557 CGP = (CGPassManager*)PMS.top();
558 else {
559 // Create new Call Graph SCC Pass Manager if it does not exist.
560 assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
Devang Patel1f8200b2007-01-23 21:52:35 +0000561 PMDataManager *PMD = PMS.top();
562
563 // [1] Create new Call Graph Pass Manager
Andrew Trick08966212011-08-29 17:07:00 +0000564 CGP = new CGPassManager();
Devang Patel1f8200b2007-01-23 21:52:35 +0000565
566 // [2] Set up new manager's top level manager
567 PMTopLevelManager *TPM = PMD->getTopLevelManager();
568 TPM->addIndirectPassManager(CGP);
569
570 // [3] Assign manager to manage this new manager. This may create
571 // and push new managers into PMS
Chris Lattner9efd4fc2010-01-22 05:37:10 +0000572 Pass *P = CGP;
Devang Patel703de8f2007-06-21 22:29:02 +0000573 TPM->schedulePass(P);
Devang Patel1f8200b2007-01-23 21:52:35 +0000574
575 // [4] Push new manager into PMS
576 PMS.push(CGP);
577 }
578
579 CGP->add(this);
580}
581
Sanjay Pateld45a3f12015-03-10 03:48:14 +0000582/// For this class, we declare that we require and preserve the call graph.
583/// If the derived class implements this method, it should
Chris Lattnerf7e95942003-08-31 01:54:59 +0000584/// always explicitly call the implementation here.
585void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth6378cf52013-11-26 04:19:30 +0000586 AU.addRequired<CallGraphWrapperPass>();
587 AU.addPreserved<CallGraphWrapperPass>();
Chris Lattnerf7e95942003-08-31 01:54:59 +0000588}
Chris Lattner6d1208f2010-04-16 21:43:55 +0000589
590
591//===----------------------------------------------------------------------===//
592// PrintCallGraphPass Implementation
593//===----------------------------------------------------------------------===//
594
595namespace {
596 /// PrintCallGraphPass - Print a Module corresponding to a call graph.
597 ///
598 class PrintCallGraphPass : public CallGraphSCCPass {
599 std::string Banner;
600 raw_ostream &Out; // raw_ostream to print on.
601
602 public:
603 static char ID;
Chris Lattner6d1208f2010-04-16 21:43:55 +0000604 PrintCallGraphPass(const std::string &B, raw_ostream &o)
Owen Andersona7aed182010-08-06 18:33:48 +0000605 : CallGraphSCCPass(ID), Banner(B), Out(o) {}
Craig Toppere9ba7592014-03-05 07:30:04 +0000606
607 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner6d1208f2010-04-16 21:43:55 +0000608 AU.setPreservesAll();
609 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000610
611 bool runOnSCC(CallGraphSCC &SCC) override {
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000612 auto PrintBannerOnce = [&] () {
613 static bool BannerPrinted = false;
614 if (BannerPrinted)
615 return;
616 Out << Banner;
617 BannerPrinted = true;
618 };
Sanjay Patelc6012542015-03-10 03:26:39 +0000619 for (CallGraphNode *CGN : SCC) {
Weiming Zhao0f1762c2016-01-06 22:55:03 +0000620 if (CGN->getFunction()) {
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000621 if (isFunctionInPrintList(CGN->getFunction()->getName())) {
622 PrintBannerOnce();
Weiming Zhao0f1762c2016-01-06 22:55:03 +0000623 CGN->getFunction()->print(Out);
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000624 }
625 } else if (llvm::isFunctionInPrintList("*")) {
626 PrintBannerOnce();
Richard Trieuf2a79522014-07-03 02:11:49 +0000627 Out << "\nPrinting <null> Function\n";
Mehdi Amini062b3fe2017-01-18 21:37:11 +0000628 }
Richard Trieua23043c2014-06-09 22:53:16 +0000629 }
Chris Lattner6d1208f2010-04-16 21:43:55 +0000630 return false;
631 }
632 };
633
634} // end anonymous namespace.
635
636char PrintCallGraphPass::ID = 0;
637
638Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &O,
639 const std::string &Banner) const {
640 return new PrintCallGraphPass(Banner, O);
641}
642
Andrew Kayloraa641a52016-04-22 22:06:11 +0000643bool CallGraphSCCPass::skipSCC(CallGraphSCC &SCC) const {
644 return !SCC.getCallGraph().getModule()
645 .getContext()
646 .getOptBisect()
647 .shouldRunPass(this, SCC);
648}
Mehdi Aminibbacddf2016-06-10 16:19:46 +0000649
650char DummyCGSCCPass::ID = 0;
651INITIALIZE_PASS(DummyCGSCCPass, "DummyCGSCCPass", "DummyCGSCCPass", false,
652 false)