3bcaee3437f707141b9f97b1449371218119ca2e
[oota-llvm.git] / lib / Transforms / IPO / StripSymbols.cpp
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/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"
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
41     explicit StripSymbols(bool ODI = false) 
42       : ModulePass(&ID), OnlyDebugInfo(ODI) {}
43
44     virtual bool runOnModule(Module &M);
45
46     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47       AU.setPreservesAll();
48     }
49   };
50
51   class StripNonDebugSymbols : public ModulePass {
52   public:
53     static char ID; // Pass identification, replacement for typeid
54     explicit StripNonDebugSymbols()
55       : ModulePass(&ID) {}
56
57     virtual bool runOnModule(Module &M);
58
59     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60       AU.setPreservesAll();
61     }
62   };
63
64   class StripDebugDeclare : public ModulePass {
65   public:
66     static char ID; // Pass identification, replacement for typeid
67     explicit StripDebugDeclare()
68       : ModulePass(&ID) {}
69
70     virtual bool runOnModule(Module &M);
71
72     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73       AU.setPreservesAll();
74     }
75   };
76
77   class StripDeadDebugInfo : public ModulePass {
78   public:
79     static char ID; // Pass identification, replacement for typeid
80     explicit StripDeadDebugInfo()
81       : ModulePass(&ID) {}
82
83     virtual bool runOnModule(Module &M);
84
85     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
86       AU.setPreservesAll();
87     }
88   };
89 }
90
91 char StripSymbols::ID = 0;
92 static RegisterPass<StripSymbols>
93 X("strip", "Strip all symbols from a module");
94
95 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
96   return new StripSymbols(OnlyDebugInfo);
97 }
98
99 char StripNonDebugSymbols::ID = 0;
100 static RegisterPass<StripNonDebugSymbols>
101 Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module");
102
103 ModulePass *llvm::createStripNonDebugSymbolsPass() {
104   return new StripNonDebugSymbols();
105 }
106
107 char StripDebugDeclare::ID = 0;
108 static RegisterPass<StripDebugDeclare>
109 Z("strip-debug-declare", "Strip all llvm.dbg.declare intrinsics");
110
111 ModulePass *llvm::createStripDebugDeclarePass() {
112   return new StripDebugDeclare();
113 }
114
115 char StripDeadDebugInfo::ID = 0;
116 static RegisterPass<StripDeadDebugInfo>
117 A("strip-dead-debug-info", "Strip debug info for unused symbols");
118
119 ModulePass *llvm::createStripDeadDebugInfoPass() {
120   return new StripDeadDebugInfo();
121 }
122
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) {
126     User *U = *I;
127     if (U != Usr)
128       return false;
129   }
130   return true;
131 }
132
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();
143   }
144   else if (!isa<Function>(C))
145     if (isa<CompositeType>(C->getType()))
146       C->destroyConstant();
147
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);
152 }
153
154 // Strip the symbol table of its names.
155 //
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();
159     ++VI;
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!
163         V->setName("");
164     }
165   }
166 }
167
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"))
172       ++TI;
173     else
174       ST.remove(TI++);
175   }
176 }
177
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);
183   
184   ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer());
185   if (Inits == 0) return;
186   
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);
191 }
192
193 /// StripSymbolNames - Strip symbol names.
194 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
195
196   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
197   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
198   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
199
200   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
201        I != E; ++I) {
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
205   }
206   
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);
212   }
213   
214   // Remove all names from types.
215   StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
216
217   return true;
218 }
219
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) {
224
225   bool Changed = false;
226
227   // Remove all of the calls to the debugger intrinsics, and remove them from
228   // the module.
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();
233     }
234     Declare->eraseFromParent();
235     Changed = true;
236   }
237
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();
242     }
243     DbgVal->eraseFromParent();
244     Changed = true;
245   }
246
247   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
248          NME = M.named_metadata_end(); NMI != NME;) {
249     NamedMDNode *NMD = NMI;
250     ++NMI;
251     if (NMD->getName().startswith("llvm.dbg.")) {
252       NMD->eraseFromParent();
253       Changed = true;
254     }
255   }
256
257   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
258     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
259          ++FI)
260       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
261            ++BI) {
262         if (!BI->getDebugLoc().isUnknown()) {
263           Changed = true;
264           BI->setDebugLoc(DebugLoc());
265         }
266       }
267
268   return Changed;
269 }
270
271 bool StripSymbols::runOnModule(Module &M) {
272   bool Changed = false;
273   Changed |= StripDebugInfo(M);
274   if (!OnlyDebugInfo)
275     Changed |= StripSymbolNames(M, false);
276   return Changed;
277 }
278
279 bool StripNonDebugSymbols::runOnModule(Module &M) {
280   return StripSymbolNames(M, true);
281 }
282
283 bool StripDebugDeclare::runOnModule(Module &M) {
284
285   Function *Declare = M.getFunction("llvm.dbg.declare");
286   std::vector<Constant*> DeadConstants;
287
288   if (Declare) {
289     while (!Declare->use_empty()) {
290       CallInst *CI = cast<CallInst>(Declare->use_back());
291       Value *Arg1 = CI->getArgOperand(0);
292       Value *Arg2 = CI->getArgOperand(1);
293       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
294       CI->eraseFromParent();
295       if (Arg1->use_empty()) {
296         if (Constant *C = dyn_cast<Constant>(Arg1)) 
297           DeadConstants.push_back(C);
298         else 
299           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
300       }
301       if (Arg2->use_empty())
302         if (Constant *C = dyn_cast<Constant>(Arg2)) 
303           DeadConstants.push_back(C);
304     }
305     Declare->eraseFromParent();
306   }
307
308   while (!DeadConstants.empty()) {
309     Constant *C = DeadConstants.back();
310     DeadConstants.pop_back();
311     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
312       if (GV->hasLocalLinkage())
313         RemoveDeadConstant(GV);
314     } else
315       RemoveDeadConstant(C);
316   }
317
318   return true;
319 }
320
321 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm 
322 /// printer to not emit usual symbol prefix before the symbol name is used then
323 /// return linkage name after skipping this special LLVM prefix.
324 static StringRef getRealLinkageName(StringRef LinkageName) {
325   char One = '\1';
326   if (LinkageName.startswith(StringRef(&One, 1)))
327     return LinkageName.substr(1);
328   return LinkageName;
329 }
330
331 bool StripDeadDebugInfo::runOnModule(Module &M) {
332   bool Changed = false;
333
334   // Debugging infomration is encoded in llvm IR using metadata. This is designed
335   // such a way that debug info for symbols preserved even if symbols are
336   // optimized away by the optimizer. This special pass removes debug info for 
337   // such symbols.
338
339   // llvm.dbg.gv keeps track of debug info for global variables.
340   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
341     SmallVector<MDNode *, 8> MDs;
342     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
343       if (DIGlobalVariable(NMD->getOperand(i)).Verify())
344         MDs.push_back(NMD->getOperand(i));
345       else
346         Changed = true;
347     NMD->eraseFromParent();
348     NMD = NULL;
349
350     for (SmallVector<MDNode *, 8>::iterator I = MDs.begin(),
351            E = MDs.end(); I != E; ++I) {
352       if (M.getGlobalVariable(DIGlobalVariable(*I).getGlobal()->getName(), 
353                               true)) {
354         if (!NMD)
355           NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
356         NMD->addOperand(*I);
357       }
358       else
359         Changed = true;
360     }
361   }
362
363   // llvm.dbg.sp keeps track of debug info for subprograms.
364   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp")) {
365     SmallVector<MDNode *, 8> MDs;
366     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
367       if (DISubprogram(NMD->getOperand(i)).Verify())
368         MDs.push_back(NMD->getOperand(i));
369       else
370         Changed = true;
371     NMD->eraseFromParent();
372     NMD = NULL;
373
374     for (SmallVector<MDNode *, 8>::iterator I = MDs.begin(),
375            E = MDs.end(); I != E; ++I) {
376       bool FnIsLive = false;
377       if (Function *F = DISubprogram(*I).getFunction())
378         if (M.getFunction(F->getName()))
379           FnIsLive = true;
380       if (FnIsLive) {
381           if (!NMD)
382             NMD = M.getOrInsertNamedMetadata("llvm.dbg.sp");
383           NMD->addOperand(*I);
384       } else {
385         // Remove llvm.dbg.lv.fnname named mdnode which may have been used
386         // to hold debug info for dead function's local variables.
387         StringRef FName = DISubprogram(*I).getLinkageName();
388         if (FName.empty())
389           FName = DISubprogram(*I).getName();
390         if (NamedMDNode *LVNMD = 
391             M.getNamedMetadata(Twine("llvm.dbg.lv.", 
392                                      getRealLinkageName(FName)))) 
393           LVNMD->eraseFromParent();
394       }
395     }
396   }
397
398   return Changed;
399 }