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/Instructions.h" 22 #include "llvm/IR/IntrinsicInst.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 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 // We need a minimally functional dummy module analysis manager. It needs 54 // to at least know about the possibility of proxying a function analysis 55 // manager. 56 FunctionAnalysisManager DummyFAM; 57 ModuleAnalysisManager DummyMAM; 58 DummyMAM.registerPass( 59 [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); }); 60 61 auto PA = Impl.run(M, DummyMAM); 62 return !PA.areAllPreserved(); 63 } 64 65 private: 66 GlobalDCEPass Impl; 67 }; 68 } 69 70 char GlobalDCELegacyPass::ID = 0; 71 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", 72 "Dead Global Elimination", false, false) 73 74 // Public interface to the GlobalDCEPass. 75 ModulePass *llvm::createGlobalDCEPass() { 76 return new GlobalDCELegacyPass(); 77 } 78 79 /// Returns true if F is effectively empty. 80 static bool isEmptyFunction(Function *F) { 81 BasicBlock &Entry = F->getEntryBlock(); 82 for (auto &I : Entry) { 83 if (isa<DbgInfoIntrinsic>(I)) 84 continue; 85 if (auto *RI = dyn_cast<ReturnInst>(&I)) 86 return !RI->getReturnValue(); 87 break; 88 } 89 return false; 90 } 91 92 /// Compute the set of GlobalValue that depends from V. 93 /// The recursion stops as soon as a GlobalValue is met. 94 void GlobalDCEPass::ComputeDependencies(Value *V, 95 SmallPtrSetImpl<GlobalValue *> &Deps) { 96 if (auto *I = dyn_cast<Instruction>(V)) { 97 Function *Parent = I->getParent()->getParent(); 98 Deps.insert(Parent); 99 } else if (auto *GV = dyn_cast<GlobalValue>(V)) { 100 Deps.insert(GV); 101 } else if (auto *CE = dyn_cast<Constant>(V)) { 102 // Avoid walking the whole tree of a big ConstantExprs multiple times. 103 auto Where = ConstantDependenciesCache.find(CE); 104 if (Where != ConstantDependenciesCache.end()) { 105 auto const &K = Where->second; 106 Deps.insert(K.begin(), K.end()); 107 } else { 108 SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE]; 109 for (User *CEUser : CE->users()) 110 ComputeDependencies(CEUser, LocalDeps); 111 Deps.insert(LocalDeps.begin(), LocalDeps.end()); 112 } 113 } 114 } 115 116 void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) { 117 SmallPtrSet<GlobalValue *, 8> Deps; 118 for (User *User : GV.users()) 119 ComputeDependencies(User, Deps); 120 Deps.erase(&GV); // Remove self-reference. 121 for (GlobalValue *GVU : Deps) { 122 GVDependencies[GVU].insert(&GV); 123 } 124 } 125 126 /// Mark Global value as Live 127 void GlobalDCEPass::MarkLive(GlobalValue &GV, 128 SmallVectorImpl<GlobalValue *> *Updates) { 129 auto const Ret = AliveGlobals.insert(&GV); 130 if (!Ret.second) 131 return; 132 133 if (Updates) 134 Updates->push_back(&GV); 135 if (Comdat *C = GV.getComdat()) { 136 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) 137 MarkLive(*CM.second, Updates); // Recursion depth is only two because only 138 // globals in the same comdat are visited. 139 } 140 } 141 142 PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) { 143 bool Changed = false; 144 145 // The algorithm first computes the set L of global variables that are 146 // trivially live. Then it walks the initialization of these variables to 147 // compute the globals used to initialize them, which effectively builds a 148 // directed graph where nodes are global variables, and an edge from A to B 149 // means B is used to initialize A. Finally, it propagates the liveness 150 // information through the graph starting from the nodes in L. Nodes note 151 // marked as alive are discarded. 152 153 // Remove empty functions from the global ctors list. 154 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction); 155 156 // Collect the set of members for each comdat. 157 for (Function &F : M) 158 if (Comdat *C = F.getComdat()) 159 ComdatMembers.insert(std::make_pair(C, &F)); 160 for (GlobalVariable &GV : M.globals()) 161 if (Comdat *C = GV.getComdat()) 162 ComdatMembers.insert(std::make_pair(C, &GV)); 163 for (GlobalAlias &GA : M.aliases()) 164 if (Comdat *C = GA.getComdat()) 165 ComdatMembers.insert(std::make_pair(C, &GA)); 166 167 // Loop over the module, adding globals which are obviously necessary. 168 for (GlobalObject &GO : M.global_objects()) { 169 Changed |= RemoveUnusedGlobalValue(GO); 170 // Functions with external linkage are needed if they have a body. 171 // Externally visible & appending globals are needed, if they have an 172 // initializer. 173 if (!GO.isDeclaration()) 174 if (!GO.isDiscardableIfUnused()) 175 MarkLive(GO); 176 177 UpdateGVDependencies(GO); 178 } 179 180 // Compute direct dependencies of aliases. 181 for (GlobalAlias &GA : M.aliases()) { 182 Changed |= RemoveUnusedGlobalValue(GA); 183 // Externally visible aliases are needed. 184 if (!GA.isDiscardableIfUnused()) 185 MarkLive(GA); 186 187 UpdateGVDependencies(GA); 188 } 189 190 // Compute direct dependencies of ifuncs. 191 for (GlobalIFunc &GIF : M.ifuncs()) { 192 Changed |= RemoveUnusedGlobalValue(GIF); 193 // Externally visible ifuncs are needed. 194 if (!GIF.isDiscardableIfUnused()) 195 MarkLive(GIF); 196 197 UpdateGVDependencies(GIF); 198 } 199 200 // Propagate liveness from collected Global Values through the computed 201 // dependencies. 202 SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(), 203 AliveGlobals.end()}; 204 while (!NewLiveGVs.empty()) { 205 GlobalValue *LGV = NewLiveGVs.pop_back_val(); 206 for (auto *GVD : GVDependencies[LGV]) 207 MarkLive(*GVD, &NewLiveGVs); 208 } 209 210 // Now that all globals which are needed are in the AliveGlobals set, we loop 211 // through the program, deleting those which are not alive. 212 // 213 214 // The first pass is to drop initializers of global variables which are dead. 215 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals 216 for (GlobalVariable &GV : M.globals()) 217 if (!AliveGlobals.count(&GV)) { 218 DeadGlobalVars.push_back(&GV); // Keep track of dead globals 219 if (GV.hasInitializer()) { 220 Constant *Init = GV.getInitializer(); 221 GV.setInitializer(nullptr); 222 if (isSafeToDestroyConstant(Init)) 223 Init->destroyConstant(); 224 } 225 } 226 227 // The second pass drops the bodies of functions which are dead... 228 std::vector<Function *> DeadFunctions; 229 for (Function &F : M) 230 if (!AliveGlobals.count(&F)) { 231 DeadFunctions.push_back(&F); // Keep track of dead globals 232 if (!F.isDeclaration()) 233 F.deleteBody(); 234 } 235 236 // The third pass drops targets of aliases which are dead... 237 std::vector<GlobalAlias*> DeadAliases; 238 for (GlobalAlias &GA : M.aliases()) 239 if (!AliveGlobals.count(&GA)) { 240 DeadAliases.push_back(&GA); 241 GA.setAliasee(nullptr); 242 } 243 244 // The fourth pass drops targets of ifuncs which are dead... 245 std::vector<GlobalIFunc*> DeadIFuncs; 246 for (GlobalIFunc &GIF : M.ifuncs()) 247 if (!AliveGlobals.count(&GIF)) { 248 DeadIFuncs.push_back(&GIF); 249 GIF.setResolver(nullptr); 250 } 251 252 // Now that all interferences have been dropped, delete the actual objects 253 // themselves. 254 auto EraseUnusedGlobalValue = [&](GlobalValue *GV) { 255 RemoveUnusedGlobalValue(*GV); 256 GV->eraseFromParent(); 257 Changed = true; 258 }; 259 260 NumFunctions += DeadFunctions.size(); 261 for (Function *F : DeadFunctions) 262 EraseUnusedGlobalValue(F); 263 264 NumVariables += DeadGlobalVars.size(); 265 for (GlobalVariable *GV : DeadGlobalVars) 266 EraseUnusedGlobalValue(GV); 267 268 NumAliases += DeadAliases.size(); 269 for (GlobalAlias *GA : DeadAliases) 270 EraseUnusedGlobalValue(GA); 271 272 NumIFuncs += DeadIFuncs.size(); 273 for (GlobalIFunc *GIF : DeadIFuncs) 274 EraseUnusedGlobalValue(GIF); 275 276 // Make sure that all memory is released 277 AliveGlobals.clear(); 278 ConstantDependenciesCache.clear(); 279 GVDependencies.clear(); 280 ComdatMembers.clear(); 281 282 if (Changed) 283 return PreservedAnalyses::none(); 284 return PreservedAnalyses::all(); 285 } 286 287 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified 288 // GlobalValue, looking for the constant pointer ref that may be pointing to it. 289 // If found, check to see if the constant pointer ref is safe to destroy, and if 290 // so, nuke it. This will reduce the reference count on the global value, which 291 // might make it deader. 292 // 293 bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) { 294 if (GV.use_empty()) 295 return false; 296 GV.removeDeadConstantUsers(); 297 return GV.use_empty(); 298 } 299