| 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 "IPOOptions.h" |
| 24 | |
| 25 | #include "llvm/ADT/SmallPtrSet.h" |
| 26 | #include "llvm/ADT/SmallVector.h" |
| 27 | #include "llvm/IR/Constants.h" |
| 28 | #include "llvm/IR/DebugInfo.h" |
| 29 | #include "llvm/IR/DerivedTypes.h" |
| 30 | #include "llvm/IR/InstIterator.h" |
| 31 | #include "llvm/IR/Instructions.h" |
| 32 | #include "llvm/IR/Metadata.h" |
| 33 | #include "llvm/IR/Module.h" |
| 34 | #include "llvm/IR/PassManager.h" |
| 35 | #include "llvm/IR/TypeFinder.h" |
| 36 | #include "llvm/IR/ValueSymbolTable.h" |
| 37 | #include "llvm/Support/Casting.h" |
| 38 | #include "llvm/Transforms/Utils/Local.h" |
| 39 | |
| 40 | using namespace llvm; |
| 41 | |
| 42 | /// OnlyUsedBy - Return true if V is only used by Usr. |
| 43 | static bool OnlyUsedBy(Value *V, Value *Usr) { |
| 44 | for (User *U : V->users()) |
| 45 | if (U != Usr) |
| 46 | return false; |
| 47 | |
| 48 | return true; |
| 49 | } |
| 50 | |
| 51 | static void RemoveDeadConstant(Constant *C) { |
| 52 | assert(C->use_empty() && "Constant is not dead!" ); |
| 53 | SmallPtrSet<Constant*, 4> Operands; |
| 54 | for (Value *Op : C->operands()) |
| 55 | if (OnlyUsedBy(V: Op, Usr: C)) |
| 56 | Operands.insert(Ptr: cast<Constant>(Val: Op)); |
| 57 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: C)) { |
| 58 | if (!GV->hasLocalLinkage()) return; // Don't delete non-static globals. |
| 59 | GV->eraseFromParent(); |
| 60 | } else if (!isa<Function>(Val: C)) { |
| 61 | // FIXME: Why does the type of the constant matter here? |
| 62 | if (isa<StructType>(Val: C->getType()) || isa<ArrayType>(Val: C->getType()) || |
| 63 | isa<VectorType>(Val: C->getType())) |
| 64 | C->destroyConstant(); |
| 65 | } |
| 66 | |
| 67 | // If the constant referenced anything, see if we can delete it as well. |
| 68 | for (Constant *O : Operands) |
| 69 | RemoveDeadConstant(C: O); |
| 70 | } |
| 71 | |
| 72 | // Strip the symbol table of its names. |
| 73 | // |
| 74 | static void StripSymtab(ValueSymbolTable &ST, bool PreserveDbgInfo) { |
| 75 | // Collect the values to rename first: setName("") removes the value from the |
| 76 | // symbol table, which invalidates iterators into it. |
| 77 | SmallVector<Value *, 0> ToStrip; |
| 78 | for (const ValueName &VN : ST) { |
| 79 | Value *V = VN.getValue(); |
| 80 | if (!isa<GlobalValue>(Val: V) || cast<GlobalValue>(Val: V)->hasLocalLinkage()) |
| 81 | if (!PreserveDbgInfo || !V->getName().starts_with(Prefix: "llvm.dbg" )) |
| 82 | ToStrip.push_back(Elt: V); |
| 83 | } |
| 84 | for (Value *V : ToStrip) |
| 85 | V->setName("" ); |
| 86 | } |
| 87 | |
| 88 | // Strip any named types of their names. |
| 89 | static void StripTypeNames(Module &M, bool PreserveDbgInfo) { |
| 90 | TypeFinder StructTypes; |
| 91 | StructTypes.run(M, onlyNamed: false); |
| 92 | |
| 93 | for (StructType *STy : StructTypes) { |
| 94 | if (STy->isLiteral() || STy->getName().empty()) continue; |
| 95 | |
| 96 | if (PreserveDbgInfo && STy->getName().starts_with(Prefix: "llvm.dbg" )) |
| 97 | continue; |
| 98 | |
| 99 | STy->setName("" ); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Find values that are marked as llvm.used. |
| 104 | static void findUsedValues(GlobalVariable *LLVMUsed, |
| 105 | SmallPtrSetImpl<const GlobalValue*> &UsedValues) { |
| 106 | if (!LLVMUsed) return; |
| 107 | UsedValues.insert(Ptr: LLVMUsed); |
| 108 | |
| 109 | ConstantArray *Inits = cast<ConstantArray>(Val: LLVMUsed->getInitializer()); |
| 110 | |
| 111 | for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) |
| 112 | if (GlobalValue *GV = |
| 113 | dyn_cast<GlobalValue>(Val: Inits->getOperand(i_nocapture: i)->stripPointerCasts())) |
| 114 | UsedValues.insert(Ptr: GV); |
| 115 | } |
| 116 | |
| 117 | /// StripSymbolNames - Strip symbol names. |
| 118 | static bool StripSymbolNames(Module &M, bool PreserveDbgInfo) { |
| 119 | |
| 120 | SmallPtrSet<const GlobalValue*, 8> llvmUsedValues; |
| 121 | findUsedValues(LLVMUsed: M.getGlobalVariable(Name: "llvm.used" ), UsedValues&: llvmUsedValues); |
| 122 | findUsedValues(LLVMUsed: M.getGlobalVariable(Name: "llvm.compiler.used" ), UsedValues&: llvmUsedValues); |
| 123 | |
| 124 | for (GlobalVariable &GV : M.globals()) { |
| 125 | if (GV.hasLocalLinkage() && !llvmUsedValues.contains(Ptr: &GV)) |
| 126 | if (!PreserveDbgInfo || !GV.getName().starts_with(Prefix: "llvm.dbg" )) |
| 127 | GV.setName("" ); // Internal symbols can't participate in linkage |
| 128 | } |
| 129 | |
| 130 | for (Function &I : M) { |
| 131 | if (I.hasLocalLinkage() && !llvmUsedValues.contains(Ptr: &I)) |
| 132 | if (!PreserveDbgInfo || !I.getName().starts_with(Prefix: "llvm.dbg" )) |
| 133 | I.setName("" ); // Internal symbols can't participate in linkage |
| 134 | if (auto *Symtab = I.getValueSymbolTable()) |
| 135 | StripSymtab(ST&: *Symtab, PreserveDbgInfo); |
| 136 | } |
| 137 | |
| 138 | // Remove all names from types. |
| 139 | StripTypeNames(M, PreserveDbgInfo); |
| 140 | |
| 141 | return true; |
| 142 | } |
| 143 | |
| 144 | static bool stripDebugDeclareImpl(Module &M) { |
| 145 | Function *Declare = |
| 146 | Intrinsic::getDeclarationIfExists(M: &M, id: Intrinsic::dbg_declare); |
| 147 | std::vector<Constant*> DeadConstants; |
| 148 | |
| 149 | if (Declare) { |
| 150 | while (!Declare->use_empty()) { |
| 151 | CallInst *CI = cast<CallInst>(Val: Declare->user_back()); |
| 152 | Value *Arg1 = CI->getArgOperand(i: 0); |
| 153 | Value *Arg2 = CI->getArgOperand(i: 1); |
| 154 | assert(CI->use_empty() && "llvm.dbg intrinsic should have void result" ); |
| 155 | CI->eraseFromParent(); |
| 156 | if (Arg1->use_empty()) { |
| 157 | if (Constant *C = dyn_cast<Constant>(Val: Arg1)) |
| 158 | DeadConstants.push_back(x: C); |
| 159 | else |
| 160 | RecursivelyDeleteTriviallyDeadInstructions(V: Arg1); |
| 161 | } |
| 162 | if (Arg2->use_empty()) |
| 163 | if (Constant *C = dyn_cast<Constant>(Val: Arg2)) |
| 164 | DeadConstants.push_back(x: C); |
| 165 | } |
| 166 | Declare->eraseFromParent(); |
| 167 | } |
| 168 | |
| 169 | while (!DeadConstants.empty()) { |
| 170 | Constant *C = DeadConstants.back(); |
| 171 | DeadConstants.pop_back(); |
| 172 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: C)) { |
| 173 | if (GV->hasLocalLinkage()) |
| 174 | RemoveDeadConstant(C: GV); |
| 175 | } else |
| 176 | RemoveDeadConstant(C); |
| 177 | } |
| 178 | |
| 179 | return true; |
| 180 | } |
| 181 | |
| 182 | static bool stripDeadDebugInfoImpl(Module &M) { |
| 183 | const IPOOptions &Opts = getIPOOptions(M); |
| 184 | bool Changed = false; |
| 185 | |
| 186 | LLVMContext &C = M.getContext(); |
| 187 | |
| 188 | // Find all debug info in F. This is actually overkill in terms of what we |
| 189 | // want to do, but we want to try and be as resilient as possible in the face |
| 190 | // of potential debug info changes by using the formal interfaces given to us |
| 191 | // as much as possible. |
| 192 | DebugInfoFinder F; |
| 193 | F.processModule(M); |
| 194 | |
| 195 | // For each compile unit, find the live set of global variables/functions and |
| 196 | // replace the current list of potentially dead global variables/functions |
| 197 | // with the live list. |
| 198 | SmallVector<Metadata *, 64> LiveGlobalVariables; |
| 199 | DenseSet<DIGlobalVariableExpression *> VisitedSet; |
| 200 | |
| 201 | std::set<DIGlobalVariableExpression *> LiveGVs; |
| 202 | for (GlobalVariable &GV : M.globals()) { |
| 203 | SmallVector<DIGlobalVariableExpression *, 1> GVEs; |
| 204 | GV.getDebugInfo(GVs&: GVEs); |
| 205 | for (auto *GVE : GVEs) |
| 206 | LiveGVs.insert(x: GVE); |
| 207 | } |
| 208 | |
| 209 | std::set<DICompileUnit *> LiveCUs; |
| 210 | DebugInfoFinder LiveCUFinder; |
| 211 | for (const Function &F : M.functions()) { |
| 212 | if (auto *SP = cast_or_null<DISubprogram>(Val: F.getSubprogram())) |
| 213 | LiveCUFinder.processSubprogram(SP); |
| 214 | for (const Instruction &I : instructions(F)) |
| 215 | LiveCUFinder.processInstruction(M, I); |
| 216 | } |
| 217 | auto FoundCUs = LiveCUFinder.compile_units(); |
| 218 | LiveCUs.insert(first: FoundCUs.begin(), last: FoundCUs.end()); |
| 219 | |
| 220 | bool HasDeadCUs = false; |
| 221 | for (DICompileUnit *DIC : F.compile_units()) { |
| 222 | // Create our live global variable list. |
| 223 | bool GlobalVariableChange = false; |
| 224 | for (auto *DIG : DIC->getGlobalVariables()) { |
| 225 | if (DIG->getExpression() && DIG->getExpression()->isConstant() && |
| 226 | !Opts.strip_global_constants) |
| 227 | LiveGVs.insert(x: DIG); |
| 228 | |
| 229 | // Make sure we only visit each global variable only once. |
| 230 | if (!VisitedSet.insert(V: DIG).second) |
| 231 | continue; |
| 232 | |
| 233 | // If a global variable references DIG, the global variable is live. |
| 234 | if (LiveGVs.count(x: DIG)) |
| 235 | LiveGlobalVariables.push_back(Elt: DIG); |
| 236 | else |
| 237 | GlobalVariableChange = true; |
| 238 | } |
| 239 | |
| 240 | if (!LiveGlobalVariables.empty()) |
| 241 | LiveCUs.insert(x: DIC); |
| 242 | else if (!LiveCUs.count(x: DIC)) |
| 243 | HasDeadCUs = true; |
| 244 | |
| 245 | // If we found dead global variables, replace the current global |
| 246 | // variable list with our new live global variable list. |
| 247 | if (GlobalVariableChange) { |
| 248 | DIC->replaceGlobalVariables(N: MDTuple::get(Context&: C, MDs: LiveGlobalVariables)); |
| 249 | Changed = true; |
| 250 | } |
| 251 | |
| 252 | // Reset lists for the next iteration. |
| 253 | LiveGlobalVariables.clear(); |
| 254 | } |
| 255 | |
| 256 | if (HasDeadCUs) { |
| 257 | // Delete the old node and replace it with a new one |
| 258 | NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name: "llvm.dbg.cu" ); |
| 259 | NMD->clearOperands(); |
| 260 | if (!LiveCUs.empty()) { |
| 261 | for (DICompileUnit *CU : LiveCUs) |
| 262 | NMD->addOperand(M: CU); |
| 263 | } |
| 264 | Changed = true; |
| 265 | } |
| 266 | |
| 267 | return Changed; |
| 268 | } |
| 269 | |
| 270 | PreservedAnalyses StripSymbolsPass::run(Module &M, ModuleAnalysisManager &AM) { |
| 271 | StripDebugInfo(M); |
| 272 | StripSymbolNames(M, PreserveDbgInfo: false); |
| 273 | PreservedAnalyses PA; |
| 274 | PA.preserveSet<CFGAnalyses>(); |
| 275 | return PA; |
| 276 | } |
| 277 | |
| 278 | PreservedAnalyses StripNonDebugSymbolsPass::run(Module &M, |
| 279 | ModuleAnalysisManager &AM) { |
| 280 | StripSymbolNames(M, PreserveDbgInfo: true); |
| 281 | PreservedAnalyses PA; |
| 282 | PA.preserveSet<CFGAnalyses>(); |
| 283 | return PA; |
| 284 | } |
| 285 | |
| 286 | PreservedAnalyses StripDebugDeclarePass::run(Module &M, |
| 287 | ModuleAnalysisManager &AM) { |
| 288 | stripDebugDeclareImpl(M); |
| 289 | PreservedAnalyses PA; |
| 290 | PA.preserveSet<CFGAnalyses>(); |
| 291 | return PA; |
| 292 | } |
| 293 | |
| 294 | PreservedAnalyses StripDeadDebugInfoPass::run(Module &M, |
| 295 | ModuleAnalysisManager &AM) { |
| 296 | stripDeadDebugInfoImpl(M); |
| 297 | PreservedAnalyses PA; |
| 298 | PA.preserveSet<CFGAnalyses>(); |
| 299 | return PA; |
| 300 | } |
| 301 | |
| 302 | PreservedAnalyses StripDeadCGProfilePass::run(Module &M, |
| 303 | ModuleAnalysisManager &AM) { |
| 304 | auto *CGProf = dyn_cast_or_null<MDTuple>(Val: M.getModuleFlag(Key: "CG Profile" )); |
| 305 | if (!CGProf) |
| 306 | return PreservedAnalyses::all(); |
| 307 | |
| 308 | SmallVector<Metadata *, 16> ValidCGEdges; |
| 309 | for (Metadata *Edge : CGProf->operands()) { |
| 310 | if (auto *EdgeAsNode = dyn_cast_or_null<MDNode>(Val: Edge)) |
| 311 | if (!llvm::is_contained(Range: EdgeAsNode->operands(), Element: nullptr)) |
| 312 | ValidCGEdges.push_back(Elt: Edge); |
| 313 | } |
| 314 | M.setModuleFlag(Behavior: Module::Append, Key: "CG Profile" , |
| 315 | Val: MDTuple::getDistinct(Context&: M.getContext(), MDs: ValidCGEdges)); |
| 316 | return PreservedAnalyses::none(); |
| 317 | } |
| 318 | |