LLVM  8.0.1
GlobalDCE.cpp
Go to the documentation of this file.
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 
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"
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) {
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 
71 INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
72  "Dead Global Elimination", false, false)
73 
74 // Public interface to the GlobalDCEPass.
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,
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) {
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,
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 
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.
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;
297  return GV.use_empty();
298 }
uint64_t CallInst * C
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents lattice values for constants.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
void initializeGlobalDCELegacyPassPass(PassRegistry &)
STATISTIC(NumFunctions, "Total number of functions")
F(f)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:344
INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce", "Dead Global Elimination", false, false) ModulePass *llvm
Definition: GlobalDCE.cpp:71
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:822
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
Definition: PassManager.h:1121
Pass to remove unused function declarations.
Definition: GlobalDCE.h:30
ModulePass * createGlobalDCEPass()
createGlobalDCEPass - This transform is designed to eliminate unreachable internal globals (functions...
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:537
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
const BasicBlock & getEntryBlock() const
Definition: Function.h:640
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
bool isSafeToDestroyConstant(const Constant *C)
It is safe to destroy a constant iff it is only used by constants itself.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:378
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
static bool isEmptyFunction(Function *F)
Returns true if F is effectively empty.
Definition: GlobalDCE.cpp:80
const Comdat * getComdat() const
Definition: Globals.cpp:171
iterator_range< user_iterator > users()
Definition: Value.h:400
void eraseFromParent()
This method unlinks &#39;this&#39; from the containing module and deletes it.
Definition: Globals.cpp:85
iterator begin() const
Definition: SmallPtrSet.h:397
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
void destroyConstant()
Called if some element of this constant is no longer valid.
Definition: Constants.cpp:362
iterator end() const
Definition: SmallPtrSet.h:402
LLVM Value Representation.
Definition: Value.h:73
A container for analyses that lazily runs them and caches their results.
bool optimizeGlobalCtorsList(Module &M, function_ref< bool(Function *)> ShouldRemove)
Call "ShouldRemove" for every entry in M&#39;s global_ctor list and remove the entries for which it retur...
Definition: CtorUtils.cpp:117
bool use_empty() const
Definition: Value.h:323
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
Definition: GlobalDCE.cpp:142