CallGraph.cpp 11 KB

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