Internalize.cpp revision e922c0201916e0b980ab3cfe91e1413e68d55647
1//===-- Internalize.cpp - Mark functions internal -------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass loops over all of the functions in the input module, looking for a
11// main function.  If a main function is found, all other functions and all
12// global variables with initializers are marked as internal.
13//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "internalize"
17#include "llvm/Analysis/CallGraph.h"
18#include "llvm/Transforms/IPO.h"
19#include "llvm/Pass.h"
20#include "llvm/Module.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/ADT/Statistic.h"
25#include <fstream>
26#include <set>
27using namespace llvm;
28
29STATISTIC(NumAliases  , "Number of aliases internalized");
30STATISTIC(NumFunctions, "Number of functions internalized");
31STATISTIC(NumGlobals  , "Number of global vars internalized");
32
33// APIFile - A file which contains a list of symbols that should not be marked
34// external.
35static cl::opt<std::string>
36APIFile("internalize-public-api-file", cl::value_desc("filename"),
37        cl::desc("A file containing list of symbol names to preserve"));
38
39// APIList - A list of symbols that should not be marked internal.
40static cl::list<std::string>
41APIList("internalize-public-api-list", cl::value_desc("list"),
42        cl::desc("A list of symbol names to preserve"),
43        cl::CommaSeparated);
44
45namespace {
46  class VISIBILITY_HIDDEN InternalizePass : public ModulePass {
47    std::set<std::string> ExternalNames;
48    /// If no api symbols were specified and a main function is defined,
49    /// assume the main function is the only API
50    bool AllButMain;
51  public:
52    static char ID; // Pass identification, replacement for typeid
53    explicit InternalizePass(bool AllButMain = true);
54    explicit InternalizePass(const std::vector <const char *>& exportList);
55    void LoadFile(const char *Filename);
56    virtual bool runOnModule(Module &M);
57
58    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59      AU.setPreservesCFG();
60      AU.addPreserved<CallGraph>();
61    }
62  };
63} // end anonymous namespace
64
65char InternalizePass::ID = 0;
66static RegisterPass<InternalizePass>
67X("internalize", "Internalize Global Symbols");
68
69InternalizePass::InternalizePass(bool AllButMain)
70  : ModulePass(&ID), AllButMain(AllButMain){
71  if (!APIFile.empty())           // If a filename is specified, use it.
72    LoadFile(APIFile.c_str());
73  if (!APIList.empty())           // If a list is specified, use it as well.
74    ExternalNames.insert(APIList.begin(), APIList.end());
75}
76
77InternalizePass::InternalizePass(const std::vector<const char *>&exportList)
78  : ModulePass(&ID), AllButMain(false){
79  for(std::vector<const char *>::const_iterator itr = exportList.begin();
80        itr != exportList.end(); itr++) {
81    ExternalNames.insert(*itr);
82  }
83}
84
85void InternalizePass::LoadFile(const char *Filename) {
86  // Load the APIFile...
87  std::ifstream In(Filename);
88  if (!In.good()) {
89    cerr << "WARNING: Internalize couldn't load file '" << Filename
90         << "'! Continuing as if it's empty.\n";
91    return; // Just continue as if the file were empty
92  }
93  while (In) {
94    std::string Symbol;
95    In >> Symbol;
96    if (!Symbol.empty())
97      ExternalNames.insert(Symbol);
98  }
99}
100
101bool InternalizePass::runOnModule(Module &M) {
102  CallGraph *CG = getAnalysisIfAvailable<CallGraph>();
103  CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : 0;
104
105  if (ExternalNames.empty()) {
106    // Return if we're not in 'all but main' mode and have no external api
107    if (!AllButMain)
108      return false;
109    // If no list or file of symbols was specified, check to see if there is a
110    // "main" symbol defined in the module.  If so, use it, otherwise do not
111    // internalize the module, it must be a library or something.
112    //
113    Function *MainFunc = M.getFunction("main");
114    if (MainFunc == 0 || MainFunc->isDeclaration())
115      return false;  // No main found, must be a library...
116
117    // Preserve main, internalize all else.
118    ExternalNames.insert(MainFunc->getName());
119  }
120
121  bool Changed = false;
122
123  // Mark all functions not in the api as internal.
124  // FIXME: maybe use private linkage?
125  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
126    if (!I->isDeclaration() &&         // Function must be defined here
127        !I->hasLocalLinkage() &&  // Can't already have internal linkage
128        !ExternalNames.count(I->getName())) {// Not marked to keep external?
129      I->setLinkage(GlobalValue::InternalLinkage);
130      // Remove a callgraph edge from the external node to this function.
131      if (ExternalNode) ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
132      Changed = true;
133      ++NumFunctions;
134      DOUT << "Internalizing func " << I->getName() << "\n";
135    }
136
137  // Never internalize the llvm.used symbol.  It is used to implement
138  // attribute((used)).
139  // FIXME: Shouldn't this just filter on llvm.metadata section??
140  ExternalNames.insert("llvm.used");
141  ExternalNames.insert("llvm.compiler.used");
142
143  // Never internalize anchors used by the machine module info, else the info
144  // won't find them.  (see MachineModuleInfo.)
145  ExternalNames.insert("llvm.dbg.compile_units");
146  ExternalNames.insert("llvm.dbg.global_variables");
147  ExternalNames.insert("llvm.dbg.subprograms");
148  ExternalNames.insert("llvm.global_ctors");
149  ExternalNames.insert("llvm.global_dtors");
150  ExternalNames.insert("llvm.noinline");
151  ExternalNames.insert("llvm.global.annotations");
152
153  // Mark all global variables with initializers that are not in the api as
154  // internal as well.
155  // FIXME: maybe use private linkage?
156  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
157       I != E; ++I)
158    if (!I->isDeclaration() && !I->hasLocalLinkage() &&
159        !ExternalNames.count(I->getName())) {
160      I->setLinkage(GlobalValue::InternalLinkage);
161      Changed = true;
162      ++NumGlobals;
163      DOUT << "Internalized gvar " << I->getName() << "\n";
164    }
165
166  // Mark all aliases that are not in the api as internal as well.
167  for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
168       I != E; ++I)
169    if (!I->isDeclaration() && !I->hasInternalLinkage() &&
170        !ExternalNames.count(I->getName())) {
171      I->setLinkage(GlobalValue::InternalLinkage);
172      Changed = true;
173      ++NumAliases;
174      DOUT << "Internalized alias " << I->getName() << "\n";
175    }
176
177  return Changed;
178}
179
180ModulePass *llvm::createInternalizePass(bool AllButMain) {
181  return new InternalizePass(AllButMain);
182}
183
184ModulePass *llvm::createInternalizePass(const std::vector <const char *> &el) {
185  return new InternalizePass(el);
186}
187