1 //===-- Internalize.cpp - Mark functions internal -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass loops over all of the functions and variables in the input module.
10 // If the function or variable does not need to be preserved according to the
11 // client supplied callback, it is marked as internal.
12 //
13 // This transformation would not be legal in a regular compilation, but it gets
14 // extra information from the linker about what is safe.
15 //
16 // For example: Internalizing a function with external linkage. Only if we are
17 // told it is only used from within this module, it is safe to do it.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm/Transforms/IPO/Internalize.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSet.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/GlobPattern.h"
32 #include "llvm/Support/LineIterator.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/IPO.h"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "internalize"
39 
40 STATISTIC(NumAliases, "Number of aliases internalized");
41 STATISTIC(NumFunctions, "Number of functions internalized");
42 STATISTIC(NumGlobals, "Number of global vars internalized");
43 
44 // APIFile - A file which contains a list of symbol glob patterns that should
45 // not be marked external.
46 static cl::opt<std::string>
47     APIFile("internalize-public-api-file", cl::value_desc("filename"),
48             cl::desc("A file containing list of symbol names to preserve"));
49 
50 // APIList - A list of symbol glob patterns that should not be marked internal.
51 static cl::list<std::string>
52     APIList("internalize-public-api-list", cl::value_desc("list"),
53             cl::desc("A list of symbol names to preserve"), cl::CommaSeparated);
54 
55 namespace {
56 // Helper to load an API list to preserve from file and expose it as a functor
57 // for internalization.
58 class PreserveAPIList {
59 public:
60   PreserveAPIList() {
61     if (!APIFile.empty())
62       LoadFile(APIFile);
63     for (StringRef Pattern : APIList)
64       addGlob(Pattern);
65   }
66 
67   bool operator()(const GlobalValue &GV) {
68     return llvm::any_of(
69         ExternalNames, [&](GlobPattern &GP) { return GP.match(GV.getName()); });
70   }
71 
72 private:
73   // Contains the set of symbols loaded from file
74   SmallVector<GlobPattern> ExternalNames;
75 
76   void addGlob(StringRef Pattern) {
77     auto GlobOrErr = GlobPattern::create(Pattern);
78     if (!GlobOrErr) {
79       errs() << "WARNING: when loading pattern: '"
80              << toString(GlobOrErr.takeError()) << "' ignoring";
81       return;
82     }
83     ExternalNames.emplace_back(std::move(*GlobOrErr));
84   }
85 
86   void LoadFile(StringRef Filename) {
87     // Load the APIFile...
88     ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
89         MemoryBuffer::getFile(Filename);
90     if (!BufOrErr) {
91       errs() << "WARNING: Internalize couldn't load file '" << Filename
92              << "'! Continuing as if it's empty.\n";
93       return; // Just continue as if the file were empty
94     }
95     Buf = std::move(*BufOrErr);
96     for (line_iterator I(*Buf, true), E; I != E; ++I)
97       addGlob(*I);
98   }
99 
100   std::shared_ptr<MemoryBuffer> Buf;
101 };
102 } // end anonymous namespace
103 
104 bool InternalizePass::shouldPreserveGV(const GlobalValue &GV) {
105   // Function must be defined here
106   if (GV.isDeclaration())
107     return true;
108 
109   // Available externally is really just a "declaration with a body".
110   if (GV.hasAvailableExternallyLinkage())
111     return true;
112 
113   // Assume that dllexported symbols are referenced elsewhere
114   if (GV.hasDLLExportStorageClass())
115     return true;
116 
117   // As the name suggests, externally initialized variables need preserving as
118   // they would be initialized elsewhere externally.
119   if (const auto *G = dyn_cast<GlobalVariable>(&GV))
120     if (G->isExternallyInitialized())
121       return true;
122 
123   // Already local, has nothing to do.
124   if (GV.hasLocalLinkage())
125     return false;
126 
127   // Check some special cases
128   if (AlwaysPreserved.count(GV.getName()))
129     return true;
130 
131   return MustPreserveGV(GV);
132 }
133 
134 bool InternalizePass::maybeInternalize(
135     GlobalValue &GV, DenseMap<const Comdat *, ComdatInfo> &ComdatMap) {
136   SmallString<0> ComdatName;
137   if (Comdat *C = GV.getComdat()) {
138     // For GlobalAlias, C is the aliasee object's comdat which may have been
139     // redirected. So ComdatMap may not contain C.
140     if (ComdatMap.lookup(C).External)
141       return false;
142 
143     if (auto *GO = dyn_cast<GlobalObject>(&GV)) {
144       // If a comdat with one member is not externally visible, we can drop it.
145       // Otherwise, the comdat can be used to establish dependencies among the
146       // group of sections. Thus we have to keep the comdat but switch it to
147       // nodeduplicate.
148       // Note: nodeduplicate is not necessary for COFF. wasm doesn't support
149       // nodeduplicate.
150       ComdatInfo &Info = ComdatMap.find(C)->second;
151       if (Info.Size == 1)
152         GO->setComdat(nullptr);
153       else if (!IsWasm)
154         C->setSelectionKind(Comdat::NoDeduplicate);
155     }
156 
157     if (GV.hasLocalLinkage())
158       return false;
159   } else {
160     if (GV.hasLocalLinkage())
161       return false;
162 
163     if (shouldPreserveGV(GV))
164       return false;
165   }
166 
167   GV.setVisibility(GlobalValue::DefaultVisibility);
168   GV.setLinkage(GlobalValue::InternalLinkage);
169   return true;
170 }
171 
172 // If GV is part of a comdat and is externally visible, update the comdat size
173 // and keep track of its comdat so that we don't internalize any of its members.
174 void InternalizePass::checkComdat(
175     GlobalValue &GV, DenseMap<const Comdat *, ComdatInfo> &ComdatMap) {
176   Comdat *C = GV.getComdat();
177   if (!C)
178     return;
179 
180   ComdatInfo &Info = ComdatMap.try_emplace(C).first->second;
181   ++Info.Size;
182   if (shouldPreserveGV(GV))
183     Info.External = true;
184 }
185 
186 bool InternalizePass::internalizeModule(Module &M, CallGraph *CG) {
187   bool Changed = false;
188   CallGraphNode *ExternalNode = CG ? CG->getExternalCallingNode() : nullptr;
189 
190   SmallVector<GlobalValue *, 4> Used;
191   collectUsedGlobalVariables(M, Used, false);
192 
193   // Collect comdat size and visiblity information for the module.
194   DenseMap<const Comdat *, ComdatInfo> ComdatMap;
195   if (!M.getComdatSymbolTable().empty()) {
196     for (Function &F : M)
197       checkComdat(F, ComdatMap);
198     for (GlobalVariable &GV : M.globals())
199       checkComdat(GV, ComdatMap);
200     for (GlobalAlias &GA : M.aliases())
201       checkComdat(GA, ComdatMap);
202   }
203 
204   // We must assume that globals in llvm.used have a reference that not even
205   // the linker can see, so we don't internalize them.
206   // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
207   // linker can drop those symbols. If this pass is running as part of LTO,
208   // one might think that it could just drop llvm.compiler.used. The problem
209   // is that even in LTO llvm doesn't see every reference. For example,
210   // we don't see references from function local inline assembly. To be
211   // conservative, we internalize symbols in llvm.compiler.used, but we
212   // keep llvm.compiler.used so that the symbol is not deleted by llvm.
213   for (GlobalValue *V : Used) {
214     AlwaysPreserved.insert(V->getName());
215   }
216 
217   // Never internalize the llvm.used symbol.  It is used to implement
218   // attribute((used)).
219   // FIXME: Shouldn't this just filter on llvm.metadata section??
220   AlwaysPreserved.insert("llvm.used");
221   AlwaysPreserved.insert("llvm.compiler.used");
222 
223   // Never internalize anchors used by the machine module info, else the info
224   // won't find them.  (see MachineModuleInfo.)
225   AlwaysPreserved.insert("llvm.global_ctors");
226   AlwaysPreserved.insert("llvm.global_dtors");
227   AlwaysPreserved.insert("llvm.global.annotations");
228 
229   // Never internalize symbols code-gen inserts.
230   // FIXME: We should probably add this (and the __stack_chk_guard) via some
231   // type of call-back in CodeGen.
232   AlwaysPreserved.insert("__stack_chk_fail");
233   if (Triple(M.getTargetTriple()).isOSAIX())
234     AlwaysPreserved.insert("__ssp_canary_word");
235   else
236     AlwaysPreserved.insert("__stack_chk_guard");
237 
238   // Mark all functions not in the api as internal.
239   IsWasm = Triple(M.getTargetTriple()).isOSBinFormatWasm();
240   for (Function &I : M) {
241     if (!maybeInternalize(I, ComdatMap))
242       continue;
243     Changed = true;
244 
245     if (ExternalNode)
246       // Remove a callgraph edge from the external node to this function.
247       ExternalNode->removeOneAbstractEdgeTo((*CG)[&I]);
248 
249     ++NumFunctions;
250     LLVM_DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");
251   }
252 
253   // Mark all global variables with initializers that are not in the api as
254   // internal as well.
255   for (auto &GV : M.globals()) {
256     if (!maybeInternalize(GV, ComdatMap))
257       continue;
258     Changed = true;
259 
260     ++NumGlobals;
261     LLVM_DEBUG(dbgs() << "Internalized gvar " << GV.getName() << "\n");
262   }
263 
264   // Mark all aliases that are not in the api as internal as well.
265   for (auto &GA : M.aliases()) {
266     if (!maybeInternalize(GA, ComdatMap))
267       continue;
268     Changed = true;
269 
270     ++NumAliases;
271     LLVM_DEBUG(dbgs() << "Internalized alias " << GA.getName() << "\n");
272   }
273 
274   return Changed;
275 }
276 
277 InternalizePass::InternalizePass() : MustPreserveGV(PreserveAPIList()) {}
278 
279 PreservedAnalyses InternalizePass::run(Module &M, ModuleAnalysisManager &AM) {
280   if (!internalizeModule(M, AM.getCachedResult<CallGraphAnalysis>(M)))
281     return PreservedAnalyses::all();
282 
283   PreservedAnalyses PA;
284   PA.preserve<CallGraphAnalysis>();
285   return PA;
286 }
287 
288 namespace {
289 class InternalizeLegacyPass : public ModulePass {
290   // Client supplied callback to control wheter a symbol must be preserved.
291   std::function<bool(const GlobalValue &)> MustPreserveGV;
292 
293 public:
294   static char ID; // Pass identification, replacement for typeid
295 
296   InternalizeLegacyPass() : ModulePass(ID), MustPreserveGV(PreserveAPIList()) {}
297 
298   InternalizeLegacyPass(std::function<bool(const GlobalValue &)> MustPreserveGV)
299       : ModulePass(ID), MustPreserveGV(std::move(MustPreserveGV)) {
300     initializeInternalizeLegacyPassPass(*PassRegistry::getPassRegistry());
301   }
302 
303   bool runOnModule(Module &M) override {
304     if (skipModule(M))
305       return false;
306 
307     CallGraphWrapperPass *CGPass =
308         getAnalysisIfAvailable<CallGraphWrapperPass>();
309     CallGraph *CG = CGPass ? &CGPass->getCallGraph() : nullptr;
310     return internalizeModule(M, MustPreserveGV, CG);
311   }
312 
313   void getAnalysisUsage(AnalysisUsage &AU) const override {
314     AU.setPreservesCFG();
315     AU.addPreserved<CallGraphWrapperPass>();
316   }
317 };
318 }
319 
320 char InternalizeLegacyPass::ID = 0;
321 INITIALIZE_PASS(InternalizeLegacyPass, "internalize",
322                 "Internalize Global Symbols", false, false)
323 
324 ModulePass *llvm::createInternalizePass() {
325   return new InternalizeLegacyPass();
326 }
327 
328 ModulePass *llvm::createInternalizePass(
329     std::function<bool(const GlobalValue &)> MustPreserveGV) {
330   return new InternalizeLegacyPass(std::move(MustPreserveGV));
331 }
332