LLVM 24.0.0git
Internalize.cpp
Go to the documentation of this file.
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
22#include "IPOOptions.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/StringSet.h"
26#include "llvm/IR/Module.h"
27#include "llvm/Support/Debug.h"
33#include "llvm/Transforms/IPO.h"
34using namespace llvm;
35
36#define DEBUG_TYPE "internalize"
37
38STATISTIC(NumAliases, "Number of aliases internalized");
39STATISTIC(NumFunctions, "Number of functions internalized");
40STATISTIC(NumGlobals, "Number of global vars internalized");
41STATISTIC(NumIFuncs, "Number of ifuncs internalized");
42
43namespace {
44// Helper to load an API list to preserve from file and expose it as a functor
45// for internalization.
46class PreserveAPIList {
47public:
48 PreserveAPIList(const IPOOptions &Opts) {
49 if (!Opts.internalize_public_api_file.empty())
50 LoadFile(Opts.internalize_public_api_file);
51 for (StringRef Pattern : Opts.internalize_public_api_list)
52 addGlob(Pattern);
53 }
54
55 bool operator()(const GlobalValue &GV) {
56 return llvm::any_of(
57 ExternalNames, [&](GlobPattern &GP) { return GP.match(GV.getName()); });
58 }
59
60private:
61 // Contains the set of symbols loaded from file
62 SmallVector<GlobPattern> ExternalNames;
63
64 void addGlob(StringRef Pattern) {
65 auto GlobOrErr = GlobPattern::create(Pattern);
66 if (!GlobOrErr) {
67 errs() << "WARNING: when loading pattern: '"
68 << toString(GlobOrErr.takeError()) << "' ignoring";
69 return;
70 }
71 ExternalNames.emplace_back(std::move(*GlobOrErr));
72 }
73
74 void LoadFile(StringRef Filename) {
75 // Load the APIFile...
76 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
78 if (!BufOrErr) {
79 errs() << "WARNING: Internalize couldn't load file '" << Filename
80 << "'! Continuing as if it's empty.\n";
81 return; // Just continue as if the file were empty
82 }
83 Buf = std::move(*BufOrErr);
84 for (line_iterator I(*Buf, true), E; I != E; ++I)
85 addGlob(*I);
86 }
87
88 std::shared_ptr<MemoryBuffer> Buf;
89};
90} // end anonymous namespace
91
92bool InternalizePass::shouldPreserveGV(const GlobalValue &GV) {
93 // Function must be defined here
94 if (GV.isDeclaration())
95 return true;
96
97 // Available externally is really just a "declaration with a body".
99 return true;
100
101 // Assume that dllexported symbols are referenced elsewhere
103 return true;
104
105 // As the name suggests, externally initialized variables need preserving as
106 // they would be initialized elsewhere externally.
107 if (const auto *G = dyn_cast<GlobalVariable>(&GV))
108 if (G->isExternallyInitialized())
109 return true;
110
111 // Already local, has nothing to do.
112 if (GV.hasLocalLinkage())
113 return false;
114
115 // Check some special cases
116 if (AlwaysPreserved.count(GV.getName()))
117 return true;
118
119 return MustPreserveGV(GV);
120}
121
122bool InternalizePass::maybeInternalize(
124 if (Comdat *C = GV.getComdat()) {
125 // For GlobalAlias, C is the aliasee object's comdat which may have been
126 // redirected. So ComdatMap may not contain C.
127 if (ComdatMap.lookup(C).External)
128 return false;
129
130 if (auto *GO = dyn_cast<GlobalObject>(&GV)) {
131 // If a comdat with one member is not externally visible, we can drop it.
132 // Otherwise, the comdat can be used to establish dependencies among the
133 // group of sections. Thus we have to keep the comdat but switch it to
134 // nodeduplicate.
135 // Note: nodeduplicate is not necessary for COFF. wasm doesn't support
136 // nodeduplicate.
137 ComdatInfo &Info = ComdatMap.find(C)->second;
138 if (Info.Size == 1)
139 GO->setComdat(nullptr);
140 else if (!IsWasm)
141 C->setSelectionKind(Comdat::NoDeduplicate);
142 }
143
144 if (GV.hasLocalLinkage())
145 return false;
146 } else {
147 if (GV.hasLocalLinkage())
148 return false;
149
150 if (shouldPreserveGV(GV))
151 return false;
152 }
153
156 return true;
157}
158
159// If GV is part of a comdat and is externally visible, update the comdat size
160// and keep track of its comdat so that we don't internalize any of its members.
161void InternalizePass::checkComdat(
163 Comdat *C = GV.getComdat();
164 if (!C)
165 return;
166
167 ComdatInfo &Info = ComdatMap[C];
168 ++Info.Size;
169 if (shouldPreserveGV(GV))
170 Info.External = true;
171}
172
174 bool Changed = false;
175
177 collectUsedGlobalVariables(M, Used, false);
178
179 // Collect comdat size and visiblity information for the module.
181 if (!M.getComdatSymbolTable().empty()) {
182 for (Function &F : M)
183 checkComdat(F, ComdatMap);
184 for (GlobalVariable &GV : M.globals())
185 checkComdat(GV, ComdatMap);
186 for (GlobalAlias &GA : M.aliases())
187 checkComdat(GA, ComdatMap);
188 }
189
190 // We must assume that globals in llvm.used have a reference that not even
191 // the linker can see, so we don't internalize them.
192 // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
193 // linker can drop those symbols. If this pass is running as part of LTO,
194 // one might think that it could just drop llvm.compiler.used. The problem
195 // is that even in LTO llvm doesn't see every reference. For example,
196 // we don't see references from function local inline assembly. To be
197 // conservative, we internalize symbols in llvm.compiler.used, but we
198 // keep llvm.compiler.used so that the symbol is not deleted by llvm.
199 for (GlobalValue *V : Used) {
200 AlwaysPreserved.insert(V->getName());
201 }
202
203 // Never internalize the llvm.used symbol. It is used to implement
204 // attribute((used)).
205 // FIXME: Shouldn't this just filter on llvm.metadata section??
206 AlwaysPreserved.insert("llvm.used");
207 AlwaysPreserved.insert("llvm.compiler.used");
208
209 // Never internalize anchors used by the machine module info, else the info
210 // won't find them. (see MachineModuleInfo.)
211 AlwaysPreserved.insert("llvm.global_ctors");
212 AlwaysPreserved.insert("llvm.global_dtors");
213 AlwaysPreserved.insert("llvm.global.annotations");
214
215 // Never internalize symbols code-gen inserts.
216 // FIXME: We should probably add this (and the __stack_chk_guard) via some
217 // type of call-back in CodeGen.
218 AlwaysPreserved.insert("__stack_chk_fail");
219 if (M.getTargetTriple().isOSAIX())
220 AlwaysPreserved.insert("__ssp_canary_word");
221 else
222 AlwaysPreserved.insert("__stack_chk_guard");
223
224 // Preserve the RPC interface for GPU host callbacks when internalizing.
225 if (M.getTargetTriple().isNVPTX())
226 AlwaysPreserved.insert("__llvm_rpc_client");
227
228 // Mark all functions not in the api as internal.
229 IsWasm = M.getTargetTriple().isOSBinFormatWasm();
230 for (Function &I : M) {
231 if (!maybeInternalize(I, ComdatMap))
232 continue;
233 Changed = true;
234
235 ++NumFunctions;
236 LLVM_DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");
237 }
238
239 // Mark all global variables with initializers that are not in the api as
240 // internal as well.
241 for (auto &GV : M.globals()) {
242 if (!maybeInternalize(GV, ComdatMap))
243 continue;
244 Changed = true;
245
246 ++NumGlobals;
247 LLVM_DEBUG(dbgs() << "Internalized gvar " << GV.getName() << "\n");
248 }
249
250 // Mark all aliases that are not in the api as internal as well.
251 for (auto &GA : M.aliases()) {
252 if (!maybeInternalize(GA, ComdatMap))
253 continue;
254 Changed = true;
255
256 ++NumAliases;
257 LLVM_DEBUG(dbgs() << "Internalized alias " << GA.getName() << "\n");
258 }
259
260 // Mark all ifuncs that are not in the api as internal as well.
261 for (auto &GI : M.ifuncs()) {
262 if (!maybeInternalize(GI, ComdatMap))
263 continue;
264 Changed = true;
265
266 ++NumIFuncs;
267 LLVM_DEBUG(dbgs() << "Internalized ifunc " << GI.getName() << "\n");
268 }
269
270 return Changed;
271}
272
274 bool Changed =
275 MustPreserveGV
277 : llvm::internalizeModule(M, PreserveAPIList(getIPOOptions(M)));
278 if (!Changed)
279 return PreservedAnalyses::all();
280
284 return PA;
285}
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static constexpr StringLiteral Filename
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
StringSet - A set-like wrapper for the StringMap.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
static LLVM_ABI Expected< GlobPattern > create(StringRef Pat, std::optional< size_t > MaxSubPatterns={}, bool SlashAgnostic=false)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:408
bool hasLocalLinkage() const
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:274
void setLinkage(LinkageTypes LT)
bool hasDLLExportStorageClass() const
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
void setVisibility(VisibilityTypes V)
bool hasAvailableExternallyLinkage() const
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
LLVM_ABI bool internalizeModule(Module &TheModule)
Run the internalizer on TheModule, returns true if any changes was made.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
constexpr MCPhysReg GP
This is an optimization pass for GlobalISel generic memory operations.
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV)
Helper function to internalize functions and variables in a Module.
Definition Internalize.h:79
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:44
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:991