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