1//===- CallGraphSCCPass.cpp - Pass that operates BU on call graph ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
18#define DEBUG_TYPE "cgscc-passmgr"
19#include "llvm/CallGraphSCCPass.h"
20#include "llvm/IntrinsicInst.h"
21#include "llvm/Function.h"
22#include "llvm/PassManagers.h"
23#include "llvm/Analysis/CallGraph.h"
24#include "llvm/ADT/SCCIterator.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/Timer.h"
29#include "llvm/Support/raw_ostream.h"
30using namespace llvm;
31
32static cl::opt<unsigned>
33MaxIterations("max-cg-scc-iterations", cl::ReallyHidden, cl::init(4));
34
35STATISTIC(MaxSCCIterations, "Maximum CGSCCPassMgr iterations on one SCC");
36
37//===----------------------------------------------------------------------===//
38// CGPassManager
39//
40/// CGPassManager manages FPPassManagers and CallGraphSCCPasses.
41
42namespace {
43
44class CGPassManager : public ModulePass, public PMDataManager {
45public:
46  static char ID;
47  explicit CGPassManager()
48    : ModulePass(ID), PMDataManager() { }
49
50  /// run - Execute all of the passes scheduled for execution.  Keep track of
51  /// whether any of the passes modifies the module, and if so, return true.
52  bool runOnModule(Module &M);
53
54  bool doInitialization(CallGraph &CG);
55  bool doFinalization(CallGraph &CG);
56
57  /// Pass Manager itself does not invalidate any analysis info.
58  void getAnalysisUsage(AnalysisUsage &Info) const {
59    // CGPassManager walks SCC and it needs CallGraph.
60    Info.addRequired<CallGraph>();
61    Info.setPreservesAll();
62  }
63
64  virtual const char *getPassName() const {
65    return "CallGraph Pass Manager";
66  }
67
68  virtual PMDataManager *getAsPMDataManager() { return this; }
69  virtual Pass *getAsPass() { return this; }
70
71  // Print passes managed by this manager
72  void dumpPassStructure(unsigned Offset) {
73    errs().indent(Offset*2) << "Call Graph SCC Pass Manager\n";
74    for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
75      Pass *P = getContainedPass(Index);
76      P->dumpPassStructure(Offset + 1);
77      dumpLastUses(P, Offset+1);
78    }
79  }
80
81  Pass *getContainedPass(unsigned N) {
82    assert(N < PassVector.size() && "Pass number out of range!");
83    return static_cast<Pass *>(PassVector[N]);
84  }
85
86  virtual PassManagerType getPassManagerType() const {
87    return PMT_CallGraphPassManager;
88  }
89
90private:
91  bool RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
92                         bool &DevirtualizedCall);
93
94  bool RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
95                    CallGraph &CG, bool &CallGraphUpToDate,
96                    bool &DevirtualizedCall);
97  bool RefreshCallGraph(CallGraphSCC &CurSCC, CallGraph &CG,
98                        bool IsCheckingMode);
99};
100
101} // end anonymous namespace.
102
103char CGPassManager::ID = 0;
104
105
106bool CGPassManager::RunPassOnSCC(Pass *P, CallGraphSCC &CurSCC,
107                                 CallGraph &CG, bool &CallGraphUpToDate,
108                                 bool &DevirtualizedCall) {
109  bool Changed = false;
110  PMDataManager *PM = P->getAsPMDataManager();
111
112  if (PM == 0) {
113    CallGraphSCCPass *CGSP = (CallGraphSCCPass*)P;
114    if (!CallGraphUpToDate) {
115      DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
116      CallGraphUpToDate = true;
117    }
118
119    {
120      TimeRegion PassTimer(getPassTimer(CGSP));
121      Changed = CGSP->runOnSCC(CurSCC);
122    }
123
124    // After the CGSCCPass is done, when assertions are enabled, use
125    // RefreshCallGraph to verify that the callgraph was correctly updated.
126#ifndef NDEBUG
127    if (Changed)
128      RefreshCallGraph(CurSCC, CG, true);
129#endif
130
131    return Changed;
132  }
133
134
135  assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
136         "Invalid CGPassManager member");
137  FPPassManager *FPP = (FPPassManager*)P;
138
139  // Run pass P on all functions in the current SCC.
140  for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
141       I != E; ++I) {
142    if (Function *F = (*I)->getFunction()) {
143      dumpPassInfo(P, EXECUTION_MSG, ON_FUNCTION_MSG, F->getName());
144      TimeRegion PassTimer(getPassTimer(FPP));
145      Changed |= FPP->runOnFunction(*F);
146    }
147  }
148
149  // The function pass(es) modified the IR, they may have clobbered the
150  // callgraph.
151  if (Changed && CallGraphUpToDate) {
152    DEBUG(dbgs() << "CGSCCPASSMGR: Pass Dirtied SCC: "
153                 << P->getPassName() << '\n');
154    CallGraphUpToDate = false;
155  }
156  return Changed;
157}
158
159
160/// RefreshCallGraph - Scan the functions in the specified CFG and resync the
161/// callgraph with the call sites found in it.  This is used after
162/// FunctionPasses have potentially munged the callgraph, and can be used after
163/// CallGraphSCC passes to verify that they correctly updated the callgraph.
164///
165/// This function returns true if it devirtualized an existing function call,
166/// meaning it turned an indirect call into a direct call.  This happens when
167/// a function pass like GVN optimizes away stuff feeding the indirect call.
168/// This never happens in checking mode.
169///
170bool CGPassManager::RefreshCallGraph(CallGraphSCC &CurSCC,
171                                     CallGraph &CG, bool CheckingMode) {
172  DenseMap<Value*, CallGraphNode*> CallSites;
173
174  DEBUG(dbgs() << "CGSCCPASSMGR: Refreshing SCC with " << CurSCC.size()
175               << " nodes:\n";
176        for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
177             I != E; ++I)
178          (*I)->dump();
179        );
180
181  bool MadeChange = false;
182  bool DevirtualizedCall = false;
183
184  // Scan all functions in the SCC.
185  unsigned FunctionNo = 0;
186  for (CallGraphSCC::iterator SCCIdx = CurSCC.begin(), E = CurSCC.end();
187       SCCIdx != E; ++SCCIdx, ++FunctionNo) {
188    CallGraphNode *CGN = *SCCIdx;
189    Function *F = CGN->getFunction();
190    if (F == 0 || F->isDeclaration()) continue;
191
192    // Walk the function body looking for call sites.  Sync up the call sites in
193    // CGN with those actually in the function.
194
195    // Keep track of the number of direct and indirect calls that were
196    // invalidated and removed.
197    unsigned NumDirectRemoved = 0, NumIndirectRemoved = 0;
198
199    // Get the set of call sites currently in the function.
200    for (CallGraphNode::iterator I = CGN->begin(), E = CGN->end(); I != E; ) {
201      // If this call site is null, then the function pass deleted the call
202      // entirely and the WeakVH nulled it out.
203      if (I->first == 0 ||
204          // If we've already seen this call site, then the FunctionPass RAUW'd
205          // one call with another, which resulted in two "uses" in the edge
206          // list of the same call.
207          CallSites.count(I->first) ||
208
209          // If the call edge is not from a call or invoke, then the function
210          // pass RAUW'd a call with another value.  This can happen when
211          // constant folding happens of well known functions etc.
212          !CallSite(I->first)) {
213        assert(!CheckingMode &&
214               "CallGraphSCCPass did not update the CallGraph correctly!");
215
216        // If this was an indirect call site, count it.
217        if (I->second->getFunction() == 0)
218          ++NumIndirectRemoved;
219        else
220          ++NumDirectRemoved;
221
222        // Just remove the edge from the set of callees, keep track of whether
223        // I points to the last element of the vector.
224        bool WasLast = I + 1 == E;
225        CGN->removeCallEdge(I);
226
227        // If I pointed to the last element of the vector, we have to bail out:
228        // iterator checking rejects comparisons of the resultant pointer with
229        // end.
230        if (WasLast)
231          break;
232        E = CGN->end();
233        continue;
234      }
235
236      assert(!CallSites.count(I->first) &&
237             "Call site occurs in node multiple times");
238      CallSites.insert(std::make_pair(I->first, I->second));
239      ++I;
240    }
241
242    // Loop over all of the instructions in the function, getting the callsites.
243    // Keep track of the number of direct/indirect calls added.
244    unsigned NumDirectAdded = 0, NumIndirectAdded = 0;
245
246    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
247      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
248        CallSite CS(cast<Value>(I));
249        if (!CS) continue;
250        Function *Callee = CS.getCalledFunction();
251        if (Callee && Callee->isIntrinsic()) continue;
252
253        // If this call site already existed in the callgraph, just verify it
254        // matches up to expectations and remove it from CallSites.
255        DenseMap<Value*, CallGraphNode*>::iterator ExistingIt =
256          CallSites.find(CS.getInstruction());
257        if (ExistingIt != CallSites.end()) {
258          CallGraphNode *ExistingNode = ExistingIt->second;
259
260          // Remove from CallSites since we have now seen it.
261          CallSites.erase(ExistingIt);
262
263          // Verify that the callee is right.
264          if (ExistingNode->getFunction() == CS.getCalledFunction())
265            continue;
266
267          // If we are in checking mode, we are not allowed to actually mutate
268          // the callgraph.  If this is a case where we can infer that the
269          // callgraph is less precise than it could be (e.g. an indirect call
270          // site could be turned direct), don't reject it in checking mode, and
271          // don't tweak it to be more precise.
272          if (CheckingMode && CS.getCalledFunction() &&
273              ExistingNode->getFunction() == 0)
274            continue;
275
276          assert(!CheckingMode &&
277                 "CallGraphSCCPass did not update the CallGraph correctly!");
278
279          // If not, we either went from a direct call to indirect, indirect to
280          // direct, or direct to different direct.
281          CallGraphNode *CalleeNode;
282          if (Function *Callee = CS.getCalledFunction()) {
283            CalleeNode = CG.getOrInsertFunction(Callee);
284            // Keep track of whether we turned an indirect call into a direct
285            // one.
286            if (ExistingNode->getFunction() == 0) {
287              DevirtualizedCall = true;
288              DEBUG(dbgs() << "  CGSCCPASSMGR: Devirtualized call to '"
289                           << Callee->getName() << "'\n");
290            }
291          } else {
292            CalleeNode = CG.getCallsExternalNode();
293          }
294
295          // Update the edge target in CGN.
296          CGN->replaceCallEdge(CS, CS, CalleeNode);
297          MadeChange = true;
298          continue;
299        }
300
301        assert(!CheckingMode &&
302               "CallGraphSCCPass did not update the CallGraph correctly!");
303
304        // If the call site didn't exist in the CGN yet, add it.
305        CallGraphNode *CalleeNode;
306        if (Function *Callee = CS.getCalledFunction()) {
307          CalleeNode = CG.getOrInsertFunction(Callee);
308          ++NumDirectAdded;
309        } else {
310          CalleeNode = CG.getCallsExternalNode();
311          ++NumIndirectAdded;
312        }
313
314        CGN->addCalledFunction(CS, CalleeNode);
315        MadeChange = true;
316      }
317
318    // We scanned the old callgraph node, removing invalidated call sites and
319    // then added back newly found call sites.  One thing that can happen is
320    // that an old indirect call site was deleted and replaced with a new direct
321    // call.  In this case, we have devirtualized a call, and CGSCCPM would like
322    // to iteratively optimize the new code.  Unfortunately, we don't really
323    // have a great way to detect when this happens.  As an approximation, we
324    // just look at whether the number of indirect calls is reduced and the
325    // number of direct calls is increased.  There are tons of ways to fool this
326    // (e.g. DCE'ing an indirect call and duplicating an unrelated block with a
327    // direct call) but this is close enough.
328    if (NumIndirectRemoved > NumIndirectAdded &&
329        NumDirectRemoved < NumDirectAdded)
330      DevirtualizedCall = true;
331
332    // After scanning this function, if we still have entries in callsites, then
333    // they are dangling pointers.  WeakVH should save us for this, so abort if
334    // this happens.
335    assert(CallSites.empty() && "Dangling pointers found in call sites map");
336
337    // Periodically do an explicit clear to remove tombstones when processing
338    // large scc's.
339    if ((FunctionNo & 15) == 15)
340      CallSites.clear();
341  }
342
343  DEBUG(if (MadeChange) {
344          dbgs() << "CGSCCPASSMGR: Refreshed SCC is now:\n";
345          for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
346            I != E; ++I)
347              (*I)->dump();
348          if (DevirtualizedCall)
349            dbgs() << "CGSCCPASSMGR: Refresh devirtualized a call!\n";
350
351         } else {
352           dbgs() << "CGSCCPASSMGR: SCC Refresh didn't change call graph.\n";
353         }
354        );
355  (void)MadeChange;
356
357  return DevirtualizedCall;
358}
359
360/// RunAllPassesOnSCC -  Execute the body of the entire pass manager on the
361/// specified SCC.  This keeps track of whether a function pass devirtualizes
362/// any calls and returns it in DevirtualizedCall.
363bool CGPassManager::RunAllPassesOnSCC(CallGraphSCC &CurSCC, CallGraph &CG,
364                                      bool &DevirtualizedCall) {
365  bool Changed = false;
366
367  // CallGraphUpToDate - Keep track of whether the callgraph is known to be
368  // up-to-date or not.  The CGSSC pass manager runs two types of passes:
369  // CallGraphSCC Passes and other random function passes.  Because other
370  // random function passes are not CallGraph aware, they may clobber the
371  // call graph by introducing new calls or deleting other ones.  This flag
372  // is set to false when we run a function pass so that we know to clean up
373  // the callgraph when we need to run a CGSCCPass again.
374  bool CallGraphUpToDate = true;
375
376  // Run all passes on current SCC.
377  for (unsigned PassNo = 0, e = getNumContainedPasses();
378       PassNo != e; ++PassNo) {
379    Pass *P = getContainedPass(PassNo);
380
381    // If we're in -debug-pass=Executions mode, construct the SCC node list,
382    // otherwise avoid constructing this string as it is expensive.
383    if (isPassDebuggingExecutionsOrMore()) {
384      std::string Functions;
385  #ifndef NDEBUG
386      raw_string_ostream OS(Functions);
387      for (CallGraphSCC::iterator I = CurSCC.begin(), E = CurSCC.end();
388           I != E; ++I) {
389        if (I != CurSCC.begin()) OS << ", ";
390        (*I)->print(OS);
391      }
392      OS.flush();
393  #endif
394      dumpPassInfo(P, EXECUTION_MSG, ON_CG_MSG, Functions);
395    }
396    dumpRequiredSet(P);
397
398    initializeAnalysisImpl(P);
399
400    // Actually run this pass on the current SCC.
401    Changed |= RunPassOnSCC(P, CurSCC, CG,
402                            CallGraphUpToDate, DevirtualizedCall);
403
404    if (Changed)
405      dumpPassInfo(P, MODIFICATION_MSG, ON_CG_MSG, "");
406    dumpPreservedSet(P);
407
408    verifyPreservedAnalysis(P);
409    removeNotPreservedAnalysis(P);
410    recordAvailableAnalysis(P);
411    removeDeadPasses(P, "", ON_CG_MSG);
412  }
413
414  // If the callgraph was left out of date (because the last pass run was a
415  // functionpass), refresh it before we move on to the next SCC.
416  if (!CallGraphUpToDate)
417    DevirtualizedCall |= RefreshCallGraph(CurSCC, CG, false);
418  return Changed;
419}
420
421/// run - Execute all of the passes scheduled for execution.  Keep track of
422/// whether any of the passes modifies the module, and if so, return true.
423bool CGPassManager::runOnModule(Module &M) {
424  CallGraph &CG = getAnalysis<CallGraph>();
425  bool Changed = doInitialization(CG);
426
427  // Walk the callgraph in bottom-up SCC order.
428  scc_iterator<CallGraph*> CGI = scc_begin(&CG);
429
430  CallGraphSCC CurSCC(&CGI);
431  while (!CGI.isAtEnd()) {
432    // Copy the current SCC and increment past it so that the pass can hack
433    // on the SCC if it wants to without invalidating our iterator.
434    std::vector<CallGraphNode*> &NodeVec = *CGI;
435    CurSCC.initialize(&NodeVec[0], &NodeVec[0]+NodeVec.size());
436    ++CGI;
437
438    // At the top level, we run all the passes in this pass manager on the
439    // functions in this SCC.  However, we support iterative compilation in the
440    // case where a function pass devirtualizes a call to a function.  For
441    // example, it is very common for a function pass (often GVN or instcombine)
442    // to eliminate the addressing that feeds into a call.  With that improved
443    // information, we would like the call to be an inline candidate, infer
444    // mod-ref information etc.
445    //
446    // Because of this, we allow iteration up to a specified iteration count.
447    // This only happens in the case of a devirtualized call, so we only burn
448    // compile time in the case that we're making progress.  We also have a hard
449    // iteration count limit in case there is crazy code.
450    unsigned Iteration = 0;
451    bool DevirtualizedCall = false;
452    do {
453      DEBUG(if (Iteration)
454              dbgs() << "  SCCPASSMGR: Re-visiting SCC, iteration #"
455                     << Iteration << '\n');
456      DevirtualizedCall = false;
457      Changed |= RunAllPassesOnSCC(CurSCC, CG, DevirtualizedCall);
458    } while (Iteration++ < MaxIterations && DevirtualizedCall);
459
460    if (DevirtualizedCall)
461      DEBUG(dbgs() << "  CGSCCPASSMGR: Stopped iteration after " << Iteration
462                   << " times, due to -max-cg-scc-iterations\n");
463
464    if (Iteration > MaxSCCIterations)
465      MaxSCCIterations = Iteration;
466
467  }
468  Changed |= doFinalization(CG);
469  return Changed;
470}
471
472
473/// Initialize CG
474bool CGPassManager::doInitialization(CallGraph &CG) {
475  bool Changed = false;
476  for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
477    if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
478      assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
479             "Invalid CGPassManager member");
480      Changed |= ((FPPassManager*)PM)->doInitialization(CG.getModule());
481    } else {
482      Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doInitialization(CG);
483    }
484  }
485  return Changed;
486}
487
488/// Finalize CG
489bool CGPassManager::doFinalization(CallGraph &CG) {
490  bool Changed = false;
491  for (unsigned i = 0, e = getNumContainedPasses(); i != e; ++i) {
492    if (PMDataManager *PM = getContainedPass(i)->getAsPMDataManager()) {
493      assert(PM->getPassManagerType() == PMT_FunctionPassManager &&
494             "Invalid CGPassManager member");
495      Changed |= ((FPPassManager*)PM)->doFinalization(CG.getModule());
496    } else {
497      Changed |= ((CallGraphSCCPass*)getContainedPass(i))->doFinalization(CG);
498    }
499  }
500  return Changed;
501}
502
503//===----------------------------------------------------------------------===//
504// CallGraphSCC Implementation
505//===----------------------------------------------------------------------===//
506
507/// ReplaceNode - This informs the SCC and the pass manager that the specified
508/// Old node has been deleted, and New is to be used in its place.
509void CallGraphSCC::ReplaceNode(CallGraphNode *Old, CallGraphNode *New) {
510  assert(Old != New && "Should not replace node with self");
511  for (unsigned i = 0; ; ++i) {
512    assert(i != Nodes.size() && "Node not in SCC");
513    if (Nodes[i] != Old) continue;
514    Nodes[i] = New;
515    break;
516  }
517
518  // Update the active scc_iterator so that it doesn't contain dangling
519  // pointers to the old CallGraphNode.
520  scc_iterator<CallGraph*> *CGI = (scc_iterator<CallGraph*>*)Context;
521  CGI->ReplaceNode(Old, New);
522}
523
524
525//===----------------------------------------------------------------------===//
526// CallGraphSCCPass Implementation
527//===----------------------------------------------------------------------===//
528
529/// Assign pass manager to manage this pass.
530void CallGraphSCCPass::assignPassManager(PMStack &PMS,
531                                         PassManagerType PreferredType) {
532  // Find CGPassManager
533  while (!PMS.empty() &&
534         PMS.top()->getPassManagerType() > PMT_CallGraphPassManager)
535    PMS.pop();
536
537  assert(!PMS.empty() && "Unable to handle Call Graph Pass");
538  CGPassManager *CGP;
539
540  if (PMS.top()->getPassManagerType() == PMT_CallGraphPassManager)
541    CGP = (CGPassManager*)PMS.top();
542  else {
543    // Create new Call Graph SCC Pass Manager if it does not exist.
544    assert(!PMS.empty() && "Unable to create Call Graph Pass Manager");
545    PMDataManager *PMD = PMS.top();
546
547    // [1] Create new Call Graph Pass Manager
548    CGP = new CGPassManager();
549
550    // [2] Set up new manager's top level manager
551    PMTopLevelManager *TPM = PMD->getTopLevelManager();
552    TPM->addIndirectPassManager(CGP);
553
554    // [3] Assign manager to manage this new manager. This may create
555    // and push new managers into PMS
556    Pass *P = CGP;
557    TPM->schedulePass(P);
558
559    // [4] Push new manager into PMS
560    PMS.push(CGP);
561  }
562
563  CGP->add(this);
564}
565
566/// getAnalysisUsage - For this class, we declare that we require and preserve
567/// the call graph.  If the derived class implements this method, it should
568/// always explicitly call the implementation here.
569void CallGraphSCCPass::getAnalysisUsage(AnalysisUsage &AU) const {
570  AU.addRequired<CallGraph>();
571  AU.addPreserved<CallGraph>();
572}
573
574
575//===----------------------------------------------------------------------===//
576// PrintCallGraphPass Implementation
577//===----------------------------------------------------------------------===//
578
579namespace {
580  /// PrintCallGraphPass - Print a Module corresponding to a call graph.
581  ///
582  class PrintCallGraphPass : public CallGraphSCCPass {
583    std::string Banner;
584    raw_ostream &Out;       // raw_ostream to print on.
585
586  public:
587    static char ID;
588    PrintCallGraphPass(const std::string &B, raw_ostream &o)
589      : CallGraphSCCPass(ID), Banner(B), Out(o) {}
590
591    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
592      AU.setPreservesAll();
593    }
594
595    bool runOnSCC(CallGraphSCC &SCC) {
596      Out << Banner;
597      for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
598        (*I)->getFunction()->print(Out);
599      return false;
600    }
601  };
602
603} // end anonymous namespace.
604
605char PrintCallGraphPass::ID = 0;
606
607Pass *CallGraphSCCPass::createPrinterPass(raw_ostream &O,
608                                          const std::string &Banner) const {
609  return new PrintCallGraphPass(Banner, O);
610}
611
612