1 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This transform is designed to eliminate unreachable internal globals from the 11 // program. It uses an aggressive algorithm, searching out globals that are 12 // known to be alive. After it finds all of the globals which are needed, it 13 // deletes whatever is left over. This allows it to delete recursive chunks of 14 // the program which are unreachable. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Transforms/IPO/GlobalDCE.h" 19 #include "llvm/ADT/SmallPtrSet.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/Pass.h" 25 #include "llvm/Transforms/IPO.h" 26 #include "llvm/Transforms/Utils/CtorUtils.h" 27 #include "llvm/Transforms/Utils/GlobalStatus.h" 28 #include <unordered_map> 29 using namespace llvm; 30 31 #define DEBUG_TYPE "globaldce" 32 33 STATISTIC(NumAliases , "Number of global aliases removed"); 34 STATISTIC(NumFunctions, "Number of functions removed"); 35 STATISTIC(NumIFuncs, "Number of indirect functions removed"); 36 STATISTIC(NumVariables, "Number of global variables removed"); 37 38 namespace { 39 class GlobalDCELegacyPass : public ModulePass { 40 public: 41 static char ID; // Pass identification, replacement for typeid 42 GlobalDCELegacyPass() : ModulePass(ID) { 43 initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry()); 44 } 45 46 // run - Do the GlobalDCE pass on the specified module, optionally updating 47 // the specified callgraph to reflect the changes. 48 // 49 bool runOnModule(Module &M) override { 50 if (skipModule(M)) 51 return false; 52 53 auto PA = Impl.run(M); 54 return !PA.areAllPreserved(); 55 } 56 57 private: 58 GlobalDCEPass Impl; 59 }; 60 } 61 62 char GlobalDCELegacyPass::ID = 0; 63 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", 64 "Dead Global Elimination", false, false) 65 66 // Public interface to the GlobalDCEPass. 67 ModulePass *llvm::createGlobalDCEPass() { 68 return new GlobalDCELegacyPass(); 69 } 70 71 /// Returns true if F contains only a single "ret" instruction. 72 static bool isEmptyFunction(Function *F) { 73 BasicBlock &Entry = F->getEntryBlock(); 74 if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front())) 75 return false; 76 ReturnInst &RI = cast<ReturnInst>(Entry.front()); 77 return RI.getReturnValue() == nullptr; 78 } 79 80 PreservedAnalyses GlobalDCEPass::run(Module &M) { 81 bool Changed = false; 82 83 // Remove empty functions from the global ctors list. 84 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); 85 86 // Collect the set of members for each comdat. 87 for (Function &F : M) 88 if (Comdat *C = F.getComdat()) 89 ComdatMembers.insert(std::make_pair(C, &F)); 90 for (GlobalVariable &GV : M.globals()) 91 if (Comdat *C = GV.getComdat()) 92 ComdatMembers.insert(std::make_pair(C, &GV)); 93 for (GlobalAlias &GA : M.aliases()) 94 if (Comdat *C = GA.getComdat()) 95 ComdatMembers.insert(std::make_pair(C, &GA)); 96 97 // Loop over the module, adding globals which are obviously necessary. 98 for (Function &F : M) { 99 Changed |= RemoveUnusedGlobalValue(F); 100 // Functions with external linkage are needed if they have a body 101 if (!F.isDeclaration() && !F.hasAvailableExternallyLinkage()) 102 if (!F.isDiscardableIfUnused()) 103 GlobalIsNeeded(&F); 104 } 105 106 for (GlobalVariable &GV : M.globals()) { 107 Changed |= RemoveUnusedGlobalValue(GV); 108 // Externally visible & appending globals are needed, if they have an 109 // initializer. 110 if (!GV.isDeclaration() && !GV.hasAvailableExternallyLinkage()) 111 if (!GV.isDiscardableIfUnused()) 112 GlobalIsNeeded(&GV); 113 } 114 115 for (GlobalAlias &GA : M.aliases()) { 116 Changed |= RemoveUnusedGlobalValue(GA); 117 // Externally visible aliases are needed. 118 if (!GA.isDiscardableIfUnused()) 119 GlobalIsNeeded(&GA); 120 } 121 122 for (GlobalIFunc &GIF : M.ifuncs()) { 123 Changed |= RemoveUnusedGlobalValue(GIF); 124 // Externally visible ifuncs are needed. 125 if (!GIF.isDiscardableIfUnused()) 126 GlobalIsNeeded(&GIF); 127 } 128 129 // Now that all globals which are needed are in the AliveGlobals set, we loop 130 // through the program, deleting those which are not alive. 131 // 132 133 // The first pass is to drop initializers of global variables which are dead. 134 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals 135 for (GlobalVariable &GV : M.globals()) 136 if (!AliveGlobals.count(&GV)) { 137 DeadGlobalVars.push_back(&GV); // Keep track of dead globals 138 if (GV.hasInitializer()) { 139 Constant *Init = GV.getInitializer(); 140 GV.setInitializer(nullptr); 141 if (isSafeToDestroyConstant(Init)) 142 Init->destroyConstant(); 143 } 144 } 145 146 // The second pass drops the bodies of functions which are dead... 147 std::vector<Function *> DeadFunctions; 148 for (Function &F : M) 149 if (!AliveGlobals.count(&F)) { 150 DeadFunctions.push_back(&F); // Keep track of dead globals 151 if (!F.isDeclaration()) 152 F.deleteBody(); 153 } 154 155 // The third pass drops targets of aliases which are dead... 156 std::vector<GlobalAlias*> DeadAliases; 157 for (GlobalAlias &GA : M.aliases()) 158 if (!AliveGlobals.count(&GA)) { 159 DeadAliases.push_back(&GA); 160 GA.setAliasee(nullptr); 161 } 162 163 // The third pass drops targets of ifuncs which are dead... 164 std::vector<GlobalIFunc*> DeadIFuncs; 165 for (GlobalIFunc &GIF : M.ifuncs()) 166 if (!AliveGlobals.count(&GIF)) { 167 DeadIFuncs.push_back(&GIF); 168 GIF.setResolver(nullptr); 169 } 170 171 if (!DeadFunctions.empty()) { 172 // Now that all interferences have been dropped, delete the actual objects 173 // themselves. 174 for (Function *F : DeadFunctions) { 175 RemoveUnusedGlobalValue(*F); 176 M.getFunctionList().erase(F); 177 } 178 NumFunctions += DeadFunctions.size(); 179 Changed = true; 180 } 181 182 if (!DeadGlobalVars.empty()) { 183 for (GlobalVariable *GV : DeadGlobalVars) { 184 RemoveUnusedGlobalValue(*GV); 185 M.getGlobalList().erase(GV); 186 } 187 NumVariables += DeadGlobalVars.size(); 188 Changed = true; 189 } 190 191 // Now delete any dead aliases. 192 if (!DeadAliases.empty()) { 193 for (GlobalAlias *GA : DeadAliases) { 194 RemoveUnusedGlobalValue(*GA); 195 M.getAliasList().erase(GA); 196 } 197 NumAliases += DeadAliases.size(); 198 Changed = true; 199 } 200 201 // Now delete any dead aliases. 202 if (!DeadIFuncs.empty()) { 203 for (GlobalIFunc *GIF : DeadIFuncs) { 204 RemoveUnusedGlobalValue(*GIF); 205 M.getIFuncList().erase(GIF); 206 } 207 NumIFuncs += DeadIFuncs.size(); 208 Changed = true; 209 } 210 211 // Make sure that all memory is released 212 AliveGlobals.clear(); 213 SeenConstants.clear(); 214 ComdatMembers.clear(); 215 216 if (Changed) 217 return PreservedAnalyses::none(); 218 return PreservedAnalyses::all(); 219 } 220 221 /// GlobalIsNeeded - the specific global value as needed, and 222 /// recursively mark anything that it uses as also needed. 223 void GlobalDCEPass::GlobalIsNeeded(GlobalValue *G) { 224 // If the global is already in the set, no need to reprocess it. 225 if (!AliveGlobals.insert(G).second) 226 return; 227 228 if (Comdat *C = G->getComdat()) { 229 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) 230 GlobalIsNeeded(CM.second); 231 } 232 233 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) { 234 // If this is a global variable, we must make sure to add any global values 235 // referenced by the initializer to the alive set. 236 if (GV->hasInitializer()) 237 MarkUsedGlobalsAsNeeded(GV->getInitializer()); 238 } else if (GlobalIndirectSymbol *GIS = dyn_cast<GlobalIndirectSymbol>(G)) { 239 // The target of a global alias or ifunc is needed. 240 MarkUsedGlobalsAsNeeded(GIS->getIndirectSymbol()); 241 } else { 242 // Otherwise this must be a function object. We have to scan the body of 243 // the function looking for constants and global values which are used as 244 // operands. Any operands of these types must be processed to ensure that 245 // any globals used will be marked as needed. 246 Function *F = cast<Function>(G); 247 248 for (Use &U : F->operands()) 249 MarkUsedGlobalsAsNeeded(cast<Constant>(U.get())); 250 251 for (BasicBlock &BB : *F) 252 for (Instruction &I : BB) 253 for (Use &U : I.operands()) 254 if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) 255 GlobalIsNeeded(GV); 256 else if (Constant *C = dyn_cast<Constant>(U)) 257 MarkUsedGlobalsAsNeeded(C); 258 } 259 } 260 261 void GlobalDCEPass::MarkUsedGlobalsAsNeeded(Constant *C) { 262 if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) 263 return GlobalIsNeeded(GV); 264 265 // Loop over all of the operands of the constant, adding any globals they 266 // use to the list of needed globals. 267 for (Use &U : C->operands()) { 268 // If we've already processed this constant there's no need to do it again. 269 Constant *Op = dyn_cast<Constant>(U); 270 if (Op && SeenConstants.insert(Op).second) 271 MarkUsedGlobalsAsNeeded(Op); 272 } 273 } 274 275 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified 276 // GlobalValue, looking for the constant pointer ref that may be pointing to it. 277 // If found, check to see if the constant pointer ref is safe to destroy, and if 278 // so, nuke it. This will reduce the reference count on the global value, which 279 // might make it deader. 280 // 281 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) { 282 if (GV.use_empty()) 283 return false; 284 GV.removeDeadConstantUsers(); 285 return GV.use_empty(); 286 } 287