Internalize.cpp revision 36b56886974eae4f9c5ebc96befd3e7bfe5de338
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 and variables in the input module.
11// If the function or variable is not in the list of external names given to
12// the pass it is marked as internal.
13//
14// This transformation would not be legal in a regular compilation, but it gets
15// extra information from the linker about what is safe.
16//
17// For example: Internalizing a function with external linkage. Only if we are
18// told it is only used from within this module, it is safe to do it.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "internalize"
23#include "llvm/Transforms/IPO.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/CallGraph.h"
27#include "llvm/IR/Module.h"
28#include "llvm/Pass.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Transforms/Utils/GlobalStatus.h"
33#include "llvm/Transforms/Utils/ModuleUtils.h"
34#include <fstream>
35#include <set>
36using namespace llvm;
37
38STATISTIC(NumAliases  , "Number of aliases internalized");
39STATISTIC(NumFunctions, "Number of functions internalized");
40STATISTIC(NumGlobals  , "Number of global vars internalized");
41
42// APIFile - A file which contains a list of symbols that should not be marked
43// external.
44static cl::opt<std::string>
45APIFile("internalize-public-api-file", cl::value_desc("filename"),
46        cl::desc("A file containing list of symbol names to preserve"));
47
48// APIList - A list of symbols that should not be marked internal.
49static cl::list<std::string>
50APIList("internalize-public-api-list", cl::value_desc("list"),
51        cl::desc("A list of symbol names to preserve"),
52        cl::CommaSeparated);
53
54namespace {
55  class InternalizePass : public ModulePass {
56    std::set<std::string> ExternalNames;
57  public:
58    static char ID; // Pass identification, replacement for typeid
59    explicit InternalizePass();
60    explicit InternalizePass(ArrayRef<const char *> ExportList);
61    void LoadFile(const char *Filename);
62    bool runOnModule(Module &M) override;
63
64    void getAnalysisUsage(AnalysisUsage &AU) const override {
65      AU.setPreservesCFG();
66      AU.addPreserved<CallGraphWrapperPass>();
67    }
68  };
69} // end anonymous namespace
70
71char InternalizePass::ID = 0;
72INITIALIZE_PASS(InternalizePass, "internalize",
73                "Internalize Global Symbols", false, false)
74
75InternalizePass::InternalizePass() : ModulePass(ID) {
76  initializeInternalizePassPass(*PassRegistry::getPassRegistry());
77  if (!APIFile.empty())           // If a filename is specified, use it.
78    LoadFile(APIFile.c_str());
79  ExternalNames.insert(APIList.begin(), APIList.end());
80}
81
82InternalizePass::InternalizePass(ArrayRef<const char *> ExportList)
83    : ModulePass(ID) {
84  initializeInternalizePassPass(*PassRegistry::getPassRegistry());
85  for(ArrayRef<const char *>::const_iterator itr = ExportList.begin();
86        itr != ExportList.end(); itr++) {
87    ExternalNames.insert(*itr);
88  }
89}
90
91void InternalizePass::LoadFile(const char *Filename) {
92  // Load the APIFile...
93  std::ifstream In(Filename);
94  if (!In.good()) {
95    errs() << "WARNING: Internalize couldn't load file '" << Filename
96         << "'! Continuing as if it's empty.\n";
97    return; // Just continue as if the file were empty
98  }
99  while (In) {
100    std::string Symbol;
101    In >> Symbol;
102    if (!Symbol.empty())
103      ExternalNames.insert(Symbol);
104  }
105}
106
107static bool shouldInternalize(const GlobalValue &GV,
108                              const std::set<std::string> &ExternalNames) {
109  // Function must be defined here
110  if (GV.isDeclaration())
111    return false;
112
113  // Available externally is really just a "declaration with a body".
114  if (GV.hasAvailableExternallyLinkage())
115    return false;
116
117  // Assume that dllexported symbols are referenced elsewhere
118  if (GV.hasDLLExportStorageClass())
119    return false;
120
121  // Already has internal linkage
122  if (GV.hasLocalLinkage())
123    return false;
124
125  // Marked to keep external?
126  if (ExternalNames.count(GV.getName()))
127    return false;
128
129  return true;
130}
131
132bool InternalizePass::runOnModule(Module &M) {
133  CallGraphWrapperPass *CGPass = getAnalysisIfAvailable<CallGraphWrapperPass>();
134  CallGraph *CG = CGPass ? &CGPass->getCallGraph() : 0;
135  CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : 0;
136  bool Changed = false;
137
138  SmallPtrSet<GlobalValue *, 8> Used;
139  collectUsedGlobalVariables(M, Used, false);
140
141  // We must assume that globals in llvm.used have a reference that not even
142  // the linker can see, so we don't internalize them.
143  // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
144  // linker can drop those symbols. If this pass is running as part of LTO,
145  // one might think that it could just drop llvm.compiler.used. The problem
146  // is that even in LTO llvm doesn't see every reference. For example,
147  // we don't see references from function local inline assembly. To be
148  // conservative, we internalize symbols in llvm.compiler.used, but we
149  // keep llvm.compiler.used so that the symbol is not deleted by llvm.
150  for (SmallPtrSet<GlobalValue *, 8>::iterator I = Used.begin(), E = Used.end();
151       I != E; ++I) {
152    GlobalValue *V = *I;
153    ExternalNames.insert(V->getName());
154  }
155
156  // Mark all functions not in the api as internal.
157  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
158    if (!shouldInternalize(*I, ExternalNames))
159      continue;
160
161    I->setLinkage(GlobalValue::InternalLinkage);
162
163    if (ExternalNode)
164      // Remove a callgraph edge from the external node to this function.
165      ExternalNode->removeOneAbstractEdgeTo((*CG)[I]);
166
167    Changed = true;
168    ++NumFunctions;
169    DEBUG(dbgs() << "Internalizing func " << I->getName() << "\n");
170  }
171
172  // Never internalize the llvm.used symbol.  It is used to implement
173  // attribute((used)).
174  // FIXME: Shouldn't this just filter on llvm.metadata section??
175  ExternalNames.insert("llvm.used");
176  ExternalNames.insert("llvm.compiler.used");
177
178  // Never internalize anchors used by the machine module info, else the info
179  // won't find them.  (see MachineModuleInfo.)
180  ExternalNames.insert("llvm.global_ctors");
181  ExternalNames.insert("llvm.global_dtors");
182  ExternalNames.insert("llvm.global.annotations");
183
184  // Never internalize symbols code-gen inserts.
185  // FIXME: We should probably add this (and the __stack_chk_guard) via some
186  // type of call-back in CodeGen.
187  ExternalNames.insert("__stack_chk_fail");
188  ExternalNames.insert("__stack_chk_guard");
189
190  // Mark all global variables with initializers that are not in the api as
191  // internal as well.
192  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
193       I != E; ++I) {
194    if (!shouldInternalize(*I, ExternalNames))
195      continue;
196
197    I->setLinkage(GlobalValue::InternalLinkage);
198    Changed = true;
199    ++NumGlobals;
200    DEBUG(dbgs() << "Internalized gvar " << I->getName() << "\n");
201  }
202
203  // Mark all aliases that are not in the api as internal as well.
204  for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
205       I != E; ++I) {
206    if (!shouldInternalize(*I, ExternalNames))
207      continue;
208
209    I->setLinkage(GlobalValue::InternalLinkage);
210    Changed = true;
211    ++NumAliases;
212    DEBUG(dbgs() << "Internalized alias " << I->getName() << "\n");
213  }
214
215  return Changed;
216}
217
218ModulePass *llvm::createInternalizePass() { return new InternalizePass(); }
219
220ModulePass *llvm::createInternalizePass(ArrayRef<const char *> ExportList) {
221  return new InternalizePass(ExportList);
222}
223