xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/IPO/StripSymbols.cpp (revision 66fd12cf4896eb08ad8e7a2627537f84ead84dd3)
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 
22 #include "llvm/Transforms/IPO/StripSymbols.h"
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/InstIterator.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/PassManager.h"
31 #include "llvm/IR/TypeFinder.h"
32 #include "llvm/IR/ValueSymbolTable.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Transforms/IPO.h"
36 #include "llvm/Transforms/IPO/StripSymbols.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 
39 using namespace llvm;
40 
41 namespace {
42   class StripSymbols : public ModulePass {
43     bool OnlyDebugInfo;
44   public:
45     static char ID; // Pass identification, replacement for typeid
46     explicit StripSymbols(bool ODI = false)
47       : ModulePass(ID), OnlyDebugInfo(ODI) {
48         initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
49       }
50 
51     bool runOnModule(Module &M) override;
52 
53     void getAnalysisUsage(AnalysisUsage &AU) const override {
54       AU.setPreservesAll();
55     }
56   };
57 
58   class StripNonDebugSymbols : public ModulePass {
59   public:
60     static char ID; // Pass identification, replacement for typeid
61     explicit StripNonDebugSymbols()
62       : ModulePass(ID) {
63         initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
64       }
65 
66     bool runOnModule(Module &M) override;
67 
68     void getAnalysisUsage(AnalysisUsage &AU) const override {
69       AU.setPreservesAll();
70     }
71   };
72 
73   class StripDebugDeclare : public ModulePass {
74   public:
75     static char ID; // Pass identification, replacement for typeid
76     explicit StripDebugDeclare()
77       : ModulePass(ID) {
78         initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
79       }
80 
81     bool runOnModule(Module &M) override;
82 
83     void getAnalysisUsage(AnalysisUsage &AU) const override {
84       AU.setPreservesAll();
85     }
86   };
87 
88   class StripDeadDebugInfo : public ModulePass {
89   public:
90     static char ID; // Pass identification, replacement for typeid
91     explicit StripDeadDebugInfo()
92       : ModulePass(ID) {
93         initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
94       }
95 
96     bool runOnModule(Module &M) override;
97 
98     void getAnalysisUsage(AnalysisUsage &AU) const override {
99       AU.setPreservesAll();
100     }
101   };
102 }
103 
104 char StripSymbols::ID = 0;
105 INITIALIZE_PASS(StripSymbols, "strip",
106                 "Strip all symbols from a module", false, false)
107 
108 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
109   return new StripSymbols(OnlyDebugInfo);
110 }
111 
112 char StripNonDebugSymbols::ID = 0;
113 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
114                 "Strip all symbols, except dbg symbols, from a module",
115                 false, false)
116 
117 ModulePass *llvm::createStripNonDebugSymbolsPass() {
118   return new StripNonDebugSymbols();
119 }
120 
121 char StripDebugDeclare::ID = 0;
122 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
123                 "Strip all llvm.dbg.declare intrinsics", false, false)
124 
125 ModulePass *llvm::createStripDebugDeclarePass() {
126   return new StripDebugDeclare();
127 }
128 
129 char StripDeadDebugInfo::ID = 0;
130 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
131                 "Strip debug info for unused symbols", false, false)
132 
133 ModulePass *llvm::createStripDeadDebugInfoPass() {
134   return new StripDeadDebugInfo();
135 }
136 
137 /// OnlyUsedBy - Return true if V is only used by Usr.
138 static bool OnlyUsedBy(Value *V, Value *Usr) {
139   for (User *U : V->users())
140     if (U != Usr)
141       return false;
142 
143   return true;
144 }
145 
146 static void RemoveDeadConstant(Constant *C) {
147   assert(C->use_empty() && "Constant is not dead!");
148   SmallPtrSet<Constant*, 4> Operands;
149   for (Value *Op : C->operands())
150     if (OnlyUsedBy(Op, C))
151       Operands.insert(cast<Constant>(Op));
152   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
153     if (!GV->hasLocalLinkage()) return;   // Don't delete non-static globals.
154     GV->eraseFromParent();
155   } else if (!isa<Function>(C)) {
156     // FIXME: Why does the type of the constant matter here?
157     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType()) ||
158         isa<VectorType>(C->getType()))
159       C->destroyConstant();
160   }
161 
162   // If the constant referenced anything, see if we can delete it as well.
163   for (Constant *O : Operands)
164     RemoveDeadConstant(O);
165 }
166 
167 // Strip the symbol table of its names.
168 //
169 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
170   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
171     Value *V = VI->getValue();
172     ++VI;
173     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
174       if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
175         // Set name to "", removing from symbol table!
176         V->setName("");
177     }
178   }
179 }
180 
181 // Strip any named types of their names.
182 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
183   TypeFinder StructTypes;
184   StructTypes.run(M, false);
185 
186   for (StructType *STy : StructTypes) {
187     if (STy->isLiteral() || STy->getName().empty()) continue;
188 
189     if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
190       continue;
191 
192     STy->setName("");
193   }
194 }
195 
196 /// Find values that are marked as llvm.used.
197 static void findUsedValues(GlobalVariable *LLVMUsed,
198                            SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
199   if (!LLVMUsed) return;
200   UsedValues.insert(LLVMUsed);
201 
202   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
203 
204   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
205     if (GlobalValue *GV =
206           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
207       UsedValues.insert(GV);
208 }
209 
210 /// StripSymbolNames - Strip symbol names.
211 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
212 
213   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
214   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
215   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
216 
217   for (GlobalVariable &GV : M.globals()) {
218     if (GV.hasLocalLinkage() && !llvmUsedValues.contains(&GV))
219       if (!PreserveDbgInfo || !GV.getName().startswith("llvm.dbg"))
220         GV.setName(""); // Internal symbols can't participate in linkage
221   }
222 
223   for (Function &I : M) {
224     if (I.hasLocalLinkage() && !llvmUsedValues.contains(&I))
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
271           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
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
287       RemoveDeadConstant(C);
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 
299 /// Collects compilation units referenced by functions or lexical scopes.
300 /// Accepts any DIScope and uses recursive bottom-up approach to reach either
301 /// DISubprogram or DILexicalBlockBase.
302 static void
303 collectCUsWithScope(const DIScope *Scope, std::set<DICompileUnit *> &LiveCUs,
304                     SmallPtrSet<const DIScope *, 8> &VisitedScopes) {
305   if (!Scope)
306     return;
307 
308   auto InS = VisitedScopes.insert(Scope);
309   if (!InS.second)
310     return;
311 
312   if (const auto *SP = dyn_cast<DISubprogram>(Scope)) {
313     if (SP->getUnit())
314       LiveCUs.insert(SP->getUnit());
315     return;
316   }
317   if (const auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
318     const DISubprogram *SP = LB->getSubprogram();
319     if (SP && SP->getUnit())
320       LiveCUs.insert(SP->getUnit());
321     return;
322   }
323 
324   collectCUsWithScope(Scope->getScope(), LiveCUs, VisitedScopes);
325 }
326 
327 static void
328 collectCUsForInlinedFuncs(const DILocation *Loc,
329                           std::set<DICompileUnit *> &LiveCUs,
330                           SmallPtrSet<const DIScope *, 8> &VisitedScopes) {
331   if (!Loc || !Loc->getInlinedAt())
332     return;
333   collectCUsWithScope(Loc->getScope(), LiveCUs, VisitedScopes);
334   collectCUsForInlinedFuncs(Loc->getInlinedAt(), LiveCUs, VisitedScopes);
335 }
336 
337 static bool stripDeadDebugInfoImpl(Module &M) {
338   bool Changed = false;
339 
340   LLVMContext &C = M.getContext();
341 
342   // Find all debug info in F. This is actually overkill in terms of what we
343   // want to do, but we want to try and be as resilient as possible in the face
344   // of potential debug info changes by using the formal interfaces given to us
345   // as much as possible.
346   DebugInfoFinder F;
347   F.processModule(M);
348 
349   // For each compile unit, find the live set of global variables/functions and
350   // replace the current list of potentially dead global variables/functions
351   // with the live list.
352   SmallVector<Metadata *, 64> LiveGlobalVariables;
353   DenseSet<DIGlobalVariableExpression *> VisitedSet;
354 
355   std::set<DIGlobalVariableExpression *> LiveGVs;
356   for (GlobalVariable &GV : M.globals()) {
357     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
358     GV.getDebugInfo(GVEs);
359     for (auto *GVE : GVEs)
360       LiveGVs.insert(GVE);
361   }
362 
363   std::set<DICompileUnit *> LiveCUs;
364   SmallPtrSet<const DIScope *, 8> VisitedScopes;
365   // Any CU is live if is referenced from a subprogram metadata that is attached
366   // to a function defined or inlined in the module.
367   for (const Function &Fn : M.functions()) {
368     collectCUsWithScope(Fn.getSubprogram(), LiveCUs, VisitedScopes);
369     for (const_inst_iterator I = inst_begin(&Fn), E = inst_end(&Fn); I != E;
370          ++I) {
371       if (!I->getDebugLoc())
372         continue;
373       const DILocation *DILoc = I->getDebugLoc().get();
374       collectCUsForInlinedFuncs(DILoc, LiveCUs, VisitedScopes);
375     }
376   }
377 
378   bool HasDeadCUs = false;
379   for (DICompileUnit *DIC : F.compile_units()) {
380     // Create our live global variable list.
381     bool GlobalVariableChange = false;
382     for (auto *DIG : DIC->getGlobalVariables()) {
383       if (DIG->getExpression() && DIG->getExpression()->isConstant())
384         LiveGVs.insert(DIG);
385 
386       // Make sure we only visit each global variable only once.
387       if (!VisitedSet.insert(DIG).second)
388         continue;
389 
390       // If a global variable references DIG, the global variable is live.
391       if (LiveGVs.count(DIG))
392         LiveGlobalVariables.push_back(DIG);
393       else
394         GlobalVariableChange = true;
395     }
396 
397     if (!LiveGlobalVariables.empty())
398       LiveCUs.insert(DIC);
399     else if (!LiveCUs.count(DIC))
400       HasDeadCUs = true;
401 
402     // If we found dead global variables, replace the current global
403     // variable list with our new live global variable list.
404     if (GlobalVariableChange) {
405       DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
406       Changed = true;
407     }
408 
409     // Reset lists for the next iteration.
410     LiveGlobalVariables.clear();
411   }
412 
413   if (HasDeadCUs) {
414     // Delete the old node and replace it with a new one
415     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
416     NMD->clearOperands();
417     if (!LiveCUs.empty()) {
418       for (DICompileUnit *CU : LiveCUs)
419         NMD->addOperand(CU);
420     }
421     Changed = true;
422   }
423 
424   return Changed;
425 }
426 
427 /// Remove any debug info for global variables/functions in the given module for
428 /// which said global variable/function no longer exists (i.e. is null).
429 ///
430 /// Debugging information is encoded in llvm IR using metadata. This is designed
431 /// such a way that debug info for symbols preserved even if symbols are
432 /// optimized away by the optimizer. This special pass removes debug info for
433 /// such symbols.
434 bool StripDeadDebugInfo::runOnModule(Module &M) {
435   if (skipModule(M))
436     return false;
437   return stripDeadDebugInfoImpl(M);
438 }
439 
440 PreservedAnalyses StripSymbolsPass::run(Module &M, ModuleAnalysisManager &AM) {
441   StripDebugInfo(M);
442   StripSymbolNames(M, false);
443   return PreservedAnalyses::all();
444 }
445 
446 PreservedAnalyses StripNonDebugSymbolsPass::run(Module &M,
447                                                 ModuleAnalysisManager &AM) {
448   StripSymbolNames(M, true);
449   return PreservedAnalyses::all();
450 }
451 
452 PreservedAnalyses StripDebugDeclarePass::run(Module &M,
453                                              ModuleAnalysisManager &AM) {
454   stripDebugDeclareImpl(M);
455   return PreservedAnalyses::all();
456 }
457 
458 PreservedAnalyses StripDeadDebugInfoPass::run(Module &M,
459                                               ModuleAnalysisManager &AM) {
460   stripDeadDebugInfoImpl(M);
461   return PreservedAnalyses::all();
462 }
463