CallGraph.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. //===- CallGraph.cpp - Build a Module's 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. #include "llvm/Analysis/CallGraph.h"
  10. #include "llvm/IR/CallSite.h"
  11. #include "llvm/IR/Instructions.h"
  12. #include "llvm/IR/IntrinsicInst.h"
  13. #include "llvm/IR/Module.h"
  14. #include "llvm/Support/Debug.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. #include "dxc/HLSL/HLModule.h" // HLSL Change
  17. using namespace llvm;
  18. //===----------------------------------------------------------------------===//
  19. // Implementations of the CallGraph class methods.
  20. //
  21. CallGraph::CallGraph(Module &M)
  22. : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
  23. CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
  24. // Add every function to the call graph.
  25. for (Function &F : M)
  26. addToCallGraph(&F);
  27. }
  28. CallGraph::CallGraph(CallGraph &&Arg)
  29. : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
  30. ExternalCallingNode(Arg.ExternalCallingNode),
  31. CallsExternalNode(std::move(Arg.CallsExternalNode)) {
  32. Arg.FunctionMap.clear();
  33. Arg.ExternalCallingNode = nullptr;
  34. }
  35. CallGraph::~CallGraph() {
  36. // CallsExternalNode is not in the function map, delete it explicitly.
  37. if (CallsExternalNode)
  38. CallsExternalNode->allReferencesDropped();
  39. // Reset all node's use counts to zero before deleting them to prevent an
  40. // assertion from firing.
  41. #ifndef NDEBUG
  42. for (auto &I : FunctionMap)
  43. I.second->allReferencesDropped();
  44. #endif
  45. }
  46. void CallGraph::addToCallGraph(Function *F) {
  47. CallGraphNode *Node = getOrInsertFunction(F);
  48. // If this function has external linkage or has its address taken, anything
  49. // could call it.
  50. if (!F->hasLocalLinkage() || F->hasAddressTaken())
  51. ExternalCallingNode->addCalledFunction(CallSite(), Node);
  52. // If this function is not defined in this translation unit, it could call
  53. // anything.
  54. if (F->isDeclaration() && !F->isIntrinsic())
  55. Node->addCalledFunction(CallSite(), CallsExternalNode.get());
  56. // Look for calls by this function.
  57. for (BasicBlock &BB : *F)
  58. for (Instruction &I : BB) {
  59. if (auto CS = CallSite(&I)) {
  60. const Function *Callee = CS.getCalledFunction();
  61. if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
  62. // Indirect calls of intrinsics are not allowed so no need to check.
  63. // We can be more precise here by using TargetArg returned by
  64. // Intrinsic::isLeaf.
  65. Node->addCalledFunction(CS, CallsExternalNode.get());
  66. else if (!Callee->isIntrinsic())
  67. Node->addCalledFunction(CS, getOrInsertFunction(Callee));
  68. }
  69. }
  70. }
  71. void CallGraph::print(raw_ostream &OS) const {
  72. // Print in a deterministic order by sorting CallGraphNodes by name. We do
  73. // this here to avoid slowing down the non-printing fast path.
  74. SmallVector<CallGraphNode *, 16> Nodes;
  75. Nodes.reserve(FunctionMap.size());
  76. for (const auto &I : *this)
  77. Nodes.push_back(I.second.get());
  78. std::sort(Nodes.begin(), Nodes.end(),
  79. [](CallGraphNode *LHS, CallGraphNode *RHS) {
  80. if (Function *LF = LHS->getFunction())
  81. if (Function *RF = RHS->getFunction())
  82. return LF->getName() < RF->getName();
  83. return RHS->getFunction() != nullptr;
  84. });
  85. for (CallGraphNode *CN : Nodes)
  86. CN->print(OS);
  87. }
  88. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  89. void CallGraph::dump() const { print(dbgs()); }
  90. #endif
  91. // removeFunctionFromModule - Unlink the function from this module, returning
  92. // it. Because this removes the function from the module, the call graph node
  93. // is destroyed. This is only valid if the function does not call any other
  94. // functions (ie, there are no edges in it's CGN). The easiest way to do this
  95. // is to dropAllReferences before calling this.
  96. //
  97. Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
  98. assert(CGN->empty() && "Cannot remove function from call "
  99. "graph if it references other functions!");
  100. Function *F = CGN->getFunction(); // Get the function for the call graph node
  101. FunctionMap.erase(F); // Remove the call graph node from the map
  102. M.CallRemoveGlobalHook(F); // HLSL Change
  103. M.getFunctionList().remove(F);
  104. return F;
  105. }
  106. /// spliceFunction - Replace the function represented by this node by another.
  107. /// This does not rescan the body of the function, so it is suitable when
  108. /// splicing the body of the old function to the new while also updating all
  109. /// callers from old to new.
  110. ///
  111. void CallGraph::spliceFunction(const Function *From, const Function *To) {
  112. assert(FunctionMap.count(From) && "No CallGraphNode for function!");
  113. assert(!FunctionMap.count(To) &&
  114. "Pointing CallGraphNode at a function that already exists");
  115. FunctionMapTy::iterator I = FunctionMap.find(From);
  116. I->second->F = const_cast<Function*>(To);
  117. FunctionMap[To] = std::move(I->second);
  118. FunctionMap.erase(I);
  119. }
  120. // getOrInsertFunction - This method is identical to calling operator[], but
  121. // it will insert a new CallGraphNode for the specified function if one does
  122. // not already exist.
  123. CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
  124. auto &CGN = FunctionMap[F];
  125. if (CGN)
  126. return CGN.get();
  127. assert((!F || F->getParent() == &M) && "Function not in current module!");
  128. CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
  129. return CGN.get();
  130. }
  131. //===----------------------------------------------------------------------===//
  132. // Implementations of the CallGraphNode class methods.
  133. //
  134. void CallGraphNode::print(raw_ostream &OS) const {
  135. if (Function *F = getFunction())
  136. OS << "Call graph node for function: '" << F->getName() << "'";
  137. else
  138. OS << "Call graph node <<null function>>";
  139. OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
  140. for (const_iterator I = begin(), E = end(); I != E; ++I) {
  141. OS << " CS<" << I->first << "> calls ";
  142. if (Function *FI = I->second->getFunction())
  143. OS << "function '" << FI->getName() <<"'\n";
  144. else
  145. OS << "external node\n";
  146. }
  147. OS << '\n';
  148. }
  149. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  150. void CallGraphNode::dump() const { print(dbgs()); }
  151. #endif
  152. /// removeCallEdgeFor - This method removes the edge in the node for the
  153. /// specified call site. Note that this method takes linear time, so it
  154. /// should be used sparingly.
  155. void CallGraphNode::removeCallEdgeFor(CallSite CS) {
  156. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  157. assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
  158. if (I->first == CS.getInstruction()) {
  159. I->second->DropRef();
  160. *I = CalledFunctions.back();
  161. CalledFunctions.pop_back();
  162. return;
  163. }
  164. }
  165. }
  166. // removeAnyCallEdgeTo - This method removes any call edges from this node to
  167. // the specified callee function. This takes more time to execute than
  168. // removeCallEdgeTo, so it should not be used unless necessary.
  169. void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
  170. for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
  171. if (CalledFunctions[i].second == Callee) {
  172. Callee->DropRef();
  173. CalledFunctions[i] = CalledFunctions.back();
  174. CalledFunctions.pop_back();
  175. --i; --e;
  176. }
  177. }
  178. /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
  179. /// from this node to the specified callee function.
  180. void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
  181. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  182. assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
  183. CallRecord &CR = *I;
  184. if (CR.second == Callee && CR.first == nullptr) {
  185. Callee->DropRef();
  186. *I = CalledFunctions.back();
  187. CalledFunctions.pop_back();
  188. return;
  189. }
  190. }
  191. }
  192. /// replaceCallEdge - This method replaces the edge in the node for the
  193. /// specified call site with a new one. Note that this method takes linear
  194. /// time, so it should be used sparingly.
  195. void CallGraphNode::replaceCallEdge(CallSite CS,
  196. CallSite NewCS, CallGraphNode *NewNode){
  197. for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
  198. assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
  199. if (I->first == CS.getInstruction()) {
  200. I->second->DropRef();
  201. I->first = NewCS.getInstruction();
  202. I->second = NewNode;
  203. NewNode->AddRef();
  204. return;
  205. }
  206. }
  207. }
  208. //===----------------------------------------------------------------------===//
  209. // Out-of-line definitions of CallGraphAnalysis class members.
  210. //
  211. char CallGraphAnalysis::PassID;
  212. //===----------------------------------------------------------------------===//
  213. // Implementations of the CallGraphWrapperPass class methods.
  214. //
  215. CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
  216. initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
  217. }
  218. CallGraphWrapperPass::~CallGraphWrapperPass() {}
  219. void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  220. AU.setPreservesAll();
  221. }
  222. bool CallGraphWrapperPass::runOnModule(Module &M) {
  223. // All the real work is done in the constructor for the CallGraph.
  224. G.reset(new CallGraph(M));
  225. return false;
  226. }
  227. INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
  228. false, true)
  229. char CallGraphWrapperPass::ID = 0;
  230. void CallGraphWrapperPass::releaseMemory() { G.reset(); }
  231. void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
  232. if (!G) {
  233. OS << "No call graph has been built!\n";
  234. return;
  235. }
  236. // Just delegate.
  237. G->print(OS);
  238. }
  239. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  240. void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
  241. #endif