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 #include "llvm/Transforms/IPO/Internalize.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/GlobalStatus.h"
34 #include "llvm/Transforms/Utils/ModuleUtils.h"
35 #include <fstream>
36 #include <set>
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "internalize"
40 
41 STATISTIC(NumAliases, "Number of aliases internalized");
42 STATISTIC(NumFunctions, "Number of functions internalized");
43 STATISTIC(NumGlobals, "Number of global vars internalized");
44 
45 // APIFile - A file which contains a list of symbols that should not be marked
46 // external.
47 static cl::opt<std::string>
48     APIFile("internalize-public-api-file", cl::value_desc("filename"),
49             cl::desc("A file containing list of symbol names to preserve"));
50 
51 // APIList - A list of symbols that should not be marked internal.
52 static cl::list<std::string>
53     APIList("internalize-public-api-list", cl::value_desc("list"),
54             cl::desc("A list of symbol names to preserve"), cl::CommaSeparated);
55 
56 namespace {
57 
58 // Helper to load an API list to preserve from file and expose it as a functor
59 // for internalization.
60 class PreserveAPIList {
61 public:
62   PreserveAPIList() {
63     if (!APIFile.empty())
64       LoadFile(APIFile);
65     ExternalNames.insert(APIList.begin(), APIList.end());
66   }
67 
68   bool operator()(const GlobalValue &GV) {
69     return ExternalNames.count(GV.getName());
70   }
71 
72 private:
73   // Contains the set of symbols loaded from file
74   StringSet<> ExternalNames;
75 
76   void LoadFile(StringRef Filename) {
77     // Load the APIFile...
78     std::ifstream In(Filename.data());
79     if (!In.good()) {
80       errs() << "WARNING: Internalize couldn't load file '" << Filename
81              << "'! Continuing as if it's empty.\n";
82       return; // Just continue as if the file were empty
83     }
84     while (In) {
85       std::string Symbol;
86       In >> Symbol;
87       if (!Symbol.empty())
88         ExternalNames.insert(Symbol);
89     }
90   }
91 };
92 
93 // Internalization exposed as a pass
94 class InternalizePass : public ModulePass {
95   // Client supplied callback to control wheter a symbol must be preserved.
96   std::function<bool(const GlobalValue &)> MustPreserveGV;
97 
98 public:
99   static char ID; // Pass identification, replacement for typeid
100 
101   InternalizePass() : ModulePass(ID), MustPreserveGV(PreserveAPIList()) {}
102 
103   InternalizePass(std::function<bool(const GlobalValue &)> MustPreserveGV)
104       : ModulePass(ID), MustPreserveGV(std::move(MustPreserveGV)) {
105     initializeInternalizePassPass(*PassRegistry::getPassRegistry());
106   }
107 
108   bool runOnModule(Module &M) override {
109     CallGraphWrapperPass *CGPass =
110         getAnalysisIfAvailable<CallGraphWrapperPass>();
111     CallGraph *CG = CGPass ? &CGPass->getCallGraph() : nullptr;
112     return internalizeModule(M, MustPreserveGV, CG);
113   }
114 
115   void getAnalysisUsage(AnalysisUsage &AU) const override {
116     AU.setPreservesCFG();
117     AU.addPreserved<CallGraphWrapperPass>();
118   }
119 };
120 
121 // Helper class to perform internalization.
122 class Internalizer {
123   // Client supplied callback to control wheter a symbol must be preserved.
124   const std::function<bool(const GlobalValue &)> &MustPreserveGV;
125 
126   // Set of symbols private to the compiler that this pass should not touch.
127   StringSet<> AlwaysPreserved;
128 
129   // Return false if we're allowed to internalize this GV.
130   bool ShouldPreserveGV(const GlobalValue &GV) {
131     // Function must be defined here
132     if (GV.isDeclaration())
133       return true;
134 
135     // Available externally is really just a "declaration with a body".
136     if (GV.hasAvailableExternallyLinkage())
137       return true;
138 
139     // Assume that dllexported symbols are referenced elsewhere
140     if (GV.hasDLLExportStorageClass())
141       return true;
142 
143     // Already local, has nothing to do.
144     if (GV.hasLocalLinkage())
145       return false;
146 
147     // Check some special cases
148     if (AlwaysPreserved.count(GV.getName()))
149       return true;
150 
151     return MustPreserveGV(GV);
152   }
153 
154   bool maybeInternalize(GlobalValue &GV,
155                         const std::set<const Comdat *> &ExternalComdats);
156   void checkComdatVisibility(GlobalValue &GV,
157                              std::set<const Comdat *> &ExternalComdats);
158 
159 public:
160   Internalizer(const std::function<bool(const GlobalValue &)> &MustPreserveGV)
161       : MustPreserveGV(MustPreserveGV) {}
162 
163   /// Run the internalizer on \p TheModule, returns true if any changes was
164   /// made.
165   ///
166   /// If the CallGraph \p CG is supplied, it will be updated when
167   /// internalizing a function (by removing any edge from the "external node")
168   bool internalizeModule(Module &TheModule, CallGraph *CG = nullptr);
169 };
170 
171 // Internalize GV if it is possible to do so, i.e. it is not externally visible
172 // and is not a member of an externally visible comdat.
173 bool Internalizer::maybeInternalize(
174     GlobalValue &GV, const std::set<const Comdat *> &ExternalComdats) {
175   if (Comdat *C = GV.getComdat()) {
176     if (ExternalComdats.count(C))
177       return false;
178 
179     // If a comdat is not externally visible we can drop it.
180     if (auto GO = dyn_cast<GlobalObject>(&GV))
181       GO->setComdat(nullptr);
182 
183     if (GV.hasLocalLinkage())
184       return false;
185   } else {
186     if (GV.hasLocalLinkage())
187       return false;
188 
189     if (ShouldPreserveGV(GV))
190       return false;
191   }
192 
193   GV.setVisibility(GlobalValue::DefaultVisibility);
194   GV.setLinkage(GlobalValue::InternalLinkage);
195   return true;
196 }
197 
198 // If GV is part of a comdat and is externally visible, keep track of its
199 // comdat so that we don't internalize any of its members.
200 void Internalizer::checkComdatVisibility(
201     GlobalValue &GV, std::set<const Comdat *> &ExternalComdats) {
202   Comdat *C = GV.getComdat();
203   if (!C)
204     return;
205 
206   if (ShouldPreserveGV(GV))
207     ExternalComdats.insert(C);
208 }
209 
210 bool Internalizer::internalizeModule(Module &M, CallGraph *CG) {
211   bool Changed = false;
212   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : nullptr;
213 
214   SmallPtrSet<GlobalValue *, 8> Used;
215   collectUsedGlobalVariables(M, Used, false);
216 
217   // Collect comdat visiblity information for the module.
218   std::set<const Comdat *> ExternalComdats;
219   if (!M.getComdatSymbolTable().empty()) {
220     for (Function &F : M)
221       checkComdatVisibility(F, ExternalComdats);
222     for (GlobalVariable &GV : M.globals())
223       checkComdatVisibility(GV, ExternalComdats);
224     for (GlobalAlias &GA : M.aliases())
225       checkComdatVisibility(GA, ExternalComdats);
226   }
227 
228   // We must assume that globals in llvm.used have a reference that not even
229   // the linker can see, so we don't internalize them.
230   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
231   // linker can drop those symbols. If this pass is running as part of LTO,
232   // one might think that it could just drop llvm.compiler.used. The problem
233   // is that even in LTO llvm doesn't see every reference. For example,
234   // we don't see references from function local inline assembly. To be
235   // conservative, we internalize symbols in llvm.compiler.used, but we
236   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
237   for (GlobalValue *V : Used) {
238     AlwaysPreserved.insert(V->getName());
239   }
240 
241   // Mark all functions not in the api as internal.
242   for (Function &I : M) {
243     if (!maybeInternalize(I, ExternalComdats))
244       continue;
245     Changed = true;
246 
247     if (ExternalNode)
248       // Remove a callgraph edge from the external node to this function.
249       ExternalNode->removeOneAbstractEdgeTo((*CG)[&I]);
250 
251     ++NumFunctions;
252     DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");
253   }
254 
255   // Never internalize the llvm.used symbol.  It is used to implement
256   // attribute((used)).
257   // FIXME: Shouldn't this just filter on llvm.metadata section??
258   AlwaysPreserved.insert("llvm.used");
259   AlwaysPreserved.insert("llvm.compiler.used");
260 
261   // Never internalize anchors used by the machine module info, else the info
262   // won't find them.  (see MachineModuleInfo.)
263   AlwaysPreserved.insert("llvm.global_ctors");
264   AlwaysPreserved.insert("llvm.global_dtors");
265   AlwaysPreserved.insert("llvm.global.annotations");
266 
267   // Never internalize symbols code-gen inserts.
268   // FIXME: We should probably add this (and the __stack_chk_guard) via some
269   // type of call-back in CodeGen.
270   AlwaysPreserved.insert("__stack_chk_fail");
271   AlwaysPreserved.insert("__stack_chk_guard");
272 
273   // Mark all global variables with initializers that are not in the api as
274   // internal as well.
275   for (auto &GV : M.globals()) {
276     if (!maybeInternalize(GV, ExternalComdats))
277       continue;
278     Changed = true;
279 
280     ++NumGlobals;
281     DEBUG(dbgs() << "Internalized gvar " << GV.getName() << "\n");
282   }
283 
284   // Mark all aliases that are not in the api as internal as well.
285   for (auto &GA : M.aliases()) {
286     if (!maybeInternalize(GA, ExternalComdats))
287       continue;
288     Changed = true;
289 
290     ++NumAliases;
291     DEBUG(dbgs() << "Internalized alias " << GA.getName() << "\n");
292   }
293 
294   return Changed;
295 }
296 
297 } // end anonymous namespace
298 
299 char InternalizePass::ID = 0;
300 INITIALIZE_PASS(InternalizePass, "internalize", "Internalize Global Symbols",
301                 false, false)
302 
303 /// Public API below
304 
305 bool llvm::internalizeModule(
306     Module &TheModule,
307     const std::function<bool(const GlobalValue &)> &MustPreserveGV,
308     CallGraph *CG) {
309   return Internalizer(MustPreserveGV).internalizeModule(TheModule, CG);
310 }
311 
312 ModulePass *llvm::createInternalizePass() { return new InternalizePass(); }
313 
314 ModulePass *llvm::createInternalizePass(
315     std::function<bool(const GlobalValue &)> MustPreserveGV) {
316   return new InternalizePass(std::move(MustPreserveGV));
317 }
318