LLVM  12.0.0git
StripSymbols.cpp
Go to the documentation of this file.
1 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The StripSymbols transformation implements code stripping. Specifically, it
10 // can delete:
11 //
12 // * names for virtual registers
13 // * symbols for internal globals and functions
14 // * debug information
15 //
16 // Note that this transformation makes code much less readable, so it should
17 // only be used in situations where the 'strip' utility would be used, such as
18 // reducing code size or making it harder to reverse engineer code.
19 //
20 //===----------------------------------------------------------------------===//
21 
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/PassManager.h"
30 #include "llvm/IR/TypeFinder.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Transforms/IPO.h"
36 
37 using namespace llvm;
38 
39 namespace {
40  class StripSymbols : public ModulePass {
41  bool OnlyDebugInfo;
42  public:
43  static char ID; // Pass identification, replacement for typeid
44  explicit StripSymbols(bool ODI = false)
45  : ModulePass(ID), OnlyDebugInfo(ODI) {
47  }
48 
49  bool runOnModule(Module &M) override;
50 
51  void getAnalysisUsage(AnalysisUsage &AU) const override {
52  AU.setPreservesAll();
53  }
54  };
55 
56  class StripNonDebugSymbols : public ModulePass {
57  public:
58  static char ID; // Pass identification, replacement for typeid
59  explicit StripNonDebugSymbols()
60  : ModulePass(ID) {
62  }
63 
64  bool runOnModule(Module &M) override;
65 
66  void getAnalysisUsage(AnalysisUsage &AU) const override {
67  AU.setPreservesAll();
68  }
69  };
70 
71  class StripDebugDeclare : public ModulePass {
72  public:
73  static char ID; // Pass identification, replacement for typeid
74  explicit StripDebugDeclare()
75  : ModulePass(ID) {
77  }
78 
79  bool runOnModule(Module &M) override;
80 
81  void getAnalysisUsage(AnalysisUsage &AU) const override {
82  AU.setPreservesAll();
83  }
84  };
85 
86  class StripDeadDebugInfo : public ModulePass {
87  public:
88  static char ID; // Pass identification, replacement for typeid
89  explicit StripDeadDebugInfo()
90  : ModulePass(ID) {
92  }
93 
94  bool runOnModule(Module &M) override;
95 
96  void getAnalysisUsage(AnalysisUsage &AU) const override {
97  AU.setPreservesAll();
98  }
99  };
100 }
101 
102 char StripSymbols::ID = 0;
103 INITIALIZE_PASS(StripSymbols, "strip",
104  "Strip all symbols from a module", false, false)
105 
106 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
107  return new StripSymbols(OnlyDebugInfo);
108 }
109 
110 char StripNonDebugSymbols::ID = 0;
111 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
112  "Strip all symbols, except dbg symbols, from a module",
113  false, false)
114 
116  return new StripNonDebugSymbols();
117 }
118 
119 char StripDebugDeclare::ID = 0;
120 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
121  "Strip all llvm.dbg.declare intrinsics", false, false)
122 
124  return new StripDebugDeclare();
125 }
126 
127 char StripDeadDebugInfo::ID = 0;
128 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
129  "Strip debug info for unused symbols", false, false)
130 
132  return new StripDeadDebugInfo();
133 }
134 
135 /// OnlyUsedBy - Return true if V is only used by Usr.
136 static bool OnlyUsedBy(Value *V, Value *Usr) {
137  for (User *U : V->users())
138  if (U != Usr)
139  return false;
140 
141  return true;
142 }
143 
145  assert(C->use_empty() && "Constant is not dead!");
147  for (Value *Op : C->operands())
148  if (OnlyUsedBy(Op, C))
149  Operands.insert(cast<Constant>(Op));
150  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
151  if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals.
152  GV->eraseFromParent();
153  } else if (!isa<Function>(C)) {
154  // FIXME: Why does the type of the constant matter here?
155  if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType()) ||
156  isa<VectorType>(C->getType()))
157  C->destroyConstant();
158  }
159 
160  // If the constant referenced anything, see if we can delete it as well.
161  for (Constant *O : Operands)
163 }
164 
165 // Strip the symbol table of its names.
166 //
167 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
168  for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
169  Value *V = VI->getValue();
170  ++VI;
171  if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
172  if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
173  // Set name to "", removing from symbol table!
174  V->setName("");
175  }
176  }
177 }
178 
179 // Strip any named types of their names.
180 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
181  TypeFinder StructTypes;
182  StructTypes.run(M, false);
183 
184  for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
185  StructType *STy = StructTypes[i];
186  if (STy->isLiteral() || STy->getName().empty()) continue;
187 
188  if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
189  continue;
190 
191  STy->setName("");
192  }
193 }
194 
195 /// Find values that are marked as llvm.used.
196 static void findUsedValues(GlobalVariable *LLVMUsed,
198  if (!LLVMUsed) return;
199  UsedValues.insert(LLVMUsed);
200 
201  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
202 
203  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
204  if (GlobalValue *GV =
205  dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
206  UsedValues.insert(GV);
207 }
208 
209 /// StripSymbolNames - Strip symbol names.
210 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
211 
212  SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
213  findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
214  findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
215 
216  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
217  I != E; ++I) {
218  if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
219  if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
220  I->setName(""); // Internal symbols can't participate in linkage
221  }
222 
223  for (Function &I : M) {
224  if (I.hasLocalLinkage() && llvmUsedValues.count(&I) == 0)
225  if (!PreserveDbgInfo || !I.getName().startswith("llvm.dbg"))
226  I.setName(""); // Internal symbols can't participate in linkage
227  if (auto *Symtab = I.getValueSymbolTable())
228  StripSymtab(*Symtab, PreserveDbgInfo);
229  }
230 
231  // Remove all names from types.
232  StripTypeNames(M, PreserveDbgInfo);
233 
234  return true;
235 }
236 
237 bool StripSymbols::runOnModule(Module &M) {
238  if (skipModule(M))
239  return false;
240 
241  bool Changed = false;
242  Changed |= StripDebugInfo(M);
243  if (!OnlyDebugInfo)
244  Changed |= StripSymbolNames(M, false);
245  return Changed;
246 }
247 
248 bool StripNonDebugSymbols::runOnModule(Module &M) {
249  if (skipModule(M))
250  return false;
251 
252  return StripSymbolNames(M, true);
253 }
254 
255 static bool stripDebugDeclareImpl(Module &M) {
256 
257  Function *Declare = M.getFunction("llvm.dbg.declare");
258  std::vector<Constant*> DeadConstants;
259 
260  if (Declare) {
261  while (!Declare->use_empty()) {
262  CallInst *CI = cast<CallInst>(Declare->user_back());
263  Value *Arg1 = CI->getArgOperand(0);
264  Value *Arg2 = CI->getArgOperand(1);
265  assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
266  CI->eraseFromParent();
267  if (Arg1->use_empty()) {
268  if (Constant *C = dyn_cast<Constant>(Arg1))
269  DeadConstants.push_back(C);
270  else
272  }
273  if (Arg2->use_empty())
274  if (Constant *C = dyn_cast<Constant>(Arg2))
275  DeadConstants.push_back(C);
276  }
277  Declare->eraseFromParent();
278  }
279 
280  while (!DeadConstants.empty()) {
281  Constant *C = DeadConstants.back();
282  DeadConstants.pop_back();
283  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
284  if (GV->hasLocalLinkage())
285  RemoveDeadConstant(GV);
286  } else
288  }
289 
290  return true;
291 }
292 
293 bool StripDebugDeclare::runOnModule(Module &M) {
294  if (skipModule(M))
295  return false;
296  return stripDebugDeclareImpl(M);
297 }
298 
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.
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;
316 
317  std::set<DIGlobalVariableExpression *> LiveGVs;
318  for (GlobalVariable &GV : M.globals()) {
320  GV.getDebugInfo(GVEs);
321  for (auto *GVE : GVEs)
322  LiveGVs.insert(GVE);
323  }
324 
325  std::set<DICompileUnit *> LiveCUs;
326  // Any CU referenced from a subprogram is live.
327  for (DISubprogram *SP : F.subprograms()) {
328  if (SP->getUnit())
329  LiveCUs.insert(SP->getUnit());
330  }
331 
332  bool HasDeadCUs = false;
333  for (DICompileUnit *DIC : F.compile_units()) {
334  // Create our live global variable list.
335  bool GlobalVariableChange = false;
336  for (auto *DIG : DIC->getGlobalVariables()) {
337  if (DIG->getExpression() && DIG->getExpression()->isConstant())
338  LiveGVs.insert(DIG);
339 
340  // Make sure we only visit each global variable only once.
341  if (!VisitedSet.insert(DIG).second)
342  continue;
343 
344  // If a global variable references DIG, the global variable is live.
345  if (LiveGVs.count(DIG))
346  LiveGlobalVariables.push_back(DIG);
347  else
348  GlobalVariableChange = true;
349  }
350 
351  if (!LiveGlobalVariables.empty())
352  LiveCUs.insert(DIC);
353  else if (!LiveCUs.count(DIC))
354  HasDeadCUs = true;
355 
356  // If we found dead global variables, replace the current global
357  // variable list with our new live global variable list.
358  if (GlobalVariableChange) {
359  DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
360  Changed = true;
361  }
362 
363  // Reset lists for the next iteration.
364  LiveGlobalVariables.clear();
365  }
366 
367  if (HasDeadCUs) {
368  // Delete the old node and replace it with a new one
369  NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
370  NMD->clearOperands();
371  if (!LiveCUs.empty()) {
372  for (DICompileUnit *CU : LiveCUs)
373  NMD->addOperand(CU);
374  }
375  Changed = true;
376  }
377 
378  return Changed;
379 }
380 
381 /// Remove any debug info for global variables/functions in the given module for
382 /// which said global variable/function no longer exists (i.e. is null).
383 ///
384 /// Debugging information is encoded in llvm IR using metadata. This is designed
385 /// such a way that debug info for symbols preserved even if symbols are
386 /// optimized away by the optimizer. This special pass removes debug info for
387 /// such symbols.
388 bool StripDeadDebugInfo::runOnModule(Module &M) {
389  if (skipModule(M))
390  return false;
391  return stripDeadDebugInfoImpl(M);
392 }
393 
395  StripDebugInfo(M);
396  StripSymbolNames(M, false);
397  return PreservedAnalyses::all();
398 }
399 
401  ModuleAnalysisManager &AM) {
402  StripSymbolNames(M, true);
403  return PreservedAnalyses::all();
404 }
405 
407  ModuleAnalysisManager &AM) {
409  return PreservedAnalyses::all();
410 }
411 
413  ModuleAnalysisManager &AM) {
415  return PreservedAnalyses::all();
416 }
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:77
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class provides a symbol table of name/value pairs.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void initializeStripDeadDebugInfoPass(PassRegistry &)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo)
void clearOperands()
Drop all references to this node's operands.
Definition: Metadata.cpp:1120
static bool StripSymbolNames(Module &M, bool PreserveDbgInfo)
StripSymbolNames - Strip symbol names.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:289
Implements a dense probed hash-table based set.
Definition: DenseSet.h:268
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void addOperand(MDNode *M)
Definition: Metadata.cpp:1111
This class represents a function call, abstracting a target machine's calling convention.
F(f)
ModulePass * createStripNonDebugSymbolsPass()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1323
void initializeStripSymbolsPass(PassRegistry &)
ModulePass * createStripDeadDebugInfoPass()
A tuple of MDNodes.
Definition: Metadata.h:1350
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Class to represent struct types.
Definition: DerivedTypes.h:212
Utility to find all debug info in a module.
Definition: DebugInfo.h:72
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:367
mir Rename Register Operands
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:156
Subprogram description.
void initializeStripNonDebugSymbolsPass(PassRegistry &)
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
static bool OnlyUsedBy(Value *V, Value *Usr)
OnlyUsedBy - Return true if V is only used by Usr.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:358
static void RemoveDeadConstant(Constant *C)
Value * getOperand(unsigned i) const
Definition: User.h:169
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:155
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1138
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:364
Represent the analysis usage information of a pass.
StringRef getName() const
Return the name for this struct type if it has an identity.
Definition: Type.cpp:524
constexpr double e
Definition: MathExtras.h:58
op_range operands()
Definition: User.h:242
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:375
static bool stripDeadDebugInfoImpl(Module &M)
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:630
ModulePass * createStripDebugDeclarePass()
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:161
INITIALIZE_PASS(StripSymbols, "strip", "Strip all symbols from a module", false, false) ModulePass *llvm
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:191
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:442
void run(const Module &M, bool onlyNamed)
Definition: TypeFinder.cpp:31
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1116
Module.h This file contains the declarations for the Module class.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition: Local.cpp:483
bool isLiteral() const
Return true if this type is uniqued by structural equivalence, false if it is a struct definition.
Definition: DerivedTypes.h:278
ConstantArray - Constant Array Declarations.
Definition: Constants.h:424
void push_back(pointer val)
Definition: ilist.h:313
void setPreservesAll()
Set by analyses that do not transform their input at all.
iterator_range< user_iterator > users()
Definition: Value.h:424
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:721
size_t size() const
Definition: TypeFinder.h:56
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
Definition: Type.cpp:410
static void StripTypeNames(Module &M, bool PreserveDbgInfo)
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:295
#define I(x, y, z)
Definition: MD5.cpp:59
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:238
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Function.cpp:317
static void findUsedValues(GlobalVariable *LLVMUsed, SmallPtrSetImpl< const GlobalValue * > &UsedValues)
Find values that are marked as llvm.used.
void initializeStripDebugDeclarePass(PassRegistry &)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:75
ModulePass * createStripSymbolsPass(bool OnlyDebugInfo=false)
static bool stripDebugDeclareImpl(Module &M)
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
Definition: TypeFinder.h:30
bool use_empty() const
Definition: Value.h:347
User * user_back()
Definition: Value.h:410