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");
41
42namespace {
43// Helper to load an API list to preserve from file and expose it as a functor
44// for internalization.
45class PreserveAPIList {
46public:
47 PreserveAPIList(const IPOOptions &Opts) {
48 if (!Opts.internalize_public_api_file.empty())
49 LoadFile(Opts.internalize_public_api_file);
50 for (StringRef Pattern : Opts.internalize_public_api_list)
51 addGlob(Pattern);
52 }
53
54 bool operator()(const GlobalValue &GV) {
55 return llvm::any_of(
56 ExternalNames, [&](GlobPattern &GP) { return GP.match(GV.getName()); });
57 }
58
59private:
60 // Contains the set of symbols loaded from file
61 SmallVector<GlobPattern> ExternalNames;
62
63 void addGlob(StringRef Pattern) {
64 auto GlobOrErr = GlobPattern::create(Pattern);
65 if (!GlobOrErr) {
66 errs() << "WARNING: when loading pattern: '"
67 << toString(GlobOrErr.takeError()) << "' ignoring";
68 return;
69 }
70 ExternalNames.emplace_back(std::move(*GlobOrErr));
71 }
72
73 void LoadFile(StringRef Filename) {
74 // Load the APIFile...
75 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
77 if (!BufOrErr) {
78 errs() << "WARNING: Internalize couldn't load file '" << Filename
79 << "'! Continuing as if it's empty.\n";
80 return; // Just continue as if the file were empty
81 }
82 Buf = std::move(*BufOrErr);
83 for (line_iterator I(*Buf, true), E; I != E; ++I)
84 addGlob(*I);
85 }
86
87 std::shared_ptr<MemoryBuffer> Buf;
88};
89} // end anonymous namespace
90
91bool InternalizePass::shouldPreserveGV(const GlobalValue &GV) {
92 // Function must be defined here
93 if (GV.isDeclaration())
94 return true;
95
96 // Available externally is really just a "declaration with a body".
98 return true;
99
100 // Assume that dllexported symbols are referenced elsewhere
102 return true;
103
104 // As the name suggests, externally initialized variables need preserving as
105 // they would be initialized elsewhere externally.
106 if (const auto *G = dyn_cast<GlobalVariable>(&GV))
107 if (G->isExternallyInitialized())
108 return true;
109
110 // Already local, has nothing to do.
111 if (GV.hasLocalLinkage())
112 return false;
113
114 // Check some special cases
115 if (AlwaysPreserved.count(GV.getName()))
116 return true;
117
118 return MustPreserveGV(GV);
119}
120
121bool InternalizePass::maybeInternalize(
123 if (Comdat *C = GV.getComdat()) {
124 // For GlobalAlias, C is the aliasee object's comdat which may have been
125 // redirected. So ComdatMap may not contain C.
126 if (ComdatMap.lookup(C).External)
127 return false;
128
129 if (auto *GO = dyn_cast<GlobalObject>(&GV)) {
130 // If a comdat with one member is not externally visible, we can drop it.
131 // Otherwise, the comdat can be used to establish dependencies among the
132 // group of sections. Thus we have to keep the comdat but switch it to
133 // nodeduplicate.
134 // Note: nodeduplicate is not necessary for COFF. wasm doesn't support
135 // nodeduplicate.
136 ComdatInfo &Info = ComdatMap.find(C)->second;
137 if (Info.Size == 1)
138 GO->setComdat(nullptr);
139 else if (!IsWasm)
140 C->setSelectionKind(Comdat::NoDeduplicate);
141 }
142
143 if (GV.hasLocalLinkage())
144 return false;
145 } else {
146 if (GV.hasLocalLinkage())
147 return false;
148
149 if (shouldPreserveGV(GV))
150 return false;
151 }
152
155 return true;
156}
157
158// If GV is part of a comdat and is externally visible, update the comdat size
159// and keep track of its comdat so that we don't internalize any of its members.
160void InternalizePass::checkComdat(
162 Comdat *C = GV.getComdat();
163 if (!C)
164 return;
165
166 ComdatInfo &Info = ComdatMap[C];
167 ++Info.Size;
168 if (shouldPreserveGV(GV))
169 Info.External = true;
170}
171
173 bool Changed = false;
174
176 collectUsedGlobalVariables(M, Used, false);
177
178 // Collect comdat size and visiblity information for the module.
180 if (!M.getComdatSymbolTable().empty()) {
181 for (Function &F : M)
182 checkComdat(F, ComdatMap);
183 for (GlobalVariable &GV : M.globals())
184 checkComdat(GV, ComdatMap);
185 for (GlobalAlias &GA : M.aliases())
186 checkComdat(GA, ComdatMap);
187 }
188
189 // We must assume that globals in llvm.used have a reference that not even
190 // the linker can see, so we don't internalize them.
191 // For llvm.compiler.used the situation is a bit fuzzy. The assembler and
192 // linker can drop those symbols. If this pass is running as part of LTO,
193 // one might think that it could just drop llvm.compiler.used. The problem
194 // is that even in LTO llvm doesn't see every reference. For example,
195 // we don't see references from function local inline assembly. To be
196 // conservative, we internalize symbols in llvm.compiler.used, but we
197 // keep llvm.compiler.used so that the symbol is not deleted by llvm.
198 for (GlobalValue *V : Used) {
199 AlwaysPreserved.insert(V->getName());
200 }
201
202 // Never internalize the llvm.used symbol. It is used to implement
203 // attribute((used)).
204 // FIXME: Shouldn't this just filter on llvm.metadata section??
205 AlwaysPreserved.insert("llvm.used");
206 AlwaysPreserved.insert("llvm.compiler.used");
207
208 // Never internalize anchors used by the machine module info, else the info
209 // won't find them. (see MachineModuleInfo.)
210 AlwaysPreserved.insert("llvm.global_ctors");
211 AlwaysPreserved.insert("llvm.global_dtors");
212 AlwaysPreserved.insert("llvm.global.annotations");
213
214 // Never internalize symbols code-gen inserts.
215 // FIXME: We should probably add this (and the __stack_chk_guard) via some
216 // type of call-back in CodeGen.
217 AlwaysPreserved.insert("__stack_chk_fail");
218 if (M.getTargetTriple().isOSAIX())
219 AlwaysPreserved.insert("__ssp_canary_word");
220 else
221 AlwaysPreserved.insert("__stack_chk_guard");
222
223 // Preserve the RPC interface for GPU host callbacks when internalizing.
224 if (M.getTargetTriple().isNVPTX())
225 AlwaysPreserved.insert("__llvm_rpc_client");
226
227 // Mark all functions not in the api as internal.
228 IsWasm = M.getTargetTriple().isOSBinFormatWasm();
229 for (Function &I : M) {
230 if (!maybeInternalize(I, ComdatMap))
231 continue;
232 Changed = true;
233
234 ++NumFunctions;
235 LLVM_DEBUG(dbgs() << "Internalizing func " << I.getName() << "\n");
236 }
237
238 // Mark all global variables with initializers that are not in the api as
239 // internal as well.
240 for (auto &GV : M.globals()) {
241 if (!maybeInternalize(GV, ComdatMap))
242 continue;
243 Changed = true;
244
245 ++NumGlobals;
246 LLVM_DEBUG(dbgs() << "Internalized gvar " << GV.getName() << "\n");
247 }
248
249 // Mark all aliases that are not in the api as internal as well.
250 for (auto &GA : M.aliases()) {
251 if (!maybeInternalize(GA, ComdatMap))
252 continue;
253 Changed = true;
254
255 ++NumAliases;
256 LLVM_DEBUG(dbgs() << "Internalized alias " << GA.getName() << "\n");
257 }
258
259 return Changed;
260}
261
263 bool Changed =
264 MustPreserveGV
266 : llvm::internalizeModule(M, PreserveAPIList(getIPOOptions(M)));
267 if (!Changed)
268 return PreservedAnalyses::all();
269
273 return PA;
274}
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:171
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:152
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
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:36
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