1 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The StripSymbols transformation implements code stripping. Specifically, it
13 // * names for virtual registers
14 // * symbols for internal globals and functions
15 // * debug information
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.
21 //===----------------------------------------------------------------------===//
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Module.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Analysis/DebugInfo.h"
30 #include "llvm/ValueSymbolTable.h"
31 #include "llvm/TypeSymbolTable.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/ADT/SmallPtrSet.h"
37 class StripSymbols : public ModulePass {
40 static char ID; // Pass identification, replacement for typeid
41 explicit StripSymbols(bool ODI = false)
42 : ModulePass(&ID), OnlyDebugInfo(ODI) {}
44 virtual bool runOnModule(Module &M);
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 class StripNonDebugSymbols : public ModulePass {
53 static char ID; // Pass identification, replacement for typeid
54 explicit StripNonDebugSymbols()
57 virtual bool runOnModule(Module &M);
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 class StripDebugDeclare : public ModulePass {
66 static char ID; // Pass identification, replacement for typeid
67 explicit StripDebugDeclare()
70 virtual bool runOnModule(Module &M);
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 class StripDeadDebugInfo : public ModulePass {
79 static char ID; // Pass identification, replacement for typeid
80 explicit StripDeadDebugInfo()
83 virtual bool runOnModule(Module &M);
85 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
91 char StripSymbols::ID = 0;
92 static RegisterPass<StripSymbols>
93 X("strip", "Strip all symbols from a module");
95 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
96 return new StripSymbols(OnlyDebugInfo);
99 char StripNonDebugSymbols::ID = 0;
100 static RegisterPass<StripNonDebugSymbols>
101 Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module");
103 ModulePass *llvm::createStripNonDebugSymbolsPass() {
104 return new StripNonDebugSymbols();
107 char StripDebugDeclare::ID = 0;
108 static RegisterPass<StripDebugDeclare>
109 Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics");
111 ModulePass *llvm::createStripDebugDeclarePass() {
112 return new StripDebugDeclare();
115 char StripDeadDebugInfo::ID = 0;
116 static RegisterPass<StripDeadDebugInfo>
117 A("strip-dead-debug-info", "Strip debug info for unused symbols");
119 ModulePass *llvm::createStripDeadDebugInfoPass() {
120 return new StripDeadDebugInfo();
123 /// OnlyUsedBy - Return true if V is only used by Usr.
124 static bool OnlyUsedBy(Value *V, Value *Usr) {
125 for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
133 static void RemoveDeadConstant(Constant *C) {
134 assert(C->use_empty() && "Constant is not dead!");
135 SmallPtrSet<Constant*, 4> Operands;
136 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
137 if (isa<DerivedType>(C->getOperand(i)->getType()) &&
138 OnlyUsedBy(C->getOperand(i), C))
139 Operands.insert(cast<Constant>(C->getOperand(i)));
140 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
141 if (!GV->hasLocalLinkage()) return; // Don't delete non static globals.
142 GV->eraseFromParent();
144 else if (!isa<Function>(C))
145 if (isa<CompositeType>(C->getType()))
146 C->destroyConstant();
148 // If the constant referenced anything, see if we can delete it as well.
149 for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
150 OE = Operands.end(); OI != OE; ++OI)
151 RemoveDeadConstant(*OI);
154 // Strip the symbol table of its names.
156 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
157 for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
158 Value *V = VI->getValue();
160 if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
161 if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
162 // Set name to "", removing from symbol table!
168 // Strip the symbol table of its names.
169 static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) {
170 for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) {
171 if (PreserveDbgInfo && StringRef(TI->first).startswith("llvm.dbg"))
178 /// Find values that are marked as llvm.used.
179 static void findUsedValues(GlobalVariable *LLVMUsed,
180 SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
181 if (LLVMUsed == 0) return;
182 UsedValues.insert(LLVMUsed);
184 ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
185 if (Inits == 0) return;
187 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
188 if (GlobalValue *GV =
189 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
190 UsedValues.insert(GV);
193 /// StripSymbolNames - Strip symbol names.
194 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
196 SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
197 findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
198 findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
200 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
202 if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
203 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
204 I->setName(""); // Internal symbols can't participate in linkage
207 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
208 if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
209 if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
210 I->setName(""); // Internal symbols can't participate in linkage
211 StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
214 // Remove all names from types.
215 StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
220 // StripDebugInfo - Strip debug info in the module if it exists.
221 // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and
222 // llvm.dbg.region.end calls, and any globals they point to if now dead.
223 static bool StripDebugInfo(Module &M) {
225 bool Changed = false;
227 // Remove all of the calls to the debugger intrinsics, and remove them from
229 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
230 while (!Declare->use_empty()) {
231 CallInst *CI = cast<CallInst>(Declare->use_back());
232 CI->eraseFromParent();
234 Declare->eraseFromParent();
238 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
239 while (!DbgVal->use_empty()) {
240 CallInst *CI = cast<CallInst>(DbgVal->use_back());
241 CI->eraseFromParent();
243 DbgVal->eraseFromParent();
247 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
248 NME = M.named_metadata_end(); NMI != NME;) {
249 NamedMDNode *NMD = NMI;
251 if (NMD->getName().startswith("llvm.dbg.")) {
252 NMD->eraseFromParent();
257 unsigned MDDbgKind = M.getMDKindID("dbg");
258 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
259 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
261 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
263 Changed = true; // FIXME: Only set if there was debug metadata.
264 BI->setMetadata(MDDbgKind, 0);
270 bool StripSymbols::runOnModule(Module &M) {
271 bool Changed = false;
272 Changed |= StripDebugInfo(M);
274 Changed |= StripSymbolNames(M, false);
278 bool StripNonDebugSymbols::runOnModule(Module &M) {
279 return StripSymbolNames(M, true);
282 bool StripDebugDeclare::runOnModule(Module &M) {
284 Function *Declare = M.getFunction("llvm.dbg.declare");
285 std::vector<Constant*> DeadConstants;
288 while (!Declare->use_empty()) {
289 CallInst *CI = cast<CallInst>(Declare->use_back());
290 Value *Arg1 = CI->getArgOperand(0);
291 Value *Arg2 = CI->getArgOperand(1);
292 assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
293 CI->eraseFromParent();
294 if (Arg1->use_empty()) {
295 if (Constant *C = dyn_cast<Constant>(Arg1))
296 DeadConstants.push_back(C);
298 RecursivelyDeleteTriviallyDeadInstructions(Arg1);
300 if (Arg2->use_empty())
301 if (Constant *C = dyn_cast<Constant>(Arg2))
302 DeadConstants.push_back(C);
304 Declare->eraseFromParent();
307 while (!DeadConstants.empty()) {
308 Constant *C = DeadConstants.back();
309 DeadConstants.pop_back();
310 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
311 if (GV->hasLocalLinkage())
312 RemoveDeadConstant(GV);
314 RemoveDeadConstant(C);
320 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
321 /// printer to not emit usual symbol prefix before the symbol name is used then
322 /// return linkage name after skipping this special LLVM prefix.
323 static StringRef getRealLinkageName(StringRef LinkageName) {
325 if (LinkageName.startswith(StringRef(&One, 1)))
326 return LinkageName.substr(1);
330 bool StripDeadDebugInfo::runOnModule(Module &M) {
331 bool Changed = false;
333 // Debugging infomration is encoded in llvm IR using metadata. This is designed
334 // such a way that debug info for symbols preserved even if symbols are
335 // optimized away by the optimizer. This special pass removes debug info for
338 // llvm.dbg.gv keeps track of debug info for global variables.
339 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
340 SmallVector<MDNode *, 8> MDs;
341 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
342 if (DIGlobalVariable(NMD->getOperand(i)).Verify())
343 MDs.push_back(NMD->getOperand(i));
346 NMD->eraseFromParent();
349 for (SmallVector<MDNode *, 8>::iterator I = MDs.begin(),
350 E = MDs.end(); I != E; ++I) {
351 if (M.getGlobalVariable(DIGlobalVariable(*I).getGlobal()->getName(),
354 NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
362 // llvm.dbg.sp keeps track of debug info for subprograms.
363 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp")) {
364 SmallVector<MDNode *, 8> MDs;
365 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
366 if (DISubprogram(NMD->getOperand(i)).Verify())
367 MDs.push_back(NMD->getOperand(i));
370 NMD->eraseFromParent();
373 for (SmallVector<MDNode *, 8>::iterator I = MDs.begin(),
374 E = MDs.end(); I != E; ++I) {
375 bool FnIsLive = false;
376 if (Function *F = DISubprogram(*I).getFunction())
377 if (M.getFunction(F->getName()))
381 NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
384 // Remove llvm.dbg.lv.fnname named mdnode which may have been used
385 // to hold debug info for dead function's local variables.
386 StringRef FName = DISubprogram(*I).getLinkageName();
388 FName = DISubprogram(*I).getName();
389 if (NamedMDNode *LVNMD =
390 M.getNamedMetadata(Twine("llvm.dbg.lv.",
391 getRealLinkageName(FName))))
392 LVNMD->eraseFromParent();