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.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Transforms/Utils/CtorUtils.h"
21 #include "llvm/Transforms/Utils/GlobalStatus.h"
22 #include "llvm/Pass.h"
25 #define DEBUG_TYPE "elim-avail-extern"
27 STATISTIC(NumAliases , "Number of global aliases removed");
28 STATISTIC(NumFunctions, "Number of functions removed");
29 STATISTIC(NumVariables, "Number of global variables removed");
32 struct EliminateAvailableExternally : public ModulePass {
33 static char ID; // Pass identification, replacement for typeid
34 EliminateAvailableExternally() : ModulePass(ID) {
35 initializeEliminateAvailableExternallyPass(
36 *PassRegistry::getPassRegistry());
39 // run - Do the EliminateAvailableExternally pass on the specified module,
40 // optionally updating the specified callgraph to reflect the changes.
42 bool runOnModule(Module &M) override;
46 char EliminateAvailableExternally::ID = 0;
47 INITIALIZE_PASS(EliminateAvailableExternally, "elim-avail-extern",
48 "Eliminate Available Externally Globals", false, false)
50 ModulePass *llvm::createEliminateAvailableExternallyPass() {
51 return new EliminateAvailableExternally();
54 bool EliminateAvailableExternally::runOnModule(Module &M) {
57 // Drop initializers of available externally global variables.
58 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
60 if (!I->hasAvailableExternallyLinkage())
62 if (I->hasInitializer()) {
63 Constant *Init = I->getInitializer();
64 I->setInitializer(nullptr);
65 if (isSafeToDestroyConstant(Init))
66 Init->destroyConstant();
68 I->removeDeadConstantUsers();
69 I->setLinkage(GlobalValue::ExternalLinkage);
73 // Drop the bodies of available externally functions.
74 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
75 if (!I->hasAvailableExternallyLinkage())
77 if (!I->isDeclaration())
78 // This will set the linkage to external
80 I->removeDeadConstantUsers();