1 //===- ElimAvailExtern.cpp - DCE unreachable internal functions -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This transform is designed to eliminate available external global
10 // definitions from the program, turning them into declarations.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/IR/Constant.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/GlobalValue.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Transforms/Utils/GlobalStatus.h"
27 #define DEBUG_TYPE "elim-avail-extern"
29 STATISTIC(NumFunctions, "Number of functions removed");
30 STATISTIC(NumVariables, "Number of global variables removed");
32 static bool eliminateAvailableExternally(Module &M) {
35 // Drop initializers of available externally global variables.
36 for (GlobalVariable &GV : M.globals()) {
37 if (!GV.hasAvailableExternallyLinkage())
39 if (GV.hasInitializer()) {
40 Constant *Init = GV.getInitializer();
41 GV.setInitializer(nullptr);
42 if (isSafeToDestroyConstant(Init))
43 Init->destroyConstant();
45 GV.removeDeadConstantUsers();
46 GV.setLinkage(GlobalValue::ExternalLinkage);
51 // Drop the bodies of available externally functions.
52 for (Function &F : M) {
53 if (!F.hasAvailableExternallyLinkage())
55 if (!F.isDeclaration())
56 // This will set the linkage to external
58 F.removeDeadConstantUsers();
67 EliminateAvailableExternallyPass::run(Module &M, ModuleAnalysisManager &) {
68 if (!eliminateAvailableExternally(M))
69 return PreservedAnalyses::all();
70 return PreservedAnalyses::none();
75 struct EliminateAvailableExternallyLegacyPass : public ModulePass {
76 static char ID; // Pass identification, replacement for typeid
78 EliminateAvailableExternallyLegacyPass() : ModulePass(ID) {
79 initializeEliminateAvailableExternallyLegacyPassPass(
80 *PassRegistry::getPassRegistry());
83 // run - Do the EliminateAvailableExternally pass on the specified module,
84 // optionally updating the specified callgraph to reflect the changes.
85 bool runOnModule(Module &M) override {
88 return eliminateAvailableExternally(M);
92 } // end anonymous namespace
94 char EliminateAvailableExternallyLegacyPass::ID = 0;
96 INITIALIZE_PASS(EliminateAvailableExternallyLegacyPass, "elim-avail-extern",
97 "Eliminate Available Externally Globals", false, false)
99 ModulePass *llvm::createEliminateAvailableExternallyPass() {
100 return new EliminateAvailableExternallyLegacyPass();