StripSymbols.cpp 13 KB

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