1 //===-- StripDeadPrototypes.cpp - Remove unused function declarations ----===//
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 // This pass loops over all of the functions in the input module, looking for
10 // dead declarations and removes them. Dead declarations are declarations of
11 // functions for which no implementation is available (i.e., declarations for
12 // unused library functions).
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/InitializePasses.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Transforms/IPO.h"
22
23 using namespace llvm;
24
25 #define DEBUG_TYPE "strip-dead-prototypes"
26
27 STATISTIC(NumDeadPrototypes, "Number of dead prototypes removed");
28
stripDeadPrototypes(Module & M)29 static bool stripDeadPrototypes(Module &M) {
30 bool MadeChange = false;
31
32 // Erase dead function prototypes.
33 for (Function &F : llvm::make_early_inc_range(M)) {
34 // Function must be a prototype and unused.
35 if (F.isDeclaration() && F.use_empty()) {
36 F.eraseFromParent();
37 ++NumDeadPrototypes;
38 MadeChange = true;
39 }
40 }
41
42 // Erase dead global var prototypes.
43 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
44 // Global must be a prototype and unused.
45 if (GV.isDeclaration() && GV.use_empty())
46 GV.eraseFromParent();
47 }
48
49 // Return an indication of whether we changed anything or not.
50 return MadeChange;
51 }
52
run(Module & M,ModuleAnalysisManager &)53 PreservedAnalyses StripDeadPrototypesPass::run(Module &M,
54 ModuleAnalysisManager &) {
55 if (stripDeadPrototypes(M))
56 return PreservedAnalyses::none();
57 return PreservedAnalyses::all();
58 }
59
60 namespace {
61
62 class StripDeadPrototypesLegacyPass : public ModulePass {
63 public:
64 static char ID; // Pass identification, replacement for typeid
StripDeadPrototypesLegacyPass()65 StripDeadPrototypesLegacyPass() : ModulePass(ID) {
66 initializeStripDeadPrototypesLegacyPassPass(
67 *PassRegistry::getPassRegistry());
68 }
runOnModule(Module & M)69 bool runOnModule(Module &M) override {
70 if (skipModule(M))
71 return false;
72
73 return stripDeadPrototypes(M);
74 }
75 };
76
77 } // end anonymous namespace
78
79 char StripDeadPrototypesLegacyPass::ID = 0;
80 INITIALIZE_PASS(StripDeadPrototypesLegacyPass, "strip-dead-prototypes",
81 "Strip Unused Function Prototypes", false, false)
82
createStripDeadPrototypesPass()83 ModulePass *llvm::createStripDeadPrototypesPass() {
84 return new StripDeadPrototypesLegacyPass();
85 }
86