LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
StripSymbols.cpp
Go to the documentation of this file.
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/DenseMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/TypeFinder.h"
33 #include "llvm/Pass.h"
35 using namespace llvm;
36 
37 namespace {
38  class StripSymbols : public ModulePass {
39  bool OnlyDebugInfo;
40  public:
41  static char ID; // Pass identification, replacement for typeid
42  explicit StripSymbols(bool ODI = false)
43  : ModulePass(ID), OnlyDebugInfo(ODI) {
45  }
46 
47  virtual bool runOnModule(Module &M);
48 
49  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
50  AU.setPreservesAll();
51  }
52  };
53 
54  class StripNonDebugSymbols : public ModulePass {
55  public:
56  static char ID; // Pass identification, replacement for typeid
57  explicit StripNonDebugSymbols()
58  : ModulePass(ID) {
60  }
61 
62  virtual bool runOnModule(Module &M);
63 
64  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65  AU.setPreservesAll();
66  }
67  };
68 
69  class StripDebugDeclare : public ModulePass {
70  public:
71  static char ID; // Pass identification, replacement for typeid
72  explicit StripDebugDeclare()
73  : ModulePass(ID) {
75  }
76 
77  virtual bool runOnModule(Module &M);
78 
79  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80  AU.setPreservesAll();
81  }
82  };
83 
84  class StripDeadDebugInfo : public ModulePass {
85  public:
86  static char ID; // Pass identification, replacement for typeid
87  explicit StripDeadDebugInfo()
88  : ModulePass(ID) {
90  }
91 
92  virtual bool runOnModule(Module &M);
93 
94  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95  AU.setPreservesAll();
96  }
97  };
98 }
99 
100 char StripSymbols::ID = 0;
101 INITIALIZE_PASS(StripSymbols, "strip",
102  "Strip all symbols from a module", false, false)
103 
104 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
105  return new StripSymbols(OnlyDebugInfo);
106 }
107 
108 char StripNonDebugSymbols::ID = 0;
109 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
110  "Strip all symbols, except dbg symbols, from a module",
111  false, false)
112 
114  return new StripNonDebugSymbols();
115 }
116 
117 char StripDebugDeclare::ID = 0;
118 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
119  "Strip all llvm.dbg.declare intrinsics", false, false)
120 
122  return new StripDebugDeclare();
123 }
124 
125 char StripDeadDebugInfo::ID = 0;
126 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
127  "Strip debug info for unused symbols", false, false)
128 
130  return new StripDeadDebugInfo();
131 }
132 
133 /// OnlyUsedBy - Return true if V is only used by Usr.
134 static bool OnlyUsedBy(Value *V, Value *Usr) {
135  for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
136  User *U = *I;
137  if (U != Usr)
138  return false;
139  }
140  return true;
141 }
142 
144  assert(C->use_empty() && "Constant is not dead!");
145  SmallPtrSet<Constant*, 4> Operands;
146  for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
147  if (OnlyUsedBy(C->getOperand(i), C))
148  Operands.insert(cast<Constant>(C->getOperand(i)));
149  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
150  if (!GV->hasLocalLinkage()) return; // Don't delete non static globals.
151  GV->eraseFromParent();
152  }
153  else if (!isa<Function>(C))
154  if (isa<CompositeType>(C->getType()))
155  C->destroyConstant();
156 
157  // If the constant referenced anything, see if we can delete it as well.
158  for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
159  OE = Operands.end(); OI != OE; ++OI)
160  RemoveDeadConstant(*OI);
161 }
162 
163 // Strip the symbol table of its names.
164 //
165 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
166  for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
167  Value *V = VI->getValue();
168  ++VI;
169  if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
170  if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
171  // Set name to "", removing from symbol table!
172  V->setName("");
173  }
174  }
175 }
176 
177 // Strip any named types of their names.
178 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
179  TypeFinder StructTypes;
180  StructTypes.run(M, false);
181 
182  for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
183  StructType *STy = StructTypes[i];
184  if (STy->isLiteral() || STy->getName().empty()) continue;
185 
186  if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
187  continue;
188 
189  STy->setName("");
190  }
191 }
192 
193 /// Find values that are marked as llvm.used.
194 static void findUsedValues(GlobalVariable *LLVMUsed,
196  if (LLVMUsed == 0) return;
197  UsedValues.insert(LLVMUsed);
198 
199  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
200 
201  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
202  if (GlobalValue *GV =
203  dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
204  UsedValues.insert(GV);
205 }
206 
207 /// StripSymbolNames - Strip symbol names.
208 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
209 
210  SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
211  findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
212  findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
213 
214  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
215  I != E; ++I) {
216  if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
217  if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
218  I->setName(""); // Internal symbols can't participate in linkage
219  }
220 
221  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
222  if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
223  if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
224  I->setName(""); // Internal symbols can't participate in linkage
225  StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
226  }
227 
228  // Remove all names from types.
229  StripTypeNames(M, PreserveDbgInfo);
230 
231  return true;
232 }
233 
234 // StripDebugInfo - Strip debug info in the module if it exists.
235 // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and
236 // llvm.dbg.region.end calls, and any globals they point to if now dead.
237 static bool StripDebugInfo(Module &M) {
238 
239  bool Changed = false;
240 
241  // Remove all of the calls to the debugger intrinsics, and remove them from
242  // the module.
243  if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
244  while (!Declare->use_empty()) {
245  CallInst *CI = cast<CallInst>(Declare->use_back());
246  CI->eraseFromParent();
247  }
248  Declare->eraseFromParent();
249  Changed = true;
250  }
251 
252  if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
253  while (!DbgVal->use_empty()) {
254  CallInst *CI = cast<CallInst>(DbgVal->use_back());
255  CI->eraseFromParent();
256  }
257  DbgVal->eraseFromParent();
258  Changed = true;
259  }
260 
262  NME = M.named_metadata_end(); NMI != NME;) {
263  NamedMDNode *NMD = NMI;
264  ++NMI;
265  if (NMD->getName().startswith("llvm.dbg.")) {
266  NMD->eraseFromParent();
267  Changed = true;
268  }
269  }
270 
271  for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
272  for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
273  ++FI)
274  for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
275  ++BI) {
276  if (!BI->getDebugLoc().isUnknown()) {
277  Changed = true;
278  BI->setDebugLoc(DebugLoc());
279  }
280  }
281 
282  return Changed;
283 }
284 
285 bool StripSymbols::runOnModule(Module &M) {
286  bool Changed = false;
287  Changed |= StripDebugInfo(M);
288  if (!OnlyDebugInfo)
289  Changed |= StripSymbolNames(M, false);
290  return Changed;
291 }
292 
293 bool StripNonDebugSymbols::runOnModule(Module &M) {
294  return StripSymbolNames(M, true);
295 }
296 
297 bool StripDebugDeclare::runOnModule(Module &M) {
298 
299  Function *Declare = M.getFunction("llvm.dbg.declare");
300  std::vector<Constant*> DeadConstants;
301 
302  if (Declare) {
303  while (!Declare->use_empty()) {
304  CallInst *CI = cast<CallInst>(Declare->use_back());
305  Value *Arg1 = CI->getArgOperand(0);
306  Value *Arg2 = CI->getArgOperand(1);
307  assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
308  CI->eraseFromParent();
309  if (Arg1->use_empty()) {
310  if (Constant *C = dyn_cast<Constant>(Arg1))
311  DeadConstants.push_back(C);
312  else
314  }
315  if (Arg2->use_empty())
316  if (Constant *C = dyn_cast<Constant>(Arg2))
317  DeadConstants.push_back(C);
318  }
319  Declare->eraseFromParent();
320  }
321 
322  while (!DeadConstants.empty()) {
323  Constant *C = DeadConstants.back();
324  DeadConstants.pop_back();
325  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
326  if (GV->hasLocalLinkage())
327  RemoveDeadConstant(GV);
328  } else
330  }
331 
332  return true;
333 }
334 
335 /// Remove any debug info for global variables/functions in the given module for
336 /// which said global variable/function no longer exists (i.e. is null).
337 ///
338 /// Debugging information is encoded in llvm IR using metadata. This is designed
339 /// such a way that debug info for symbols preserved even if symbols are
340 /// optimized away by the optimizer. This special pass removes debug info for
341 /// such symbols.
342 bool StripDeadDebugInfo::runOnModule(Module &M) {
343  bool Changed = false;
344 
345  LLVMContext &C = M.getContext();
346 
347  // Find all debug info in F. This is actually overkill in terms of what we
348  // want to do, but we want to try and be as resilient as possible in the face
349  // of potential debug info changes by using the formal interfaces given to us
350  // as much as possible.
352  F.processModule(M);
353 
354  // For each compile unit, find the live set of global variables/functions and
355  // replace the current list of potentially dead global variables/functions
356  // with the live list.
357  SmallVector<Value *, 64> LiveGlobalVariables;
358  SmallVector<Value *, 64> LiveSubprograms;
359  DenseSet<const MDNode *> VisitedSet;
360 
362  CE = F.compile_unit_end(); CI != CE; ++CI) {
363  // Create our compile unit.
364  DICompileUnit DIC(*CI);
365  assert(DIC.Verify() && "DIC must verify as a DICompileUnit.");
366 
367  // Create our live subprogram list.
368  DIArray SPs = DIC.getSubprograms();
369  bool SubprogramChange = false;
370  for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
371  DISubprogram DISP(SPs.getElement(i));
372  assert(DISP.Verify() && "DISP must verify as a DISubprogram.");
373 
374  // Make sure we visit each subprogram only once.
375  if (!VisitedSet.insert(DISP).second)
376  continue;
377 
378  // If the function referenced by DISP is not null, the function is live.
379  if (DISP.getFunction())
380  LiveSubprograms.push_back(DISP);
381  else
382  SubprogramChange = true;
383  }
384 
385  // Create our live global variable list.
386  DIArray GVs = DIC.getGlobalVariables();
387  bool GlobalVariableChange = false;
388  for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
389  DIGlobalVariable DIG(GVs.getElement(i));
390  assert(DIG.Verify() && "DIG must verify as DIGlobalVariable.");
391 
392  // Make sure we only visit each global variable only once.
393  if (!VisitedSet.insert(DIG).second)
394  continue;
395 
396  // If the global variable referenced by DIG is not null, the global
397  // variable is live.
398  if (DIG.getGlobal())
399  LiveGlobalVariables.push_back(DIG);
400  else
401  GlobalVariableChange = true;
402  }
403 
404  // If we found dead subprograms or global variables, replace the current
405  // subprogram list/global variable list with our new live subprogram/global
406  // variable list.
407  if (SubprogramChange) {
408  // Make sure that 9 is still the index of the subprograms. This is to make
409  // sure that an assert is hit if the location of the subprogram array
410  // changes. This is just to make sure that this is updated if such an
411  // event occurs.
412  assert(DIC->getNumOperands() >= 10 &&
413  SPs == DIC->getOperand(9) &&
414  "DICompileUnits is expected to store Subprograms in operand "
415  "9.");
416  DIC->replaceOperandWith(9, MDNode::get(C, LiveSubprograms));
417  Changed = true;
418  }
419 
420  if (GlobalVariableChange) {
421  // Make sure that 10 is still the index of global variables. This is to
422  // make sure that an assert is hit if the location of the subprogram array
423  // changes. This is just to make sure that this index is updated if such
424  // an event occurs.
425  assert(DIC->getNumOperands() >= 11 &&
426  GVs == DIC->getOperand(10) &&
427  "DICompileUnits is expected to store Global Variables in operand "
428  "10.");
429  DIC->replaceOperandWith(10, MDNode::get(C, LiveGlobalVariables));
430  Changed = true;
431  }
432 
433  // Reset lists for the next iteration.
434  LiveSubprograms.clear();
435  LiveGlobalVariables.clear();
436  }
437 
438  return Changed;
439 }
StringRef getName() const
getName - Return a constant reference to this named metadata's name.
Definition: Metadata.cpp:569
use_iterator use_end()
Definition: Value.h:152
static PassRegistry * getPassRegistry()
iterator begin()
Get an iterator that from the beginning of the symbol table.
void initializeStripDeadDebugInfoPass(PassRegistry &)
The main container class for the LLVM Intermediate Representation.
Definition: Module.h:112
static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo)
static bool StripSymbolNames(Module &M, bool PreserveDbgInfo)
StripSymbolNames - Strip symbol names.
unsigned getNumOperands() const
Definition: User.h:108
static bool StripDebugInfo(Module &M)
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=0)
Definition: Local.cpp:316
named_metadata_iterator named_metadata_end()
Definition: Module.h:559
bool insert(PtrType Ptr)
Definition: SmallPtrSet.h:253
F(f)
const Constant * getInitializer() const
const GlobalVariable * getGlobalVariable(StringRef Name, bool AllowInternal=false) const
Definition: Module.h:355
void processModule(const Module &M)
processModule - Process entire module and collect debug info.
Definition: DebugInfo.cpp:966
iterator compile_unit_begin() const
Definition: DebugInfo.h:811
static MDNode * get(LLVMContext &Context, ArrayRef< Value * > Vals)
Definition: Metadata.cpp:268
ModulePass * createStripNonDebugSymbolsPass()
StringRef getName() const
Definition: Value.cpp:167
DIArray - This descriptor holds an array of descriptors.
Definition: DebugInfo.h:167
void initializeStripSymbolsPass(PassRegistry &)
ModulePass * createStripDeadDebugInfoPass()
void eraseFromParent()
Definition: Metadata.cpp:559
bool isLiteral() const
Definition: DerivedTypes.h:245
void setName(const Twine &Name)
Definition: Value.cpp:175
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
global_iterator global_begin()
Definition: Module.h:521
DISubprogram - This is a wrapper for a subprogram (e.g. a function).
Definition: DebugInfo.h:429
void initializeStripNonDebugSymbolsPass(PassRegistry &)
bool count(PtrType Ptr) const
count - Return true if the specified pointer is in the set.
Definition: SmallPtrSet.h:264
static bool OnlyUsedBy(Value *V, Value *Usr)
OnlyUsedBy - Return true if V is only used by Usr.
static void RemoveDeadConstant(Constant *C)
iterator end()
Get an iterator to the end of the symbol table.
Function * getFunction(StringRef Name) const
Definition: Module.cpp:221
DIDescriptor getElement(unsigned Idx) const
Definition: DebugInfo.h:172
LLVM Constant Representation.
Definition: Constant.h:41
DIGlobalVariable - This is a wrapper for a global variable.
Definition: DebugInfo.h:572
Value * getOperand(unsigned i) const
Definition: User.h:88
unsigned getNumElements() const
Definition: DebugInfo.cpp:328
ModulePass * createStripDebugDeclarePass()
global_iterator global_end()
Definition: Module.h:523
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
Definition: SmallPtrSet.h:174
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:117
bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:208
void run(const Module &M, bool onlyNamed)
Definition: TypeFinder.cpp:23
Type * getType() const
Definition: Value.h:111
Value * stripPointerCasts()
Strips off any unneeded pointer casts, all-zero GEPs and aliases from the specified value...
Definition: Value.cpp:385
iterator compile_unit_end() const
Definition: DebugInfo.h:812
Value * getArgOperand(unsigned i) const
virtual void destroyConstant()
Definition: Constant.h:122
StringRef getName() const
Definition: Type.cpp:580
INITIALIZE_PASS(StripSymbols,"strip","Strip all symbols from a module", false, false) ModulePass *llvm
use_iterator use_begin()
Definition: Value.h:150
void setName(StringRef Name)
Definition: Type.cpp:441
iterator end()
Definition: Module.h:533
static void StripTypeNames(Module &M, bool PreserveDbgInfo)
User * use_back()
Definition: Value.h:154
#define I(x, y, z)
Definition: MD5.cpp:54
iterator begin()
Definition: Module.h:531
virtual void eraseFromParent()
Definition: Function.cpp:187
NamedMDListType::iterator named_metadata_iterator
The named metadata iterators.
Definition: Module.h:141
void initializeStripDebugDeclarePass(PassRegistry &)
bool use_empty() const
Definition: Value.h:149
size_t size() const
Definition: TypeFinder.h:55
LLVM Value Representation.
Definition: Value.h:66
ModulePass * createStripSymbolsPass(bool OnlyDebugInfo=false)
static void findUsedValues(GlobalVariable *LLVMUsed, SmallPtrSet< const GlobalValue *, 8 > &UsedValues)
Find values that are marked as llvm.used.
DICompileUnit - A wrapper for a compile unit.
Definition: DebugInfo.h:402
named_metadata_iterator named_metadata_begin()
Definition: Module.h:554
LLVMContext & getContext() const
Definition: Module.h:249
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110