Recursively remove dead argument while removing llvm.dbg.declare intrinsic.
[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/ValueSymbolTable.h"
30 #include "llvm/TypeSymbolTable.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 using namespace llvm;
35
36 namespace {
37   class VISIBILITY_HIDDEN 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 VISIBILITY_HIDDEN 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
65 char StripSymbols::ID = 0;
66 static RegisterPass<StripSymbols>
67 X("strip", "Strip all symbols from a module");
68
69 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
70   return new StripSymbols(OnlyDebugInfo);
71 }
72
73 char StripNonDebugSymbols::ID = 0;
74 static RegisterPass<StripNonDebugSymbols>
75 Y("strip-nondebug", "Strip all symbols, except dbg symbols, from a module");
76
77 ModulePass *llvm::createStripNonDebugSymbolsPass() {
78   return new StripNonDebugSymbols();
79 }
80
81 /// OnlyUsedBy - Return true if V is only used by Usr.
82 static bool OnlyUsedBy(Value *V, Value *Usr) {
83   for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
84     User *U = *I;
85     if (U != Usr)
86       return false;
87   }
88   return true;
89 }
90
91 static void RemoveDeadConstant(Constant *C) {
92   assert(C->use_empty() && "Constant is not dead!");
93   SmallPtrSet<Constant *, 4> Operands;
94   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
95     if (isa<DerivedType>(C->getOperand(i)->getType()) &&
96         OnlyUsedBy(C->getOperand(i), C)) 
97       Operands.insert(C->getOperand(i));
98   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
99     if (!GV->hasLocalLinkage()) return;   // Don't delete non static globals.
100     GV->eraseFromParent();
101   }
102   else if (!isa<Function>(C))
103     if (isa<CompositeType>(C->getType()))
104       C->destroyConstant();
105
106   // If the constant referenced anything, see if we can delete it as well.
107   for (SmallPtrSet<Constant *, 4>::iterator OI = Operands.begin(),
108          OE = Operands.end(); OI != OE; ++OI)
109     RemoveDeadConstant(*OI);
110 }
111
112 // Strip the symbol table of its names.
113 //
114 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
115   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
116     Value *V = VI->getValue();
117     ++VI;
118     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
119       if (!PreserveDbgInfo || strncmp(V->getNameStart(), "llvm.dbg", 8))
120         // Set name to "", removing from symbol table!
121         V->setName("");
122     }
123   }
124 }
125
126 // Strip the symbol table of its names.
127 static void StripTypeSymtab(TypeSymbolTable &ST, bool PreserveDbgInfo) {
128   for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) {
129     if (PreserveDbgInfo && strncmp(TI->first.c_str(), "llvm.dbg", 8) == 0)
130       ++TI;
131     else
132       ST.remove(TI++);
133   }
134 }
135
136 /// Find values that are marked as llvm.used.
137 void findUsedValues(Module &M,
138                     SmallPtrSet<const GlobalValue*, 8>& llvmUsedValues) {
139   if (GlobalVariable *LLVMUsed = M.getGlobalVariable("llvm.used")) {
140     llvmUsedValues.insert(LLVMUsed);
141     // Collect values that are preserved as per explicit request.
142     // llvm.used is used to list these values.
143     if (ConstantArray *Inits = 
144         dyn_cast<ConstantArray>(LLVMUsed->getInitializer())) {
145       for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
146         if (GlobalValue *GV = dyn_cast<GlobalValue>(Inits->getOperand(i)))
147           llvmUsedValues.insert(GV);
148         else if (ConstantExpr *CE =
149                  dyn_cast<ConstantExpr>(Inits->getOperand(i)))
150           if (CE->getOpcode() == Instruction::BitCast)
151             if (GlobalValue *GV = dyn_cast<GlobalValue>(CE->getOperand(0)))
152               llvmUsedValues.insert(GV);
153       }
154     }
155   }
156 }
157
158 /// StripSymbolNames - Strip symbol names.
159 bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
160
161   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
162   findUsedValues(M, llvmUsedValues);
163
164   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
165        I != E; ++I) {
166     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
167       if (!PreserveDbgInfo || strncmp(I->getNameStart(), "llvm.dbg", 8))
168         I->setName("");     // Internal symbols can't participate in linkage
169   }
170   
171   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
172     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
173       if (!PreserveDbgInfo || strncmp(I->getNameStart(), "llvm.dbg", 8))
174         I->setName("");     // Internal symbols can't participate in linkage
175     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
176   }
177   
178   // Remove all names from types.
179   StripTypeSymtab(M.getTypeSymbolTable(), PreserveDbgInfo);
180
181   return true;
182 }
183
184 // StripDebugInfo - Strip debug info in the module if it exists.  
185 // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and 
186 // llvm.dbg.region.end calls, and any globals they point to if now dead.
187 bool StripDebugInfo(Module &M) {
188
189   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
190   findUsedValues(M, llvmUsedValues);
191
192   // Delete all dbg variables.
193   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
194        I != E; ++I) {
195     GlobalVariable *GV = dyn_cast<GlobalVariable>(I);
196     if (!GV) continue;
197     if (!GV->use_empty() && llvmUsedValues.count(I) == 0) {
198       if (strncmp(GV->getNameStart(), "llvm.dbg", 8) == 0) {
199         GV->replaceAllUsesWith(UndefValue::get(GV->getType()));
200       }
201     }
202   }
203
204   Function *FuncStart = M.getFunction("llvm.dbg.func.start");
205   Function *StopPoint = M.getFunction("llvm.dbg.stoppoint");
206   Function *RegionStart = M.getFunction("llvm.dbg.region.start");
207   Function *RegionEnd = M.getFunction("llvm.dbg.region.end");
208   Function *Declare = M.getFunction("llvm.dbg.declare");
209
210   std::vector<Constant*> DeadConstants;
211
212   // Remove all of the calls to the debugger intrinsics, and remove them from
213   // the module.
214   if (FuncStart) {
215     while (!FuncStart->use_empty()) {
216       CallInst *CI = cast<CallInst>(FuncStart->use_back());
217       Value *Arg = CI->getOperand(1);
218       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
219       CI->eraseFromParent();
220       if (Arg->use_empty())
221         if (Constant *C = dyn_cast<Constant>(Arg)) 
222           DeadConstants.push_back(C);
223     }
224     FuncStart->eraseFromParent();
225   }
226   if (StopPoint) {
227     while (!StopPoint->use_empty()) {
228       CallInst *CI = cast<CallInst>(StopPoint->use_back());
229       Value *Arg = CI->getOperand(3);
230       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
231       CI->eraseFromParent();
232       if (Arg->use_empty())
233         if (Constant *C = dyn_cast<Constant>(Arg)) 
234           DeadConstants.push_back(C);
235     }
236     StopPoint->eraseFromParent();
237   }
238   if (RegionStart) {
239     while (!RegionStart->use_empty()) {
240       CallInst *CI = cast<CallInst>(RegionStart->use_back());
241       Value *Arg = CI->getOperand(1);
242       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
243       CI->eraseFromParent();
244       if (Arg->use_empty())
245         if (Constant *C = dyn_cast<Constant>(Arg)) 
246           DeadConstants.push_back(C);
247     }
248     RegionStart->eraseFromParent();
249   }
250   if (RegionEnd) {
251     while (!RegionEnd->use_empty()) {
252       CallInst *CI = cast<CallInst>(RegionEnd->use_back());
253       Value *Arg = CI->getOperand(1);
254       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
255       CI->eraseFromParent();
256       if (Arg->use_empty())
257         if (Constant *C = dyn_cast<Constant>(Arg)) 
258           DeadConstants.push_back(C);
259     }
260     RegionEnd->eraseFromParent();
261   }
262   if (Declare) {
263     while (!Declare->use_empty()) {
264       CallInst *CI = cast<CallInst>(Declare->use_back());
265       Value *Arg1 = CI->getOperand(1);
266       Value *Arg2 = CI->getOperand(2);
267       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
268       CI->eraseFromParent();
269       if (Arg1->use_empty()) {
270         if (Constant *C = dyn_cast<Constant>(Arg1)) 
271           DeadConstants.push_back(C);
272         else 
273           RecursivelyDeleteTriviallyDeadInstructions(Arg1, NULL);
274       }
275       if (Arg2->use_empty())
276         if (Constant *C = dyn_cast<Constant>(Arg2)) 
277           DeadConstants.push_back(C);
278     }
279     Declare->eraseFromParent();
280   }
281
282   // llvm.dbg.compile_units and llvm.dbg.subprograms are marked as linkonce
283   // but since we are removing all debug information, make them internal now.
284   // FIXME: Use private linkage maybe?
285   if (Constant *C = M.getNamedGlobal("llvm.dbg.compile_units"))
286     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
287       GV->setLinkage(GlobalValue::InternalLinkage);
288
289   if (Constant *C = M.getNamedGlobal("llvm.dbg.subprograms"))
290     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
291       GV->setLinkage(GlobalValue::InternalLinkage);
292  
293   if (Constant *C = M.getNamedGlobal("llvm.dbg.global_variables"))
294     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
295       GV->setLinkage(GlobalValue::InternalLinkage);
296
297   // Delete all dbg variables.
298   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
299        I != E; ++I) {
300     GlobalVariable *GV = dyn_cast<GlobalVariable>(I);
301     if (!GV) continue;
302     if (GV->use_empty() && llvmUsedValues.count(I) == 0
303         && (!GV->hasSection() 
304             || strcmp(GV->getSection().c_str(), "llvm.metadata") == 0))
305       DeadConstants.push_back(GV);
306   }
307
308   if (DeadConstants.empty())
309     return false;
310
311   // Delete any internal globals that were only used by the debugger intrinsics.
312   while (!DeadConstants.empty()) {
313     Constant *C = DeadConstants.back();
314     DeadConstants.pop_back();
315     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
316       if (GV->hasLocalLinkage())
317         RemoveDeadConstant(GV);
318     }
319     else
320       RemoveDeadConstant(C);
321   }
322
323   // Remove all llvm.dbg types.
324   TypeSymbolTable &ST = M.getTypeSymbolTable();
325   for (TypeSymbolTable::iterator TI = ST.begin(), TE = ST.end(); TI != TE; ) {
326     if (!strncmp(TI->first.c_str(), "llvm.dbg.", 9))
327       ST.remove(TI++);
328     else 
329       ++TI;
330   }
331   
332   return true;
333 }
334
335 bool StripSymbols::runOnModule(Module &M) {
336   bool Changed = false;
337   Changed |= StripDebugInfo(M);
338   if (!OnlyDebugInfo)
339     Changed |= StripSymbolNames(M, false);
340   return Changed;
341 }
342
343 bool StripNonDebugSymbols::runOnModule(Module &M) {
344   return StripSymbolNames(M, true);
345 }