StripSymbols.cpp 14 KB

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