1 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
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
7 //===----------------------------------------------------------------------===//
9 // The StripSymbols transformation implements code stripping. Specifically, it
12 // * names for virtual registers
13 // * symbols for internal globals and functions
14 // * debug information
16 // Note that this transformation makes code much less readable, so it should
17 // only be used in situations where the 'strip' utility would be used, such as
18 // reducing code size or making it harder to reverse engineer code.
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Transforms/IPO/StripSymbols.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/PassManager.h"
30 #include "llvm/IR/TypeFinder.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/Utils/Local.h"
40 class StripSymbols
: public ModulePass
{
43 static char ID
; // Pass identification, replacement for typeid
44 explicit StripSymbols(bool ODI
= false)
45 : ModulePass(ID
), OnlyDebugInfo(ODI
) {
46 initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
49 bool runOnModule(Module
&M
) override
;
51 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
56 class StripNonDebugSymbols
: public ModulePass
{
58 static char ID
; // Pass identification, replacement for typeid
59 explicit StripNonDebugSymbols()
61 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
64 bool runOnModule(Module
&M
) override
;
66 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
71 class StripDebugDeclare
: public ModulePass
{
73 static char ID
; // Pass identification, replacement for typeid
74 explicit StripDebugDeclare()
76 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
79 bool runOnModule(Module
&M
) override
;
81 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
86 class StripDeadDebugInfo
: public ModulePass
{
88 static char ID
; // Pass identification, replacement for typeid
89 explicit StripDeadDebugInfo()
91 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
94 bool runOnModule(Module
&M
) override
;
96 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
102 char StripSymbols::ID
= 0;
103 INITIALIZE_PASS(StripSymbols
, "strip",
104 "Strip all symbols from a module", false, false)
106 ModulePass
*llvm::createStripSymbolsPass(bool OnlyDebugInfo
) {
107 return new StripSymbols(OnlyDebugInfo
);
110 char StripNonDebugSymbols::ID
= 0;
111 INITIALIZE_PASS(StripNonDebugSymbols
, "strip-nondebug",
112 "Strip all symbols, except dbg symbols, from a module",
115 ModulePass
*llvm::createStripNonDebugSymbolsPass() {
116 return new StripNonDebugSymbols();
119 char StripDebugDeclare::ID
= 0;
120 INITIALIZE_PASS(StripDebugDeclare
, "strip-debug-declare",
121 "Strip all llvm.dbg.declare intrinsics", false, false)
123 ModulePass
*llvm::createStripDebugDeclarePass() {
124 return new StripDebugDeclare();
127 char StripDeadDebugInfo::ID
= 0;
128 INITIALIZE_PASS(StripDeadDebugInfo
, "strip-dead-debug-info",
129 "Strip debug info for unused symbols", false, false)
131 ModulePass
*llvm::createStripDeadDebugInfoPass() {
132 return new StripDeadDebugInfo();
135 /// OnlyUsedBy - Return true if V is only used by Usr.
136 static bool OnlyUsedBy(Value
*V
, Value
*Usr
) {
137 for (User
*U
: V
->users())
144 static void RemoveDeadConstant(Constant
*C
) {
145 assert(C
->use_empty() && "Constant is not dead!");
146 SmallPtrSet
<Constant
*, 4> Operands
;
147 for (Value
*Op
: C
->operands())
148 if (OnlyUsedBy(Op
, C
))
149 Operands
.insert(cast
<Constant
>(Op
));
150 if (GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(C
)) {
151 if (!GV
->hasLocalLinkage()) return; // Don't delete non-static globals.
152 GV
->eraseFromParent();
153 } else if (!isa
<Function
>(C
)) {
154 // FIXME: Why does the type of the constant matter here?
155 if (isa
<StructType
>(C
->getType()) || isa
<ArrayType
>(C
->getType()) ||
156 isa
<VectorType
>(C
->getType()))
157 C
->destroyConstant();
160 // If the constant referenced anything, see if we can delete it as well.
161 for (Constant
*O
: Operands
)
162 RemoveDeadConstant(O
);
165 // Strip the symbol table of its names.
167 static void StripSymtab(ValueSymbolTable
&ST
, bool PreserveDbgInfo
) {
168 for (ValueSymbolTable::iterator VI
= ST
.begin(), VE
= ST
.end(); VI
!= VE
; ) {
169 Value
*V
= VI
->getValue();
171 if (!isa
<GlobalValue
>(V
) || cast
<GlobalValue
>(V
)->hasLocalLinkage()) {
172 if (!PreserveDbgInfo
|| !V
->getName().startswith("llvm.dbg"))
173 // Set name to "", removing from symbol table!
179 // Strip any named types of their names.
180 static void StripTypeNames(Module
&M
, bool PreserveDbgInfo
) {
181 TypeFinder StructTypes
;
182 StructTypes
.run(M
, false);
184 for (unsigned i
= 0, e
= StructTypes
.size(); i
!= e
; ++i
) {
185 StructType
*STy
= StructTypes
[i
];
186 if (STy
->isLiteral() || STy
->getName().empty()) continue;
188 if (PreserveDbgInfo
&& STy
->getName().startswith("llvm.dbg"))
195 /// Find values that are marked as llvm.used.
196 static void findUsedValues(GlobalVariable
*LLVMUsed
,
197 SmallPtrSetImpl
<const GlobalValue
*> &UsedValues
) {
198 if (!LLVMUsed
) return;
199 UsedValues
.insert(LLVMUsed
);
201 ConstantArray
*Inits
= cast
<ConstantArray
>(LLVMUsed
->getInitializer());
203 for (unsigned i
= 0, e
= Inits
->getNumOperands(); i
!= e
; ++i
)
204 if (GlobalValue
*GV
=
205 dyn_cast
<GlobalValue
>(Inits
->getOperand(i
)->stripPointerCasts()))
206 UsedValues
.insert(GV
);
209 /// StripSymbolNames - Strip symbol names.
210 static bool StripSymbolNames(Module
&M
, bool PreserveDbgInfo
) {
212 SmallPtrSet
<const GlobalValue
*, 8> llvmUsedValues
;
213 findUsedValues(M
.getGlobalVariable("llvm.used"), llvmUsedValues
);
214 findUsedValues(M
.getGlobalVariable("llvm.compiler.used"), llvmUsedValues
);
216 for (GlobalVariable
&GV
: M
.globals()) {
217 if (GV
.hasLocalLinkage() && llvmUsedValues
.count(&GV
) == 0)
218 if (!PreserveDbgInfo
|| !GV
.getName().startswith("llvm.dbg"))
219 GV
.setName(""); // Internal symbols can't participate in linkage
222 for (Function
&I
: M
) {
223 if (I
.hasLocalLinkage() && llvmUsedValues
.count(&I
) == 0)
224 if (!PreserveDbgInfo
|| !I
.getName().startswith("llvm.dbg"))
225 I
.setName(""); // Internal symbols can't participate in linkage
226 if (auto *Symtab
= I
.getValueSymbolTable())
227 StripSymtab(*Symtab
, PreserveDbgInfo
);
230 // Remove all names from types.
231 StripTypeNames(M
, PreserveDbgInfo
);
236 bool StripSymbols::runOnModule(Module
&M
) {
240 bool Changed
= false;
241 Changed
|= StripDebugInfo(M
);
243 Changed
|= StripSymbolNames(M
, false);
247 bool StripNonDebugSymbols::runOnModule(Module
&M
) {
251 return StripSymbolNames(M
, true);
254 static bool stripDebugDeclareImpl(Module
&M
) {
256 Function
*Declare
= M
.getFunction("llvm.dbg.declare");
257 std::vector
<Constant
*> DeadConstants
;
260 while (!Declare
->use_empty()) {
261 CallInst
*CI
= cast
<CallInst
>(Declare
->user_back());
262 Value
*Arg1
= CI
->getArgOperand(0);
263 Value
*Arg2
= CI
->getArgOperand(1);
264 assert(CI
->use_empty() && "llvm.dbg intrinsic should have void result");
265 CI
->eraseFromParent();
266 if (Arg1
->use_empty()) {
267 if (Constant
*C
= dyn_cast
<Constant
>(Arg1
))
268 DeadConstants
.push_back(C
);
270 RecursivelyDeleteTriviallyDeadInstructions(Arg1
);
272 if (Arg2
->use_empty())
273 if (Constant
*C
= dyn_cast
<Constant
>(Arg2
))
274 DeadConstants
.push_back(C
);
276 Declare
->eraseFromParent();
279 while (!DeadConstants
.empty()) {
280 Constant
*C
= DeadConstants
.back();
281 DeadConstants
.pop_back();
282 if (GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(C
)) {
283 if (GV
->hasLocalLinkage())
284 RemoveDeadConstant(GV
);
286 RemoveDeadConstant(C
);
292 bool StripDebugDeclare::runOnModule(Module
&M
) {
295 return stripDebugDeclareImpl(M
);
298 static bool stripDeadDebugInfoImpl(Module
&M
) {
299 bool Changed
= false;
301 LLVMContext
&C
= M
.getContext();
303 // Find all debug info in F. This is actually overkill in terms of what we
304 // want to do, but we want to try and be as resilient as possible in the face
305 // of potential debug info changes by using the formal interfaces given to us
306 // as much as possible.
310 // For each compile unit, find the live set of global variables/functions and
311 // replace the current list of potentially dead global variables/functions
312 // with the live list.
313 SmallVector
<Metadata
*, 64> LiveGlobalVariables
;
314 DenseSet
<DIGlobalVariableExpression
*> VisitedSet
;
316 std::set
<DIGlobalVariableExpression
*> LiveGVs
;
317 for (GlobalVariable
&GV
: M
.globals()) {
318 SmallVector
<DIGlobalVariableExpression
*, 1> GVEs
;
319 GV
.getDebugInfo(GVEs
);
320 for (auto *GVE
: GVEs
)
324 std::set
<DICompileUnit
*> LiveCUs
;
325 // Any CU referenced from a subprogram is live.
326 for (DISubprogram
*SP
: F
.subprograms()) {
328 LiveCUs
.insert(SP
->getUnit());
331 bool HasDeadCUs
= false;
332 for (DICompileUnit
*DIC
: F
.compile_units()) {
333 // Create our live global variable list.
334 bool GlobalVariableChange
= false;
335 for (auto *DIG
: DIC
->getGlobalVariables()) {
336 if (DIG
->getExpression() && DIG
->getExpression()->isConstant())
339 // Make sure we only visit each global variable only once.
340 if (!VisitedSet
.insert(DIG
).second
)
343 // If a global variable references DIG, the global variable is live.
344 if (LiveGVs
.count(DIG
))
345 LiveGlobalVariables
.push_back(DIG
);
347 GlobalVariableChange
= true;
350 if (!LiveGlobalVariables
.empty())
352 else if (!LiveCUs
.count(DIC
))
355 // If we found dead global variables, replace the current global
356 // variable list with our new live global variable list.
357 if (GlobalVariableChange
) {
358 DIC
->replaceGlobalVariables(MDTuple::get(C
, LiveGlobalVariables
));
362 // Reset lists for the next iteration.
363 LiveGlobalVariables
.clear();
367 // Delete the old node and replace it with a new one
368 NamedMDNode
*NMD
= M
.getOrInsertNamedMetadata("llvm.dbg.cu");
369 NMD
->clearOperands();
370 if (!LiveCUs
.empty()) {
371 for (DICompileUnit
*CU
: LiveCUs
)
380 /// Remove any debug info for global variables/functions in the given module for
381 /// which said global variable/function no longer exists (i.e. is null).
383 /// Debugging information is encoded in llvm IR using metadata. This is designed
384 /// such a way that debug info for symbols preserved even if symbols are
385 /// optimized away by the optimizer. This special pass removes debug info for
387 bool StripDeadDebugInfo::runOnModule(Module
&M
) {
390 return stripDeadDebugInfoImpl(M
);
393 PreservedAnalyses
StripSymbolsPass::run(Module
&M
, ModuleAnalysisManager
&AM
) {
395 StripSymbolNames(M
, false);
396 return PreservedAnalyses::all();
399 PreservedAnalyses
StripNonDebugSymbolsPass::run(Module
&M
,
400 ModuleAnalysisManager
&AM
) {
401 StripSymbolNames(M
, true);
402 return PreservedAnalyses::all();
405 PreservedAnalyses
StripDebugDeclarePass::run(Module
&M
,
406 ModuleAnalysisManager
&AM
) {
407 stripDebugDeclareImpl(M
);
408 return PreservedAnalyses::all();
411 PreservedAnalyses
StripDeadDebugInfoPass::run(Module
&M
,
412 ModuleAnalysisManager
&AM
) {
413 stripDeadDebugInfoImpl(M
);
414 return PreservedAnalyses::all();