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