CallGraph.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Analysis/CallGraph.h"
  9. #include "llvm/ADT/SCCIterator.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/Config/llvm-config.h"
  13. #include "llvm/IR/AbstractCallSite.h"
  14. #include "llvm/IR/Function.h"
  15. #include "llvm/IR/IntrinsicInst.h"
  16. #include "llvm/IR/Module.h"
  17. #include "llvm/IR/PassManager.h"
  18. #include "llvm/InitializePasses.h"
  19. #include "llvm/Pass.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/Debug.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include <cassert>
  24. using namespace llvm;
  25. //===----------------------------------------------------------------------===//
  26. // Implementations of the CallGraph class methods.
  27. //
  28. CallGraph::CallGraph(Module &M)
  29. : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
  30. CallsExternalNode(std::make_unique<CallGraphNode>(this, nullptr)) {
  31. // Add every interesting function to the call graph.
  32. for (Function &F : M)
  33. if (!isDbgInfoIntrinsic(F.getIntrinsicID()))
  34. addToCallGraph(&F);
  35. }
  36. CallGraph::CallGraph(CallGraph &&Arg)
  37. : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
  38. ExternalCallingNode(Arg.ExternalCallingNode),
  39. CallsExternalNode(std::move(Arg.CallsExternalNode)) {
  40. Arg.FunctionMap.clear();
  41. Arg.ExternalCallingNode = nullptr;
  42. // Update parent CG for all call graph's nodes.
  43. CallsExternalNode->CG = this;
  44. for (auto &P : FunctionMap)
  45. P.second->CG = this;
  46. }
  47. CallGraph::~CallGraph() {
  48. // CallsExternalNode is not in the function map, delete it explicitly.
  49. if (CallsExternalNode)
  50. CallsExternalNode->allReferencesDropped();
  51. // Reset all node's use counts to zero before deleting them to prevent an
  52. // assertion from firing.
  53. #ifndef NDEBUG
  54. for (auto &I : FunctionMap)
  55. I.second->allReferencesDropped();
  56. #endif
  57. }
  58. bool CallGraph::invalidate(Module &, const PreservedAnalyses &PA,
  59. ModuleAnalysisManager::Invalidator &) {
  60. // Check whether the analysis, all analyses on functions, or the function's
  61. // CFG have been preserved.
  62. auto PAC = PA.getChecker<CallGraphAnalysis>();
  63. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>());
  64. }
  65. void CallGraph::addToCallGraph(Function *F) {
  66. CallGraphNode *Node = getOrInsertFunction(F);
  67. // If this function has external linkage or has its address taken and
  68. // it is not a callback, then anything could call it.
  69. if (!F->hasLocalLinkage() ||
  70. F->hasAddressTaken(nullptr, /*IgnoreCallbackUses=*/true,
  71. /* IgnoreAssumeLikeCalls */ true,
  72. /* IgnoreLLVMUsed */ false))
  73. ExternalCallingNode->addCalledFunction(nullptr, Node);
  74. populateCallGraphNode(Node);
  75. }
  76. void CallGraph::populateCallGraphNode(CallGraphNode *Node) {
  77. Function *F = Node->getFunction();
  78. // If this function is not defined in this translation unit, it could call
  79. // anything.
  80. if (F->isDeclaration() && !F->hasFnAttribute(Attribute::NoCallback))
  81. Node->addCalledFunction(nullptr, CallsExternalNode.get());
  82. // Look for calls by this function.
  83. for (BasicBlock &BB : *F)
  84. for (Instruction &I : BB) {
  85. if (auto *Call = dyn_cast<CallBase>(&I)) {
  86. const Function *Callee = Call->getCalledFunction();
  87. if (!Callee)
  88. Node->addCalledFunction(Call, CallsExternalNode.get());
  89. else if (!isDbgInfoIntrinsic(Callee->getIntrinsicID()))
  90. Node->addCalledFunction(Call, getOrInsertFunction(Callee));
  91. // Add reference to callback functions.
  92. forEachCallbackFunction(*Call, [=](Function *CB) {
  93. Node->addCalledFunction(nullptr, getOrInsertFunction(CB));
  94. });
  95. }
  96. }
  97. }
  98. void CallGraph::print(raw_ostream &OS) const {
  99. // Print in a deterministic order by sorting CallGraphNodes by name. We do
  100. // this here to avoid slowing down the non-printing fast path.
  101. SmallVector<CallGraphNode *, 16> Nodes;
  102. Nodes.reserve(FunctionMap.size());
  103. for (const auto &I : *this)
  104. Nodes.push_back(I.second.get());
  105. llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
  106. if (Function *LF = LHS->getFunction())
  107. if (Function *RF = RHS->getFunction())
  108. return LF->getName() < RF->getName();
  109. return RHS->getFunction() != nullptr;
  110. });
  111. for (CallGraphNode *CN : Nodes)
  112. CN->print(OS);
  113. }
  114. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  115. LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); }
  116. #endif
  117. void CallGraph::ReplaceExternalCallEdge(CallGraphNode *Old,
  118. CallGraphNode *New) {
  119. for (auto &CR : ExternalCallingNode->CalledFunctions)
  120. if (CR.second == Old) {
  121. CR.second->DropRef();
  122. CR.second = New;
  123. CR.second->AddRef();
  124. }
  125. }
  126. // removeFunctionFromModule - Unlink the function from this module, returning
  127. // it. Because this removes the function from the module, the call graph node
  128. // is destroyed. This is only valid if the function does not call any other
  129. // functions (ie, there are no edges in it's CGN). The easiest way to do this
  130. // is to dropAllReferences before calling this.
  131. //
  132. Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
  133. assert(CGN->empty() && "Cannot remove function from call "
  134. "graph if it references other functions!");
  135. Function *F = CGN->getFunction(); // Get the function for the call graph node
  136. FunctionMap.erase(F); // Remove the call graph node from the map
  137. M.getFunctionList().remove(F);
  138. return F;
  139. }
  140. // getOrInsertFunction - This method is identical to calling operator[], but
  141. // it will insert a new CallGraphNode for the specified function if one does
  142. // not already exist.
  143. CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
  144. auto &CGN = FunctionMap[F];
  145. if (CGN)
  146. return CGN.get();
  147. assert((!F || F->getParent() == &M) && "Function not in current module!");
  148. CGN = std::make_unique<CallGraphNode>(this, const_cast<Function *>(F));
  149. return CGN.get();
  150. }
  151. //===----------------------------------------------------------------------===//
  152. // Implementations of the CallGraphNode class methods.
  153. //
  154. void CallGraphNode::print(raw_ostream &OS) const {
  155. if (Function *F = getFunction())
  156. OS << "Call graph node for function: '" << F->getName() << "'";
  157. else
  158. OS << "Call graph node <<null function>>";
  159. OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
  160. for (const auto &I : *this) {
  161. OS << " CS<" << I.first << "> calls ";
  162. if (Function *FI = I.second->getFunction())
  163. OS << "function '" << FI->getName() <<"'\n";
  164. else
  165. OS << "external node\n";
  166. }
  167. OS << '\n';
  168. }
  169. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  170. LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); }
  171. #endif
  172. /// removeCallEdgeFor - This method removes the edge in the node for the
  173. /// specified call site. Note that this method takes linear time, so it
  174. /// should be used sparingly.
  175. void CallGraphNode::removeCallEdgeFor(CallBase &Call) {
  176. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  177. assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
  178. if (I->first && *I->first == &Call) {
  179. I->second->DropRef();
  180. *I = CalledFunctions.back();
  181. CalledFunctions.pop_back();
  182. // Remove all references to callback functions if there are any.
  183. forEachCallbackFunction(Call, [=](Function *CB) {
  184. removeOneAbstractEdgeTo(CG->getOrInsertFunction(CB));
  185. });
  186. return;
  187. }
  188. }
  189. }
  190. // removeAnyCallEdgeTo - This method removes any call edges from this node to
  191. // the specified callee function. This takes more time to execute than
  192. // removeCallEdgeTo, so it should not be used unless necessary.
  193. void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
  194. for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
  195. if (CalledFunctions[i].second == Callee) {
  196. Callee->DropRef();
  197. CalledFunctions[i] = CalledFunctions.back();
  198. CalledFunctions.pop_back();
  199. --i; --e;
  200. }
  201. }
  202. /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
  203. /// from this node to the specified callee function.
  204. void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
  205. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  206. assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
  207. CallRecord &CR = *I;
  208. if (CR.second == Callee && !CR.first) {
  209. Callee->DropRef();
  210. *I = CalledFunctions.back();
  211. CalledFunctions.pop_back();
  212. return;
  213. }
  214. }
  215. }
  216. /// replaceCallEdge - This method replaces the edge in the node for the
  217. /// specified call site with a new one. Note that this method takes linear
  218. /// time, so it should be used sparingly.
  219. void CallGraphNode::replaceCallEdge(CallBase &Call, CallBase &NewCall,
  220. CallGraphNode *NewNode) {
  221. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  222. assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
  223. if (I->first && *I->first == &Call) {
  224. I->second->DropRef();
  225. I->first = &NewCall;
  226. I->second = NewNode;
  227. NewNode->AddRef();
  228. // Refresh callback references. Do not resize CalledFunctions if the
  229. // number of callbacks is the same for new and old call sites.
  230. SmallVector<CallGraphNode *, 4u> OldCBs;
  231. SmallVector<CallGraphNode *, 4u> NewCBs;
  232. forEachCallbackFunction(Call, [this, &OldCBs](Function *CB) {
  233. OldCBs.push_back(CG->getOrInsertFunction(CB));
  234. });
  235. forEachCallbackFunction(NewCall, [this, &NewCBs](Function *CB) {
  236. NewCBs.push_back(CG->getOrInsertFunction(CB));
  237. });
  238. if (OldCBs.size() == NewCBs.size()) {
  239. for (unsigned N = 0; N < OldCBs.size(); ++N) {
  240. CallGraphNode *OldNode = OldCBs[N];
  241. CallGraphNode *NewNode = NewCBs[N];
  242. for (auto J = CalledFunctions.begin();; ++J) {
  243. assert(J != CalledFunctions.end() &&
  244. "Cannot find callsite to update!");
  245. if (!J->first && J->second == OldNode) {
  246. J->second = NewNode;
  247. OldNode->DropRef();
  248. NewNode->AddRef();
  249. break;
  250. }
  251. }
  252. }
  253. } else {
  254. for (auto *CGN : OldCBs)
  255. removeOneAbstractEdgeTo(CGN);
  256. for (auto *CGN : NewCBs)
  257. addCalledFunction(nullptr, CGN);
  258. }
  259. return;
  260. }
  261. }
  262. }
  263. // Provide an explicit template instantiation for the static ID.
  264. AnalysisKey CallGraphAnalysis::Key;
  265. PreservedAnalyses CallGraphPrinterPass::run(Module &M,
  266. ModuleAnalysisManager &AM) {
  267. AM.getResult<CallGraphAnalysis>(M).print(OS);
  268. return PreservedAnalyses::all();
  269. }
  270. PreservedAnalyses CallGraphSCCsPrinterPass::run(Module &M,
  271. ModuleAnalysisManager &AM) {
  272. auto &CG = AM.getResult<CallGraphAnalysis>(M);
  273. unsigned sccNum = 0;
  274. OS << "SCCs for the program in PostOrder:";
  275. for (scc_iterator<CallGraph *> SCCI = scc_begin(&CG); !SCCI.isAtEnd();
  276. ++SCCI) {
  277. const std::vector<CallGraphNode *> &nextSCC = *SCCI;
  278. OS << "\nSCC #" << ++sccNum << ": ";
  279. bool First = true;
  280. for (std::vector<CallGraphNode *>::const_iterator I = nextSCC.begin(),
  281. E = nextSCC.end();
  282. I != E; ++I) {
  283. if (First)
  284. First = false;
  285. else
  286. OS << ", ";
  287. OS << ((*I)->getFunction() ? (*I)->getFunction()->getName()
  288. : "external node");
  289. }
  290. if (nextSCC.size() == 1 && SCCI.hasCycle())
  291. OS << " (Has self-loop).";
  292. }
  293. OS << "\n";
  294. return PreservedAnalyses::all();
  295. }
  296. //===----------------------------------------------------------------------===//
  297. // Out-of-line definitions of CallGraphAnalysis class members.
  298. //
  299. //===----------------------------------------------------------------------===//
  300. // Implementations of the CallGraphWrapperPass class methods.
  301. //
  302. CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
  303. initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
  304. }
  305. CallGraphWrapperPass::~CallGraphWrapperPass() = default;
  306. void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  307. AU.setPreservesAll();
  308. }
  309. bool CallGraphWrapperPass::runOnModule(Module &M) {
  310. // All the real work is done in the constructor for the CallGraph.
  311. G.reset(new CallGraph(M));
  312. return false;
  313. }
  314. INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
  315. false, true)
  316. char CallGraphWrapperPass::ID = 0;
  317. void CallGraphWrapperPass::releaseMemory() { G.reset(); }
  318. void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
  319. if (!G) {
  320. OS << "No call graph has been built!\n";
  321. return;
  322. }
  323. // Just delegate.
  324. G->print(OS);
  325. }
  326. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  327. LLVM_DUMP_METHOD
  328. void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
  329. #endif
  330. namespace {
  331. struct CallGraphPrinterLegacyPass : public ModulePass {
  332. static char ID; // Pass ID, replacement for typeid
  333. CallGraphPrinterLegacyPass() : ModulePass(ID) {
  334. initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
  335. }
  336. void getAnalysisUsage(AnalysisUsage &AU) const override {
  337. AU.setPreservesAll();
  338. AU.addRequiredTransitive<CallGraphWrapperPass>();
  339. }
  340. bool runOnModule(Module &M) override {
  341. getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
  342. return false;
  343. }
  344. };
  345. } // end anonymous namespace
  346. char CallGraphPrinterLegacyPass::ID = 0;
  347. INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
  348. "Print a call graph", true, true)
  349. INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
  350. INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
  351. "Print a call graph", true, true)