xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/IPO/StripSymbols.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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/Instructions.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/PassManager.h"
30 #include "llvm/IR/TypeFinder.h"
31 #include "llvm/IR/ValueSymbolTable.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/Utils/Local.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) {
46         initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
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) {
61         initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
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) {
76         initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
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) {
91         initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
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 
115 ModulePass *llvm::createStripNonDebugSymbolsPass() {
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 
123 ModulePass *llvm::createStripDebugDeclarePass() {
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 
131 ModulePass *llvm::createStripDeadDebugInfoPass() {
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 
144 static void RemoveDeadConstant(Constant *C) {
145   assert(C->use_empty() && "Constant is not dead!");
146   SmallPtrSet<Constant*, 4> Operands;
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)
162     RemoveDeadConstant(O);
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,
197                            SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
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
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 static bool stripDeadDebugInfoImpl(Module &M) {
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.
308   DebugInfoFinder F;
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;
315   DenseSet<DIGlobalVariableExpression *> VisitedSet;
316 
317   std::set<DIGlobalVariableExpression *> LiveGVs;
318   for (GlobalVariable &GV : M.globals()) {
319     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
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 
394 PreservedAnalyses StripSymbolsPass::run(Module &M, ModuleAnalysisManager &AM) {
395   StripDebugInfo(M);
396   StripSymbolNames(M, false);
397   return PreservedAnalyses::all();
398 }
399 
400 PreservedAnalyses StripNonDebugSymbolsPass::run(Module &M,
401                                                 ModuleAnalysisManager &AM) {
402   StripSymbolNames(M, true);
403   return PreservedAnalyses::all();
404 }
405 
406 PreservedAnalyses StripDebugDeclarePass::run(Module &M,
407                                              ModuleAnalysisManager &AM) {
408   stripDebugDeclareImpl(M);
409   return PreservedAnalyses::all();
410 }
411 
412 PreservedAnalyses StripDeadDebugInfoPass::run(Module &M,
413                                               ModuleAnalysisManager &AM) {
414   stripDeadDebugInfoImpl(M);
415   return PreservedAnalyses::all();
416 }
417