1 //===- ElimAvailExtern.cpp - DCE unreachable internal functions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transform is designed to eliminate available external global
11 // definitions from the program, turning them into declarations.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/Constant.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalValue.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Utils/GlobalStatus.h"
28 #define DEBUG_TYPE "elim-avail-extern"
30 STATISTIC(NumFunctions, "Number of functions removed");
31 STATISTIC(NumVariables, "Number of global variables removed");
33 static bool eliminateAvailableExternally(Module &M) {
36 // Drop initializers of available externally global variables.
37 for (GlobalVariable &GV : M.globals()) {
38 if (!GV.hasAvailableExternallyLinkage())
40 if (GV.hasInitializer()) {
41 Constant *Init = GV.getInitializer();
42 GV.setInitializer(nullptr);
43 if (isSafeToDestroyConstant(Init))
44 Init->destroyConstant();
46 GV.removeDeadConstantUsers();
47 GV.setLinkage(GlobalValue::ExternalLinkage);
52 // Drop the bodies of available externally functions.
53 for (Function &F : M) {
54 if (!F.hasAvailableExternallyLinkage())
56 if (!F.isDeclaration())
57 // This will set the linkage to external
59 F.removeDeadConstantUsers();
68 EliminateAvailableExternallyPass::run(Module &M, ModuleAnalysisManager &) {
69 if (!eliminateAvailableExternally(M))
70 return PreservedAnalyses::all();
71 return PreservedAnalyses::none();
76 struct EliminateAvailableExternallyLegacyPass : public ModulePass {
77 static char ID; // Pass identification, replacement for typeid
79 EliminateAvailableExternallyLegacyPass() : ModulePass(ID) {
80 initializeEliminateAvailableExternallyLegacyPassPass(
81 *PassRegistry::getPassRegistry());
84 // run - Do the EliminateAvailableExternally pass on the specified module,
85 // optionally updating the specified callgraph to reflect the changes.
86 bool runOnModule(Module &M) override {
89 return eliminateAvailableExternally(M);
93 } // end anonymous namespace
95 char EliminateAvailableExternallyLegacyPass::ID = 0;
97 INITIALIZE_PASS(EliminateAvailableExternallyLegacyPass, "elim-avail-extern",
98 "Eliminate Available Externally Globals", false, false)
100 ModulePass *llvm::createEliminateAvailableExternallyPass() {
101 return new EliminateAvailableExternallyLegacyPass();