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 void CallGraph::ReplaceExternalCallEdge(CallGraphNode *Old, 133 CallGraphNode *New) { 134 for (auto &CR : ExternalCallingNode->CalledFunctions) 135 if (CR.second == Old) { 136 CR.second->DropRef(); 137 CR.second = New; 138 CR.second->AddRef(); 139 } 140 } 141 142 // removeFunctionFromModule - Unlink the function from this module, returning 143 // it. Because this removes the function from the module, the call graph node 144 // is destroyed. This is only valid if the function does not call any other 145 // functions (ie, there are no edges in it's CGN). The easiest way to do this 146 // is to dropAllReferences before calling this. 147 // 148 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) { 149 assert(CGN->empty() && "Cannot remove function from call " 150 "graph if it references other functions!"); 151 Function *F = CGN->getFunction(); // Get the function for the call graph node 152 FunctionMap.erase(F); // Remove the call graph node from the map 153 154 M.getFunctionList().remove(F); 155 return F; 156 } 157 158 /// spliceFunction - Replace the function represented by this node by another. 159 /// This does not rescan the body of the function, so it is suitable when 160 /// splicing the body of the old function to the new while also updating all 161 /// callers from old to new. 162 void CallGraph::spliceFunction(const Function *From, const Function *To) { 163 assert(FunctionMap.count(From) && "No CallGraphNode for function!"); 164 assert(!FunctionMap.count(To) && 165 "Pointing CallGraphNode at a function that already exists"); 166 FunctionMapTy::iterator I = FunctionMap.find(From); 167 I->second->F = const_cast<Function*>(To); 168 FunctionMap[To] = std::move(I->second); 169 FunctionMap.erase(I); 170 } 171 172 // getOrInsertFunction - This method is identical to calling operator[], but 173 // it will insert a new CallGraphNode for the specified function if one does 174 // not already exist. 175 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) { 176 auto &CGN = FunctionMap[F]; 177 if (CGN) 178 return CGN.get(); 179 180 assert((!F || F->getParent() == &M) && "Function not in current module!"); 181 CGN = std::make_unique<CallGraphNode>(const_cast<Function *>(F)); 182 return CGN.get(); 183 } 184 185 //===----------------------------------------------------------------------===// 186 // Implementations of the CallGraphNode class methods. 187 // 188 189 void CallGraphNode::print(raw_ostream &OS) const { 190 if (Function *F = getFunction()) 191 OS << "Call graph node for function: '" << F->getName() << "'"; 192 else 193 OS << "Call graph node <<null function>>"; 194 195 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n'; 196 197 for (const auto &I : *this) { 198 OS << " CS<" << I.first << "> calls "; 199 if (Function *FI = I.second->getFunction()) 200 OS << "function '" << FI->getName() <<"'\n"; 201 else 202 OS << "external node\n"; 203 } 204 OS << '\n'; 205 } 206 207 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 208 LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); } 209 #endif 210 211 /// removeCallEdgeFor - This method removes the edge in the node for the 212 /// specified call site. Note that this method takes linear time, so it 213 /// should be used sparingly. 214 void CallGraphNode::removeCallEdgeFor(CallBase &Call) { 215 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) { 216 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!"); 217 if (I->first == &Call) { 218 I->second->DropRef(); 219 *I = CalledFunctions.back(); 220 CalledFunctions.pop_back(); 221 return; 222 } 223 } 224 } 225 226 // removeAnyCallEdgeTo - This method removes any call edges from this node to 227 // the specified callee function. This takes more time to execute than 228 // removeCallEdgeTo, so it should not be used unless necessary. 229 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) { 230 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i) 231 if (CalledFunctions[i].second == Callee) { 232 Callee->DropRef(); 233 CalledFunctions[i] = CalledFunctions.back(); 234 CalledFunctions.pop_back(); 235 --i; --e; 236 } 237 } 238 239 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite 240 /// from this node to the specified callee function. 241 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) { 242 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) { 243 assert(I != CalledFunctions.end() && "Cannot find callee to remove!"); 244 CallRecord &CR = *I; 245 if (CR.second == Callee && CR.first == nullptr) { 246 Callee->DropRef(); 247 *I = CalledFunctions.back(); 248 CalledFunctions.pop_back(); 249 return; 250 } 251 } 252 } 253 254 /// replaceCallEdge - This method replaces the edge in the node for the 255 /// specified call site with a new one. Note that this method takes linear 256 /// time, so it should be used sparingly. 257 void CallGraphNode::replaceCallEdge(CallBase &Call, CallBase &NewCall, 258 CallGraphNode *NewNode) { 259 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) { 260 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!"); 261 if (I->first == &Call) { 262 I->second->DropRef(); 263 I->first = &NewCall; 264 I->second = NewNode; 265 NewNode->AddRef(); 266 return; 267 } 268 } 269 } 270 271 // Provide an explicit template instantiation for the static ID. 272 AnalysisKey CallGraphAnalysis::Key; 273 274 PreservedAnalyses CallGraphPrinterPass::run(Module &M, 275 ModuleAnalysisManager &AM) { 276 AM.getResult<CallGraphAnalysis>(M).print(OS); 277 return PreservedAnalyses::all(); 278 } 279 280 //===----------------------------------------------------------------------===// 281 // Out-of-line definitions of CallGraphAnalysis class members. 282 // 283 284 //===----------------------------------------------------------------------===// 285 // Implementations of the CallGraphWrapperPass class methods. 286 // 287 288 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) { 289 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry()); 290 } 291 292 CallGraphWrapperPass::~CallGraphWrapperPass() = default; 293 294 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 295 AU.setPreservesAll(); 296 } 297 298 bool CallGraphWrapperPass::runOnModule(Module &M) { 299 // All the real work is done in the constructor for the CallGraph. 300 G.reset(new CallGraph(M)); 301 return false; 302 } 303 304 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction", 305 false, true) 306 307 char CallGraphWrapperPass::ID = 0; 308 309 void CallGraphWrapperPass::releaseMemory() { G.reset(); } 310 311 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const { 312 if (!G) { 313 OS << "No call graph has been built!\n"; 314 return; 315 } 316 317 // Just delegate. 318 G->print(OS); 319 } 320 321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 322 LLVM_DUMP_METHOD 323 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); } 324 #endif 325 326 namespace { 327 328 struct CallGraphPrinterLegacyPass : public ModulePass { 329 static char ID; // Pass ID, replacement for typeid 330 331 CallGraphPrinterLegacyPass() : ModulePass(ID) { 332 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry()); 333 } 334 335 void getAnalysisUsage(AnalysisUsage &AU) const override { 336 AU.setPreservesAll(); 337 AU.addRequiredTransitive<CallGraphWrapperPass>(); 338 } 339 340 bool runOnModule(Module &M) override { 341 getAnalysis<CallGraphWrapperPass>().print(errs(), &M); 342 return false; 343 } 344 }; 345 346 } // end anonymous namespace 347 348 char CallGraphPrinterLegacyPass::ID = 0; 349 350 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph", 351 "Print a call graph", true, true) 352 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 353 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph", 354 "Print a call graph", true, true) 355