LLVM API Documentation

StripSymbols.cpp
Go to the documentation of this file.
00001 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // The StripSymbols transformation implements code stripping. Specifically, it
00011 // can delete:
00012 //
00013 //   * names for virtual registers
00014 //   * symbols for internal globals and functions
00015 //   * debug information
00016 //
00017 // Note that this transformation makes code much less readable, so it should
00018 // only be used in situations where the 'strip' utility would be used, such as
00019 // reducing code size or making it harder to reverse engineer code.
00020 //
00021 //===----------------------------------------------------------------------===//
00022 
00023 #include "llvm/Transforms/IPO.h"
00024 #include "llvm/ADT/DenseMap.h"
00025 #include "llvm/ADT/SmallPtrSet.h"
00026 #include "llvm/IR/Constants.h"
00027 #include "llvm/IR/DebugInfo.h"
00028 #include "llvm/IR/DerivedTypes.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/Module.h"
00031 #include "llvm/IR/TypeFinder.h"
00032 #include "llvm/IR/ValueSymbolTable.h"
00033 #include "llvm/Pass.h"
00034 #include "llvm/Transforms/Utils/Local.h"
00035 using namespace llvm;
00036 
00037 namespace {
00038   class StripSymbols : public ModulePass {
00039     bool OnlyDebugInfo;
00040   public:
00041     static char ID; // Pass identification, replacement for typeid
00042     explicit StripSymbols(bool ODI = false)
00043       : ModulePass(ID), OnlyDebugInfo(ODI) {
00044         initializeStripSymbolsPass(*PassRegistry::getPassRegistry());
00045       }
00046 
00047     bool runOnModule(Module &M) override;
00048 
00049     void getAnalysisUsage(AnalysisUsage &AU) const override {
00050       AU.setPreservesAll();
00051     }
00052   };
00053 
00054   class StripNonDebugSymbols : public ModulePass {
00055   public:
00056     static char ID; // Pass identification, replacement for typeid
00057     explicit StripNonDebugSymbols()
00058       : ModulePass(ID) {
00059         initializeStripNonDebugSymbolsPass(*PassRegistry::getPassRegistry());
00060       }
00061 
00062     bool runOnModule(Module &M) override;
00063 
00064     void getAnalysisUsage(AnalysisUsage &AU) const override {
00065       AU.setPreservesAll();
00066     }
00067   };
00068 
00069   class StripDebugDeclare : public ModulePass {
00070   public:
00071     static char ID; // Pass identification, replacement for typeid
00072     explicit StripDebugDeclare()
00073       : ModulePass(ID) {
00074         initializeStripDebugDeclarePass(*PassRegistry::getPassRegistry());
00075       }
00076 
00077     bool runOnModule(Module &M) override;
00078 
00079     void getAnalysisUsage(AnalysisUsage &AU) const override {
00080       AU.setPreservesAll();
00081     }
00082   };
00083 
00084   class StripDeadDebugInfo : public ModulePass {
00085   public:
00086     static char ID; // Pass identification, replacement for typeid
00087     explicit StripDeadDebugInfo()
00088       : ModulePass(ID) {
00089         initializeStripDeadDebugInfoPass(*PassRegistry::getPassRegistry());
00090       }
00091 
00092     bool runOnModule(Module &M) override;
00093 
00094     void getAnalysisUsage(AnalysisUsage &AU) const override {
00095       AU.setPreservesAll();
00096     }
00097   };
00098 }
00099 
00100 char StripSymbols::ID = 0;
00101 INITIALIZE_PASS(StripSymbols, "strip",
00102                 "Strip all symbols from a module", false, false)
00103 
00104 ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) {
00105   return new StripSymbols(OnlyDebugInfo);
00106 }
00107 
00108 char StripNonDebugSymbols::ID = 0;
00109 INITIALIZE_PASS(StripNonDebugSymbols, "strip-nondebug",
00110                 "Strip all symbols, except dbg symbols, from a module",
00111                 false, false)
00112 
00113 ModulePass *llvm::createStripNonDebugSymbolsPass() {
00114   return new StripNonDebugSymbols();
00115 }
00116 
00117 char StripDebugDeclare::ID = 0;
00118 INITIALIZE_PASS(StripDebugDeclare, "strip-debug-declare",
00119                 "Strip all llvm.dbg.declare intrinsics", false, false)
00120 
00121 ModulePass *llvm::createStripDebugDeclarePass() {
00122   return new StripDebugDeclare();
00123 }
00124 
00125 char StripDeadDebugInfo::ID = 0;
00126 INITIALIZE_PASS(StripDeadDebugInfo, "strip-dead-debug-info",
00127                 "Strip debug info for unused symbols", false, false)
00128 
00129 ModulePass *llvm::createStripDeadDebugInfoPass() {
00130   return new StripDeadDebugInfo();
00131 }
00132 
00133 /// OnlyUsedBy - Return true if V is only used by Usr.
00134 static bool OnlyUsedBy(Value *V, Value *Usr) {
00135   for (User *U : V->users())
00136     if (U != Usr)
00137       return false;
00138 
00139   return true;
00140 }
00141 
00142 static void RemoveDeadConstant(Constant *C) {
00143   assert(C->use_empty() && "Constant is not dead!");
00144   SmallPtrSet<Constant*, 4> Operands;
00145   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
00146     if (OnlyUsedBy(C->getOperand(i), C))
00147       Operands.insert(cast<Constant>(C->getOperand(i)));
00148   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00149     if (!GV->hasLocalLinkage()) return;   // Don't delete non-static globals.
00150     GV->eraseFromParent();
00151   }
00152   else if (!isa<Function>(C))
00153     if (isa<CompositeType>(C->getType()))
00154       C->destroyConstant();
00155 
00156   // If the constant referenced anything, see if we can delete it as well.
00157   for (SmallPtrSet<Constant*, 4>::iterator OI = Operands.begin(),
00158          OE = Operands.end(); OI != OE; ++OI)
00159     RemoveDeadConstant(*OI);
00160 }
00161 
00162 // Strip the symbol table of its names.
00163 //
00164 static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) {
00165   for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) {
00166     Value *V = VI->getValue();
00167     ++VI;
00168     if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasLocalLinkage()) {
00169       if (!PreserveDbgInfo || !V->getName().startswith("llvm.dbg"))
00170         // Set name to "", removing from symbol table!
00171         V->setName("");
00172     }
00173   }
00174 }
00175 
00176 // Strip any named types of their names.
00177 static void StripTypeNames(Module &M, bool PreserveDbgInfo) {
00178   TypeFinder StructTypes;
00179   StructTypes.run(M, false);
00180 
00181   for (unsigned i = 0, e = StructTypes.size(); i != e; ++i) {
00182     StructType *STy = StructTypes[i];
00183     if (STy->isLiteral() || STy->getName().empty()) continue;
00184 
00185     if (PreserveDbgInfo && STy->getName().startswith("llvm.dbg"))
00186       continue;
00187 
00188     STy->setName("");
00189   }
00190 }
00191 
00192 /// Find values that are marked as llvm.used.
00193 static void findUsedValues(GlobalVariable *LLVMUsed,
00194                            SmallPtrSet<const GlobalValue*, 8> &UsedValues) {
00195   if (LLVMUsed == 0) return;
00196   UsedValues.insert(LLVMUsed);
00197 
00198   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
00199 
00200   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
00201     if (GlobalValue *GV =
00202           dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
00203       UsedValues.insert(GV);
00204 }
00205 
00206 /// StripSymbolNames - Strip symbol names.
00207 static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) {
00208 
00209   SmallPtrSet<const GlobalValue*, 8> llvmUsedValues;
00210   findUsedValues(M.getGlobalVariable("llvm.used"), llvmUsedValues);
00211   findUsedValues(M.getGlobalVariable("llvm.compiler.used"), llvmUsedValues);
00212 
00213   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00214        I != E; ++I) {
00215     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
00216       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
00217         I->setName("");     // Internal symbols can't participate in linkage
00218   }
00219 
00220   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00221     if (I->hasLocalLinkage() && llvmUsedValues.count(I) == 0)
00222       if (!PreserveDbgInfo || !I->getName().startswith("llvm.dbg"))
00223         I->setName("");     // Internal symbols can't participate in linkage
00224     StripSymtab(I->getValueSymbolTable(), PreserveDbgInfo);
00225   }
00226 
00227   // Remove all names from types.
00228   StripTypeNames(M, PreserveDbgInfo);
00229 
00230   return true;
00231 }
00232 
00233 bool StripSymbols::runOnModule(Module &M) {
00234   bool Changed = false;
00235   Changed |= StripDebugInfo(M);
00236   if (!OnlyDebugInfo)
00237     Changed |= StripSymbolNames(M, false);
00238   return Changed;
00239 }
00240 
00241 bool StripNonDebugSymbols::runOnModule(Module &M) {
00242   return StripSymbolNames(M, true);
00243 }
00244 
00245 bool StripDebugDeclare::runOnModule(Module &M) {
00246 
00247   Function *Declare = M.getFunction("llvm.dbg.declare");
00248   std::vector<Constant*> DeadConstants;
00249 
00250   if (Declare) {
00251     while (!Declare->use_empty()) {
00252       CallInst *CI = cast<CallInst>(Declare->user_back());
00253       Value *Arg1 = CI->getArgOperand(0);
00254       Value *Arg2 = CI->getArgOperand(1);
00255       assert(CI->use_empty() && "llvm.dbg intrinsic should have void result");
00256       CI->eraseFromParent();
00257       if (Arg1->use_empty()) {
00258         if (Constant *C = dyn_cast<Constant>(Arg1))
00259           DeadConstants.push_back(C);
00260         else
00261           RecursivelyDeleteTriviallyDeadInstructions(Arg1);
00262       }
00263       if (Arg2->use_empty())
00264         if (Constant *C = dyn_cast<Constant>(Arg2))
00265           DeadConstants.push_back(C);
00266     }
00267     Declare->eraseFromParent();
00268   }
00269 
00270   while (!DeadConstants.empty()) {
00271     Constant *C = DeadConstants.back();
00272     DeadConstants.pop_back();
00273     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00274       if (GV->hasLocalLinkage())
00275         RemoveDeadConstant(GV);
00276     } else
00277       RemoveDeadConstant(C);
00278   }
00279 
00280   return true;
00281 }
00282 
00283 /// Remove any debug info for global variables/functions in the given module for
00284 /// which said global variable/function no longer exists (i.e. is null).
00285 ///
00286 /// Debugging information is encoded in llvm IR using metadata. This is designed
00287 /// such a way that debug info for symbols preserved even if symbols are
00288 /// optimized away by the optimizer. This special pass removes debug info for
00289 /// such symbols.
00290 bool StripDeadDebugInfo::runOnModule(Module &M) {
00291   bool Changed = false;
00292 
00293   LLVMContext &C = M.getContext();
00294 
00295   // Find all debug info in F. This is actually overkill in terms of what we
00296   // want to do, but we want to try and be as resilient as possible in the face
00297   // of potential debug info changes by using the formal interfaces given to us
00298   // as much as possible.
00299   DebugInfoFinder F;
00300   F.processModule(M);
00301 
00302   // For each compile unit, find the live set of global variables/functions and
00303   // replace the current list of potentially dead global variables/functions
00304   // with the live list.
00305   SmallVector<Value *, 64> LiveGlobalVariables;
00306   SmallVector<Value *, 64> LiveSubprograms;
00307   DenseSet<const MDNode *> VisitedSet;
00308 
00309   for (DICompileUnit DIC : F.compile_units()) {
00310     assert(DIC.Verify() && "DIC must verify as a DICompileUnit.");
00311 
00312     // Create our live subprogram list.
00313     DIArray SPs = DIC.getSubprograms();
00314     bool SubprogramChange = false;
00315     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
00316       DISubprogram DISP(SPs.getElement(i));
00317       assert(DISP.Verify() && "DISP must verify as a DISubprogram.");
00318 
00319       // Make sure we visit each subprogram only once.
00320       if (!VisitedSet.insert(DISP).second)
00321         continue;
00322 
00323       // If the function referenced by DISP is not null, the function is live.
00324       if (DISP.getFunction())
00325         LiveSubprograms.push_back(DISP);
00326       else
00327         SubprogramChange = true;
00328     }
00329 
00330     // Create our live global variable list.
00331     DIArray GVs = DIC.getGlobalVariables();
00332     bool GlobalVariableChange = false;
00333     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
00334       DIGlobalVariable DIG(GVs.getElement(i));
00335       assert(DIG.Verify() && "DIG must verify as DIGlobalVariable.");
00336 
00337       // Make sure we only visit each global variable only once.
00338       if (!VisitedSet.insert(DIG).second)
00339         continue;
00340 
00341       // If the global variable referenced by DIG is not null, the global
00342       // variable is live.
00343       if (DIG.getGlobal())
00344         LiveGlobalVariables.push_back(DIG);
00345       else
00346         GlobalVariableChange = true;
00347     }
00348 
00349     // If we found dead subprograms or global variables, replace the current
00350     // subprogram list/global variable list with our new live subprogram/global
00351     // variable list.
00352     if (SubprogramChange) {
00353       // Make sure that 9 is still the index of the subprograms. This is to make
00354       // sure that an assert is hit if the location of the subprogram array
00355       // changes. This is just to make sure that this is updated if such an
00356       // event occurs.
00357       assert(DIC->getNumOperands() >= 10 &&
00358              SPs == DIC->getOperand(9) &&
00359              "DICompileUnits is expected to store Subprograms in operand "
00360              "9.");
00361       DIC->replaceOperandWith(9, MDNode::get(C, LiveSubprograms));
00362       Changed = true;
00363     }
00364 
00365     if (GlobalVariableChange) {
00366       // Make sure that 10 is still the index of global variables. This is to
00367       // make sure that an assert is hit if the location of the subprogram array
00368       // changes. This is just to make sure that this index is updated if such
00369       // an event occurs.
00370       assert(DIC->getNumOperands() >= 11 &&
00371              GVs == DIC->getOperand(10) &&
00372              "DICompileUnits is expected to store Global Variables in operand "
00373              "10.");
00374       DIC->replaceOperandWith(10, MDNode::get(C, LiveGlobalVariables));
00375       Changed = true;
00376     }
00377 
00378     // Reset lists for the next iteration.
00379     LiveSubprograms.clear();
00380     LiveGlobalVariables.clear();
00381   }
00382 
00383   return Changed;
00384 }