1 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
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 // The StripSymbols transformation implements code stripping. Specifically, it
11 // can delete:
12 //
13 // * names for virtual registers
14 // * symbols for internal globals and functions
15 // * debug information
16 //
17 // Note that this transformation makes code much less readable, so it should
18 // only be used in situations where the 'strip' utility would be used, such as
19 // reducing code size or making it harder to reverse engineer code.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/TypeFinder.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 using namespace llvm;
35
36 namespace {
37 class StripSymbols : public ModulePass {
38 bool OnlyDebugInfo;
39 public:
40 static char ID; // Pass identification, replacement for typeid
StripSymbols(bool ODI=false)41 explicit StripSymbols(bool ODI = false)
42 : ModulePass(ID), OnlyDebugInfo(ODI) {
43 initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
44 }
45
46 bool runOnModule(Module &M) override;
47
getAnalysisUsage(AnalysisUsage & AU) const48 void getAnalysisUsage(AnalysisUsage &AU) const override {
49 AU.setPreservesAll();
50 }
51 };
52
53 class StripNonDebugSymbols : public ModulePass {
54 public:
55 static char ID; // Pass identification, replacement for typeid
StripNonDebugSymbols()56 explicit StripNonDebugSymbols()
57 : ModulePass(ID) {
58 initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
59 }
60
61 bool runOnModule(Module &M) override;
62
getAnalysisUsage(AnalysisUsage & AU) const63 void getAnalysisUsage(AnalysisUsage &AU) const override {
64 AU.setPreservesAll();
65 }
66 };
67
68 class StripDebugDeclare : public ModulePass {
69 public:
70 static char ID; // Pass identification, replacement for typeid
StripDebugDeclare()71 explicit StripDebugDeclare()
72 : ModulePass(ID) {
73 initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
74 }
75
76 bool runOnModule(Module &M) override;
77
getAnalysisUsage(AnalysisUsage & AU) const78 void getAnalysisUsage(AnalysisUsage &AU) const override {
79 AU.setPreservesAll();
80 }
81 };
82
83 class StripDeadDebugInfo : public ModulePass {
84 public:
85 static char ID; // Pass identification, replacement for typeid
StripDeadDebugInfo()86 explicit StripDeadDebugInfo()
87 : ModulePass(ID) {
88 initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
89 }
90
91 bool runOnModule(Module &M) override;
92
getAnalysisUsage(AnalysisUsage & AU) const93 void getAnalysisUsage(AnalysisUsage &AU) const override {
94 AU.setPreservesAll();
95 }
96 };
97 }
98
99 char StripSymbols::ID = 0;
100 INITIALIZE_PASS(StripSymbols, "strip",
101 "Strip all symbols from a module", false, false)
102
createStripSymbolsPass(bool OnlyDebugInfo)103 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
104 return new StripSymbols(OnlyDebugInfo);
105 }
106
107 char StripNonDebugSymbols::ID = 0;
108 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
109 "Strip all symbols, except dbg symbols, from a module",
110 false, false)
111
createStripNonDebugSymbolsPass()112 ModulePass *llvm::createStripNonDebugSymbolsPass() {
113 return new StripNonDebugSymbols();
114 }
115
116 char StripDebugDeclare::ID = 0;
117 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
118 "Strip all llvm.dbg.declare intrinsics", false, false)
119
createStripDebugDeclarePass()120 ModulePass *llvm::createStripDebugDeclarePass() {
121 return new StripDebugDeclare();
122 }
123
124 char StripDeadDebugInfo::ID = 0;
125 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
126 "Strip debug info for unused symbols", false, false)
127
createStripDeadDebugInfoPass()128 ModulePass *llvm::createStripDeadDebugInfoPass() {
129 return new StripDeadDebugInfo();
130 }
131
132 /// OnlyUsedBy - Return true if V is only used by Usr.
OnlyUsedBy(Value * V,Value * Usr)133 static bool OnlyUsedBy(Value *V, Value *Usr) {
134 for (User *U : V->users())
135 if (U != Usr)
136 return false;
137
138 return true;
139 }
140
RemoveDeadConstant(Constant * C)141 static void RemoveDeadConstant(Constant *C) {
142 assert(C->use_empty() && "Constant is not dead!");
143 SmallPtrSet<Constant*, 4> Operands;
144 for (Value *Op : C->operands())
145 if (OnlyUsedBy(Op, C))
146 Operands.insert(cast<Constant>(Op));
147 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
148 if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
149 GV->eraseFromParent();
150 }
151 else if (!isa<Function>(C))
152 if (isa<CompositeType>(C->getType()))
153 C->destroyConstant();
154
155 // If the constant referenced anything, see if we can delete it as well.
156 for (Constant *O : Operands)
157 RemoveDeadConstant(O);
158 }
159
160 // Strip the symbol table of its names.
161 //
StripSymtab(ValueSymbolTable & ST,bool PreserveDbgInfo)162 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
163 for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
164 Value *V = VI->getValue();
165 ++VI;
166 if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
167 if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
168 // Set name to "", removing from symbol table!
169 V->setName("");
170 }
171 }
172 }
173
174 // Strip any named types of their names.
StripTypeNames(Module & M,bool PreserveDbgInfo)175 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
176 TypeFinder StructTypes;
177 StructTypes.run(M, false);
178
179 for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
180 StructType *STy = StructTypes[i];
181 if (STy->isLiteral() || STy->getName().empty()) continue;
182
183 if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
184 continue;
185
186 STy->setName("");
187 }
188 }
189
190 /// Find values that are marked as llvm.used.
findUsedValues(GlobalVariable * LLVMUsed,SmallPtrSetImpl<const GlobalValue * > & UsedValues)191 static void findUsedValues(GlobalVariable *LLVMUsed,
192 SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
193 if (!LLVMUsed) return;
194 UsedValues.insert(LLVMUsed);
195
196 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
197
198 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
199 if (GlobalValue *GV =
200 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
201 UsedValues.insert(GV);
202 }
203
204 /// StripSymbolNames - Strip symbol names.
StripSymbolNames(Module & M,bool PreserveDbgInfo)205 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
206
207 SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
208 findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
209 findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
210
211 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
212 I != E; ++I) {
213 if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
214 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
215 I->setName(""); // Internal symbols can't participate in linkage
216 }
217
218 for (Function &I : M) {
219 if (I.hasLocalLinkage() && llvmUsedValues.count(&I) == 0)
220 if (!PreserveDbgInfo || !I.getName().startswith("llvm.dbg"))
221 I.setName(""); // Internal symbols can't participate in linkage
222 StripSymtab(I.getValueSymbolTable(), PreserveDbgInfo);
223 }
224
225 // Remove all names from types.
226 StripTypeNames(M, PreserveDbgInfo);
227
228 return true;
229 }
230
runOnModule(Module & M)231 bool StripSymbols::runOnModule(Module &M) {
232 if (skipModule(M))
233 return false;
234
235 bool Changed = false;
236 Changed |= StripDebugInfo(M);
237 if (!OnlyDebugInfo)
238 Changed |= StripSymbolNames(M, false);
239 return Changed;
240 }
241
runOnModule(Module & M)242 bool StripNonDebugSymbols::runOnModule(Module &M) {
243 if (skipModule(M))
244 return false;
245
246 return StripSymbolNames(M, true);
247 }
248
runOnModule(Module & M)249 bool StripDebugDeclare::runOnModule(Module &M) {
250 if (skipModule(M))
251 return false;
252
253 Function *Declare = M.getFunction("llvm.dbg.declare");
254 std::vector<Constant*> DeadConstants;
255
256 if (Declare) {
257 while (!Declare->use_empty()) {
258 CallInst *CI = cast<CallInst>(Declare->user_back());
259 Value *Arg1 = CI->getArgOperand(0);
260 Value *Arg2 = CI->getArgOperand(1);
261 assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
262 CI->eraseFromParent();
263 if (Arg1->use_empty()) {
264 if (Constant *C = dyn_cast<Constant>(Arg1))
265 DeadConstants.push_back(C);
266 else
267 RecursivelyDeleteTriviallyDeadInstructions(Arg1);
268 }
269 if (Arg2->use_empty())
270 if (Constant *C = dyn_cast<Constant>(Arg2))
271 DeadConstants.push_back(C);
272 }
273 Declare->eraseFromParent();
274 }
275
276 while (!DeadConstants.empty()) {
277 Constant *C = DeadConstants.back();
278 DeadConstants.pop_back();
279 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
280 if (GV->hasLocalLinkage())
281 RemoveDeadConstant(GV);
282 } else
283 RemoveDeadConstant(C);
284 }
285
286 return true;
287 }
288
289 /// Remove any debug info for global variables/functions in the given module for
290 /// which said global variable/function no longer exists (i.e. is null).
291 ///
292 /// Debugging information is encoded in llvm IR using metadata. This is designed
293 /// such a way that debug info for symbols preserved even if symbols are
294 /// optimized away by the optimizer. This special pass removes debug info for
295 /// such symbols.
runOnModule(Module & M)296 bool StripDeadDebugInfo::runOnModule(Module &M) {
297 if (skipModule(M))
298 return false;
299
300 bool Changed = false;
301
302 LLVMContext &C = M.getContext();
303
304 // Find all debug info in F. This is actually overkill in terms of what we
305 // want to do, but we want to try and be as resilient as possible in the face
306 // of potential debug info changes by using the formal interfaces given to us
307 // as much as possible.
308 DebugInfoFinder F;
309 F.processModule(M);
310
311 // For each compile unit, find the live set of global variables/functions and
312 // replace the current list of potentially dead global variables/functions
313 // with the live list.
314 SmallVector<Metadata *, 64> LiveGlobalVariables;
315 SmallVector<Metadata *, 64> LiveSubprograms;
316 DenseSet<const MDNode *> VisitedSet;
317
318 std::set<DISubprogram *> LiveSPs;
319 for (Function &F : M) {
320 if (DISubprogram *SP = F.getSubprogram())
321 LiveSPs.insert(SP);
322 }
323
324 for (DICompileUnit *DIC : F.compile_units()) {
325 // Create our live global variable list.
326 bool GlobalVariableChange = false;
327 for (DIGlobalVariable *DIG : DIC->getGlobalVariables()) {
328 // Make sure we only visit each global variable only once.
329 if (!VisitedSet.insert(DIG).second)
330 continue;
331
332 // If the global variable referenced by DIG is not null, the global
333 // variable is live.
334 if (DIG->getVariable())
335 LiveGlobalVariables.push_back(DIG);
336 else
337 GlobalVariableChange = true;
338 }
339
340 // If we found dead global variables, replace the current global
341 // variable list with our new live global variable list.
342 if (GlobalVariableChange) {
343 DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
344 Changed = true;
345 }
346
347 // Reset lists for the next iteration.
348 LiveSubprograms.clear();
349 LiveGlobalVariables.clear();
350 }
351
352 return Changed;
353 }
354