1 //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===// 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 /// \file 10 /// 11 /// This file provides interfaces used to build and manipulate a call graph, 12 /// which is a very useful tool for interprocedural optimization. 13 /// 14 /// Every function in a module is represented as a node in the call graph. The 15 /// callgraph node keeps track of which functions are called by the function 16 /// corresponding to the node. 17 /// 18 /// A call graph may contain nodes where the function that they correspond to 19 /// is null. These 'external' nodes are used to represent control flow that is 20 /// not represented (or analyzable) in the module. In particular, this 21 /// analysis builds one external node such that: 22 /// 1. All functions in the module without internal linkage will have edges 23 /// from this external node, indicating that they could be called by 24 /// functions outside of the module. 25 /// 2. All functions whose address is used for something more than a direct 26 /// call, for example being stored into a memory location will also have 27 /// an edge from this external node. Since they may be called by an 28 /// unknown caller later, they must be tracked as such. 29 /// 30 /// There is a second external node added for calls that leave this module. 31 /// Functions have a call edge to the external node iff: 32 /// 1. The function is external, reflecting the fact that they could call 33 /// anything without internal linkage or that has its address taken. 34 /// 2. The function contains an indirect function call. 35 /// 36 /// As an extension in the future, there may be multiple nodes with a null 37 /// function. These will be used when we can prove (through pointer analysis) 38 /// that an indirect call site can call only a specific set of functions. 39 /// 40 /// Because of these properties, the CallGraph captures a conservative superset 41 /// of all of the caller-callee relationships, which is useful for 42 /// transformations. 43 /// 44 /// The CallGraph class also attempts to figure out what the root of the 45 /// CallGraph is, which it currently does by looking for a function named 46 /// 'main'. If no function named 'main' is found, the external node is used as 47 /// the entry node, reflecting the fact that any function without internal 48 /// linkage could be called into (which is common for libraries). 49 /// 50 //===----------------------------------------------------------------------===// 51 52 #ifndef LLVM_ANALYSIS_CALLGRAPH_H 53 #define LLVM_ANALYSIS_CALLGRAPH_H 54 55 #include "llvm/ADT/GraphTraits.h" 56 #include "llvm/ADT/STLExtras.h" 57 #include "llvm/IR/CallSite.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/ValueHandle.h" 60 #include "llvm/Pass.h" 61 #include <map> 62 63 namespace llvm { 64 65 class Function; 66 class Module; 67 class CallGraphNode; 68 69 /// \brief The basic data container for the call graph of a \c Module of IR. 70 /// 71 /// This class exposes both the interface to the call graph for a module of IR. 72 /// 73 /// The core call graph itself can also be updated to reflect changes to the IR. 74 class CallGraph { 75 Module &M; 76 77 typedef std::map<const Function *, CallGraphNode *> FunctionMapTy; 78 79 /// \brief A map from \c Function* to \c CallGraphNode*. 80 FunctionMapTy FunctionMap; 81 82 /// \brief Root is root of the call graph, or the external node if a 'main' 83 /// function couldn't be found. 84 CallGraphNode *Root; 85 86 /// \brief This node has edges to all external functions and those internal 87 /// functions that have their address taken. 88 CallGraphNode *ExternalCallingNode; 89 90 /// \brief This node has edges to it from all functions making indirect calls 91 /// or calling an external function. 92 CallGraphNode *CallsExternalNode; 93 94 /// \brief Replace the function represented by this node by another. 95 /// 96 /// This does not rescan the body of the function, so it is suitable when 97 /// splicing the body of one function to another while also updating all 98 /// callers from the old function to the new. 99 void spliceFunction(const Function *From, const Function *To); 100 101 /// \brief Add a function to the call graph, and link the node to all of the 102 /// functions that it calls. 103 void addToCallGraph(Function *F); 104 105 public: 106 CallGraph(Module &M); 107 ~CallGraph(); 108 109 void print(raw_ostream &OS) const; 110 void dump() const; 111 112 typedef FunctionMapTy::iterator iterator; 113 typedef FunctionMapTy::const_iterator const_iterator; 114 115 /// \brief Returns the module the call graph corresponds to. getModule()116 Module &getModule() const { return M; } 117 begin()118 inline iterator begin() { return FunctionMap.begin(); } end()119 inline iterator end() { return FunctionMap.end(); } begin()120 inline const_iterator begin() const { return FunctionMap.begin(); } end()121 inline const_iterator end() const { return FunctionMap.end(); } 122 123 /// \brief Returns the call graph node for the provided function. 124 inline const CallGraphNode *operator[](const Function *F) const { 125 const_iterator I = FunctionMap.find(F); 126 assert(I != FunctionMap.end() && "Function not in callgraph!"); 127 return I->second; 128 } 129 130 /// \brief Returns the call graph node for the provided function. 131 inline CallGraphNode *operator[](const Function *F) { 132 const_iterator I = FunctionMap.find(F); 133 assert(I != FunctionMap.end() && "Function not in callgraph!"); 134 return I->second; 135 } 136 137 /// \brief Returns the \c CallGraphNode which is used to represent 138 /// undetermined calls into the callgraph. getExternalCallingNode()139 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; } 140 getCallsExternalNode()141 CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; } 142 143 //===--------------------------------------------------------------------- 144 // Functions to keep a call graph up to date with a function that has been 145 // modified. 146 // 147 148 /// \brief Unlink the function from this module, returning it. 149 /// 150 /// Because this removes the function from the module, the call graph node is 151 /// destroyed. This is only valid if the function does not call any other 152 /// functions (ie, there are no edges in it's CGN). The easiest way to do 153 /// this is to dropAllReferences before calling this. 154 Function *removeFunctionFromModule(CallGraphNode *CGN); 155 156 /// \brief Similar to operator[], but this will insert a new CallGraphNode for 157 /// \c F if one does not already exist. 158 CallGraphNode *getOrInsertFunction(const Function *F); 159 }; 160 161 /// \brief A node in the call graph for a module. 162 /// 163 /// Typically represents a function in the call graph. There are also special 164 /// "null" nodes used to represent theoretical entries in the call graph. 165 class CallGraphNode { 166 public: 167 /// \brief A pair of the calling instruction (a call or invoke) 168 /// and the call graph node being called. 169 typedef std::pair<WeakVH, CallGraphNode *> CallRecord; 170 171 public: 172 typedef std::vector<CallRecord> CalledFunctionsVector; 173 174 /// \brief Creates a node for the specified function. CallGraphNode(Function * F)175 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {} 176 ~CallGraphNode()177 ~CallGraphNode() { 178 assert(NumReferences == 0 && "Node deleted while references remain"); 179 } 180 181 typedef std::vector<CallRecord>::iterator iterator; 182 typedef std::vector<CallRecord>::const_iterator const_iterator; 183 184 /// \brief Returns the function that this call graph node represents. getFunction()185 Function *getFunction() const { return F; } 186 begin()187 inline iterator begin() { return CalledFunctions.begin(); } end()188 inline iterator end() { return CalledFunctions.end(); } begin()189 inline const_iterator begin() const { return CalledFunctions.begin(); } end()190 inline const_iterator end() const { return CalledFunctions.end(); } empty()191 inline bool empty() const { return CalledFunctions.empty(); } size()192 inline unsigned size() const { return (unsigned)CalledFunctions.size(); } 193 194 /// \brief Returns the number of other CallGraphNodes in this CallGraph that 195 /// reference this node in their callee list. getNumReferences()196 unsigned getNumReferences() const { return NumReferences; } 197 198 /// \brief Returns the i'th called function. 199 CallGraphNode *operator[](unsigned i) const { 200 assert(i < CalledFunctions.size() && "Invalid index"); 201 return CalledFunctions[i].second; 202 } 203 204 /// \brief Print out this call graph node. 205 void dump() const; 206 void print(raw_ostream &OS) const; 207 208 //===--------------------------------------------------------------------- 209 // Methods to keep a call graph up to date with a function that has been 210 // modified 211 // 212 213 /// \brief Removes all edges from this CallGraphNode to any functions it 214 /// calls. removeAllCalledFunctions()215 void removeAllCalledFunctions() { 216 while (!CalledFunctions.empty()) { 217 CalledFunctions.back().second->DropRef(); 218 CalledFunctions.pop_back(); 219 } 220 } 221 222 /// \brief Moves all the callee information from N to this node. stealCalledFunctionsFrom(CallGraphNode * N)223 void stealCalledFunctionsFrom(CallGraphNode *N) { 224 assert(CalledFunctions.empty() && 225 "Cannot steal callsite information if I already have some"); 226 std::swap(CalledFunctions, N->CalledFunctions); 227 } 228 229 /// \brief Adds a function to the list of functions called by this one. addCalledFunction(CallSite CS,CallGraphNode * M)230 void addCalledFunction(CallSite CS, CallGraphNode *M) { 231 assert(!CS.getInstruction() || !CS.getCalledFunction() || 232 !CS.getCalledFunction()->isIntrinsic()); 233 CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M)); 234 M->AddRef(); 235 } 236 removeCallEdge(iterator I)237 void removeCallEdge(iterator I) { 238 I->second->DropRef(); 239 *I = CalledFunctions.back(); 240 CalledFunctions.pop_back(); 241 } 242 243 /// \brief Removes the edge in the node for the specified call site. 244 /// 245 /// Note that this method takes linear time, so it should be used sparingly. 246 void removeCallEdgeFor(CallSite CS); 247 248 /// \brief Removes all call edges from this node to the specified callee 249 /// function. 250 /// 251 /// This takes more time to execute than removeCallEdgeTo, so it should not 252 /// be used unless necessary. 253 void removeAnyCallEdgeTo(CallGraphNode *Callee); 254 255 /// \brief Removes one edge associated with a null callsite from this node to 256 /// the specified callee function. 257 void removeOneAbstractEdgeTo(CallGraphNode *Callee); 258 259 /// \brief Replaces the edge in the node for the specified call site with a 260 /// new one. 261 /// 262 /// Note that this method takes linear time, so it should be used sparingly. 263 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode); 264 265 private: 266 friend class CallGraph; 267 268 AssertingVH<Function> F; 269 270 std::vector<CallRecord> CalledFunctions; 271 272 /// \brief The number of times that this CallGraphNode occurs in the 273 /// CalledFunctions array of this or other CallGraphNodes. 274 unsigned NumReferences; 275 276 CallGraphNode(const CallGraphNode &) = delete; 277 void operator=(const CallGraphNode &) = delete; 278 DropRef()279 void DropRef() { --NumReferences; } AddRef()280 void AddRef() { ++NumReferences; } 281 282 /// \brief A special function that should only be used by the CallGraph class. allReferencesDropped()283 void allReferencesDropped() { NumReferences = 0; } 284 }; 285 286 /// \brief An analysis pass to compute the \c CallGraph for a \c Module. 287 /// 288 /// This class implements the concept of an analysis pass used by the \c 289 /// ModuleAnalysisManager to run an analysis over a module and cache the 290 /// resulting data. 291 class CallGraphAnalysis { 292 public: 293 /// \brief A formulaic typedef to inform clients of the result type. 294 typedef CallGraph Result; 295 ID()296 static void *ID() { return (void *)&PassID; } 297 298 /// \brief Compute the \c CallGraph for the module \c M. 299 /// 300 /// The real work here is done in the \c CallGraph constructor. run(Module * M)301 CallGraph run(Module *M) { return CallGraph(*M); } 302 303 private: 304 static char PassID; 305 }; 306 307 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to 308 /// build it. 309 /// 310 /// This class exposes both the interface to the call graph container and the 311 /// module pass which runs over a module of IR and produces the call graph. The 312 /// call graph interface is entirelly a wrapper around a \c CallGraph object 313 /// which is stored internally for each module. 314 class CallGraphWrapperPass : public ModulePass { 315 std::unique_ptr<CallGraph> G; 316 317 public: 318 static char ID; // Class identification, replacement for typeinfo 319 320 CallGraphWrapperPass(); 321 ~CallGraphWrapperPass() override; 322 323 /// \brief The internal \c CallGraph around which the rest of this interface 324 /// is wrapped. getCallGraph()325 const CallGraph &getCallGraph() const { return *G; } getCallGraph()326 CallGraph &getCallGraph() { return *G; } 327 328 typedef CallGraph::iterator iterator; 329 typedef CallGraph::const_iterator const_iterator; 330 331 /// \brief Returns the module the call graph corresponds to. getModule()332 Module &getModule() const { return G->getModule(); } 333 begin()334 inline iterator begin() { return G->begin(); } end()335 inline iterator end() { return G->end(); } begin()336 inline const_iterator begin() const { return G->begin(); } end()337 inline const_iterator end() const { return G->end(); } 338 339 /// \brief Returns the call graph node for the provided function. 340 inline const CallGraphNode *operator[](const Function *F) const { 341 return (*G)[F]; 342 } 343 344 /// \brief Returns the call graph node for the provided function. 345 inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; } 346 347 /// \brief Returns the \c CallGraphNode which is used to represent 348 /// undetermined calls into the callgraph. getExternalCallingNode()349 CallGraphNode *getExternalCallingNode() const { 350 return G->getExternalCallingNode(); 351 } 352 getCallsExternalNode()353 CallGraphNode *getCallsExternalNode() const { 354 return G->getCallsExternalNode(); 355 } 356 357 //===--------------------------------------------------------------------- 358 // Functions to keep a call graph up to date with a function that has been 359 // modified. 360 // 361 362 /// \brief Unlink the function from this module, returning it. 363 /// 364 /// Because this removes the function from the module, the call graph node is 365 /// destroyed. This is only valid if the function does not call any other 366 /// functions (ie, there are no edges in it's CGN). The easiest way to do 367 /// this is to dropAllReferences before calling this. removeFunctionFromModule(CallGraphNode * CGN)368 Function *removeFunctionFromModule(CallGraphNode *CGN) { 369 return G->removeFunctionFromModule(CGN); 370 } 371 372 /// \brief Similar to operator[], but this will insert a new CallGraphNode for 373 /// \c F if one does not already exist. getOrInsertFunction(const Function * F)374 CallGraphNode *getOrInsertFunction(const Function *F) { 375 return G->getOrInsertFunction(F); 376 } 377 378 //===--------------------------------------------------------------------- 379 // Implementation of the ModulePass interface needed here. 380 // 381 382 void getAnalysisUsage(AnalysisUsage &AU) const override; 383 bool runOnModule(Module &M) override; 384 void releaseMemory() override; 385 386 void print(raw_ostream &o, const Module *) const override; 387 void dump() const; 388 }; 389 390 //===----------------------------------------------------------------------===// 391 // GraphTraits specializations for call graphs so that they can be treated as 392 // graphs by the generic graph algorithms. 393 // 394 395 // Provide graph traits for tranversing call graphs using standard graph 396 // traversals. 397 template <> struct GraphTraits<CallGraphNode *> { 398 typedef CallGraphNode NodeType; 399 400 typedef CallGraphNode::CallRecord CGNPairTy; 401 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *> 402 CGNDerefFun; 403 404 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; } 405 406 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType; 407 408 static inline ChildIteratorType child_begin(NodeType *N) { 409 return map_iterator(N->begin(), CGNDerefFun(CGNDeref)); 410 } 411 static inline ChildIteratorType child_end(NodeType *N) { 412 return map_iterator(N->end(), CGNDerefFun(CGNDeref)); 413 } 414 415 static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; } 416 }; 417 418 template <> struct GraphTraits<const CallGraphNode *> { 419 typedef const CallGraphNode NodeType; 420 421 typedef CallGraphNode::CallRecord CGNPairTy; 422 typedef std::pointer_to_unary_function<CGNPairTy, const CallGraphNode *> 423 CGNDerefFun; 424 425 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; } 426 427 typedef mapped_iterator<NodeType::const_iterator, CGNDerefFun> 428 ChildIteratorType; 429 430 static inline ChildIteratorType child_begin(NodeType *N) { 431 return map_iterator(N->begin(), CGNDerefFun(CGNDeref)); 432 } 433 static inline ChildIteratorType child_end(NodeType *N) { 434 return map_iterator(N->end(), CGNDerefFun(CGNDeref)); 435 } 436 437 static const CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; } 438 }; 439 440 template <> 441 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> { 442 static NodeType *getEntryNode(CallGraph *CGN) { 443 return CGN->getExternalCallingNode(); // Start at the external node! 444 } 445 typedef std::pair<const Function *, CallGraphNode *> PairTy; 446 typedef std::pointer_to_unary_function<PairTy, CallGraphNode &> DerefFun; 447 448 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph 449 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator; 450 static nodes_iterator nodes_begin(CallGraph *CG) { 451 return map_iterator(CG->begin(), DerefFun(CGdereference)); 452 } 453 static nodes_iterator nodes_end(CallGraph *CG) { 454 return map_iterator(CG->end(), DerefFun(CGdereference)); 455 } 456 457 static CallGraphNode &CGdereference(PairTy P) { return *P.second; } 458 }; 459 460 template <> 461 struct GraphTraits<const CallGraph *> : public GraphTraits< 462 const CallGraphNode *> { 463 static NodeType *getEntryNode(const CallGraph *CGN) { 464 return CGN->getExternalCallingNode(); // Start at the external node! 465 } 466 typedef std::pair<const Function *, const CallGraphNode *> PairTy; 467 typedef std::pointer_to_unary_function<PairTy, const CallGraphNode &> 468 DerefFun; 469 470 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph 471 typedef mapped_iterator<CallGraph::const_iterator, DerefFun> nodes_iterator; 472 static nodes_iterator nodes_begin(const CallGraph *CG) { 473 return map_iterator(CG->begin(), DerefFun(CGdereference)); 474 } 475 static nodes_iterator nodes_end(const CallGraph *CG) { 476 return map_iterator(CG->end(), DerefFun(CGdereference)); 477 } 478 479 static const CallGraphNode &CGdereference(PairTy P) { return *P.second; } 480 }; 481 482 } // End llvm namespace 483 484 #endif 485