xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/IPO/StripSymbols.cpp (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
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/ADT/SmallPtrSet.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DebugInfo.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/TypeFinder.h"
29 #include "llvm/IR/ValueSymbolTable.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 using namespace llvm;
35 
36 namespace {
37   class 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         initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
44       }
45 
46     bool runOnModule(Module &M) override;
47 
48     void getAnalysisUsage(AnalysisUsage &AU) const override {
49       AU.setPreservesAll();
50     }
51   };
52 
53   class StripNonDebugSymbols : public ModulePass {
54   public:
55     static char ID; // Pass identification, replacement for typeid
56     explicit StripNonDebugSymbols()
57       : ModulePass(ID) {
58         initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
59       }
60 
61     bool runOnModule(Module &M) override;
62 
63     void getAnalysisUsage(AnalysisUsage &AU) const override {
64       AU.setPreservesAll();
65     }
66   };
67 
68   class StripDebugDeclare : public ModulePass {
69   public:
70     static char ID; // Pass identification, replacement for typeid
71     explicit StripDebugDeclare()
72       : ModulePass(ID) {
73         initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
74       }
75 
76     bool runOnModule(Module &M) override;
77 
78     void getAnalysisUsage(AnalysisUsage &AU) const override {
79       AU.setPreservesAll();
80     }
81   };
82 
83   class StripDeadDebugInfo : public ModulePass {
84   public:
85     static char ID; // Pass identification, replacement for typeid
86     explicit StripDeadDebugInfo()
87       : ModulePass(ID) {
88         initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
89       }
90 
91     bool runOnModule(Module &M) override;
92 
93     void getAnalysisUsage(AnalysisUsage &AU) const override {
94       AU.setPreservesAll();
95     }
96   };
97 }
98 
99 char StripSymbols::ID = 0;
100 INITIALIZE_PASS(StripSymbols, "strip",
101                 "Strip all symbols from a module", false, false)
102 
103 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
104   return new StripSymbols(OnlyDebugInfo);
105 }
106 
107 char StripNonDebugSymbols::ID = 0;
108 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
109                 "Strip all symbols, except dbg symbols, from a module",
110                 false, false)
111 
112 ModulePass *llvm::createStripNonDebugSymbolsPass() {
113   return new StripNonDebugSymbols();
114 }
115 
116 char StripDebugDeclare::ID = 0;
117 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
118                 "Strip all llvm.dbg.declare intrinsics", false, false)
119 
120 ModulePass *llvm::createStripDebugDeclarePass() {
121   return new StripDebugDeclare();
122 }
123 
124 char StripDeadDebugInfo::ID = 0;
125 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
126                 "Strip debug info for unused symbols", false, false)
127 
128 ModulePass *llvm::createStripDeadDebugInfoPass() {
129   return new StripDeadDebugInfo();
130 }
131 
132 /// OnlyUsedBy - Return true if V is only used by Usr.
133 static bool OnlyUsedBy(Value *V, Value *Usr) {
134   for (User *U : V->users())
135     if (U != Usr)
136       return false;
137 
138   return true;
139 }
140 
141 static void RemoveDeadConstant(Constant *C) {
142   assert(C->use_empty() && "Constant is not dead!");
143   SmallPtrSet<Constant*, 4> Operands;
144   for (Value *Op : C->operands())
145     if (OnlyUsedBy(Op, C))
146       Operands.insert(cast<Constant>(Op));
147   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
148     if (!GV->hasLocalLinkage()) return;   // Don't delete non-static globals.
149     GV->eraseFromParent();
150   } else if (!isa<Function>(C)) {
151     // FIXME: Why does the type of the constant matter here?
152     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType()) ||
153         isa<VectorType>(C->getType()))
154       C->destroyConstant();
155   }
156 
157   // If the constant referenced anything, see if we can delete it as well.
158   for (Constant *O : Operands)
159     RemoveDeadConstant(O);
160 }
161 
162 // Strip the symbol table of its names.
163 //
164 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
165   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
166     Value *V = VI->getValue();
167     ++VI;
168     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
169       if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
170         // Set name to "", removing from symbol table!
171         V->setName("");
172     }
173   }
174 }
175 
176 // Strip any named types of their names.
177 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
178   TypeFinder StructTypes;
179   StructTypes.run(M, false);
180 
181   for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
182     StructType *STy = StructTypes[i];
183     if (STy->isLiteral() || STy->getName().empty()) continue;
184 
185     if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
186       continue;
187 
188     STy->setName("");
189   }
190 }
191 
192 /// Find values that are marked as llvm.used.
193 static void findUsedValues(GlobalVariable *LLVMUsed,
194                            SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
195   if (!LLVMUsed) return;
196   UsedValues.insert(LLVMUsed);
197 
198   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
199 
200   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
201     if (GlobalValue *GV =
202           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
203       UsedValues.insert(GV);
204 }
205 
206 /// StripSymbolNames - Strip symbol names.
207 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
208 
209   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
210   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
211   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
212 
213   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
214        I != E; ++I) {
215     if (I->hasLocalLinkage() && llvmUsedValues.count(&*I) == 0)
216       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
217         I->setName("");     // Internal symbols can't participate in linkage
218   }
219 
220   for (Function &I : M) {
221     if (I.hasLocalLinkage() && llvmUsedValues.count(&I) == 0)
222       if (!PreserveDbgInfo || !I.getName().startswith("llvm.dbg"))
223         I.setName(""); // Internal symbols can't participate in linkage
224     if (auto *Symtab = I.getValueSymbolTable())
225       StripSymtab(*Symtab, PreserveDbgInfo);
226   }
227 
228   // Remove all names from types.
229   StripTypeNames(M, PreserveDbgInfo);
230 
231   return true;
232 }
233 
234 bool StripSymbols::runOnModule(Module &M) {
235   if (skipModule(M))
236     return false;
237 
238   bool Changed = false;
239   Changed |= StripDebugInfo(M);
240   if (!OnlyDebugInfo)
241     Changed |= StripSymbolNames(M, false);
242   return Changed;
243 }
244 
245 bool StripNonDebugSymbols::runOnModule(Module &M) {
246   if (skipModule(M))
247     return false;
248 
249   return StripSymbolNames(M, true);
250 }
251 
252 bool StripDebugDeclare::runOnModule(Module &M) {
253   if (skipModule(M))
254     return false;
255 
256   Function *Declare = M.getFunction("llvm.dbg.declare");
257   std::vector<Constant*> DeadConstants;
258 
259   if (Declare) {
260     while (!Declare->use_empty()) {
261       CallInst *CI = cast<CallInst>(Declare->user_back());
262       Value *Arg1 = CI->getArgOperand(0);
263       Value *Arg2 = CI->getArgOperand(1);
264       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
265       CI->eraseFromParent();
266       if (Arg1->use_empty()) {
267         if (Constant *C = dyn_cast<Constant>(Arg1))
268           DeadConstants.push_back(C);
269         else
270           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
271       }
272       if (Arg2->use_empty())
273         if (Constant *C = dyn_cast<Constant>(Arg2))
274           DeadConstants.push_back(C);
275     }
276     Declare->eraseFromParent();
277   }
278 
279   while (!DeadConstants.empty()) {
280     Constant *C = DeadConstants.back();
281     DeadConstants.pop_back();
282     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
283       if (GV->hasLocalLinkage())
284         RemoveDeadConstant(GV);
285     } else
286       RemoveDeadConstant(C);
287   }
288 
289   return true;
290 }
291 
292 /// Remove any debug info for global variables/functions in the given module for
293 /// which said global variable/function no longer exists (i.e. is null).
294 ///
295 /// Debugging information is encoded in llvm IR using metadata. This is designed
296 /// such a way that debug info for symbols preserved even if symbols are
297 /// optimized away by the optimizer. This special pass removes debug info for
298 /// such symbols.
299 bool StripDeadDebugInfo::runOnModule(Module &M) {
300   if (skipModule(M))
301     return false;
302 
303   bool Changed = false;
304 
305   LLVMContext &C = M.getContext();
306 
307   // Find all debug info in F. This is actually overkill in terms of what we
308   // want to do, but we want to try and be as resilient as possible in the face
309   // of potential debug info changes by using the formal interfaces given to us
310   // as much as possible.
311   DebugInfoFinder F;
312   F.processModule(M);
313 
314   // For each compile unit, find the live set of global variables/functions and
315   // replace the current list of potentially dead global variables/functions
316   // with the live list.
317   SmallVector<Metadata *, 64> LiveGlobalVariables;
318   DenseSet<DIGlobalVariableExpression *> VisitedSet;
319 
320   std::set<DIGlobalVariableExpression *> LiveGVs;
321   for (GlobalVariable &GV : M.globals()) {
322     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
323     GV.getDebugInfo(GVEs);
324     for (auto *GVE : GVEs)
325       LiveGVs.insert(GVE);
326   }
327 
328   std::set<DICompileUnit *> LiveCUs;
329   // Any CU referenced from a subprogram is live.
330   for (DISubprogram *SP : F.subprograms()) {
331     if (SP->getUnit())
332       LiveCUs.insert(SP->getUnit());
333   }
334 
335   bool HasDeadCUs = false;
336   for (DICompileUnit *DIC : F.compile_units()) {
337     // Create our live global variable list.
338     bool GlobalVariableChange = false;
339     for (auto *DIG : DIC->getGlobalVariables()) {
340       if (DIG->getExpression() && DIG->getExpression()->isConstant())
341         LiveGVs.insert(DIG);
342 
343       // Make sure we only visit each global variable only once.
344       if (!VisitedSet.insert(DIG).second)
345         continue;
346 
347       // If a global variable references DIG, the global variable is live.
348       if (LiveGVs.count(DIG))
349         LiveGlobalVariables.push_back(DIG);
350       else
351         GlobalVariableChange = true;
352     }
353 
354     if (!LiveGlobalVariables.empty())
355       LiveCUs.insert(DIC);
356     else if (!LiveCUs.count(DIC))
357       HasDeadCUs = true;
358 
359     // If we found dead global variables, replace the current global
360     // variable list with our new live global variable list.
361     if (GlobalVariableChange) {
362       DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables));
363       Changed = true;
364     }
365 
366     // Reset lists for the next iteration.
367     LiveGlobalVariables.clear();
368   }
369 
370   if (HasDeadCUs) {
371     // Delete the old node and replace it with a new one
372     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
373     NMD->clearOperands();
374     if (!LiveCUs.empty()) {
375       for (DICompileUnit *CU : LiveCUs)
376         NMD->addOperand(CU);
377     }
378     Changed = true;
379   }
380 
381   return Changed;
382 }
383