GlobalDCE: Delete available_externally initializers if it allows removing the value...
[oota-llvm.git] / lib / Transforms / IPO / GlobalDCE.cpp
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.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/Transforms/Utils/CtorUtils.h"
25 #include "llvm/Pass.h"
26 using namespace llvm;
27
28 #define DEBUG_TYPE "globaldce"
29
30 STATISTIC(NumAliases  , "Number of global aliases removed");
31 STATISTIC(NumFunctions, "Number of functions removed");
32 STATISTIC(NumVariables, "Number of global variables removed");
33
34 namespace {
35   struct GlobalDCE : public ModulePass {
36     static char ID; // Pass identification, replacement for typeid
37     GlobalDCE() : ModulePass(ID) {
38       initializeGlobalDCEPass(*PassRegistry::getPassRegistry());
39     }
40
41     // run - Do the GlobalDCE pass on the specified module, optionally updating
42     // the specified callgraph to reflect the changes.
43     //
44     bool runOnModule(Module &M) override;
45
46   private:
47     SmallPtrSet<Constant *, 32> AliveGlobals;
48     SmallPtrSet<Constant *, 8> SeenConstants;
49     SmallPtrSet<GlobalVariable *, 8> DiscardableGlobalInitializers;
50
51     /// GlobalIsNeeded - mark the specific global value as needed, and
52     /// recursively mark anything that it uses as also needed.
53     void GlobalIsNeeded(GlobalValue *GV);
54     void MarkUsedGlobalsAsNeeded(Constant *C);
55
56     /// \brief Checks if C is alive or is a ConstantExpr that refers to an alive
57     /// value.
58     bool ContainsUsedGlobal(Constant *C);
59
60     bool RemoveUnusedGlobalValue(GlobalValue &GV);
61   };
62 }
63
64 /// Returns true if F contains only a single "ret" instruction.
65 static bool isEmptyFunction(Function *F) {
66   BasicBlock &Entry = F->getEntryBlock();
67   if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
68     return false;
69   ReturnInst &RI = cast<ReturnInst>(Entry.front());
70   return RI.getReturnValue() == nullptr;
71 }
72
73 char GlobalDCE::ID = 0;
74 INITIALIZE_PASS(GlobalDCE, "globaldce",
75                 "Dead Global Elimination", false, false)
76
77 ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }
78
79 bool GlobalDCE::runOnModule(Module &M) {
80   bool Changed = false;
81
82   // Remove empty functions from the global ctors list.
83   Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
84
85   typedef std::multimap<const Comdat *, GlobalValue *> ComdatGVPairsTy;
86   ComdatGVPairsTy ComdatGVPairs;
87
88   // Loop over the module, adding globals which are obviously necessary.
89   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
90     Changed |= RemoveUnusedGlobalValue(*I);
91     // Functions with external linkage are needed if they have a body
92     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
93       if (!I->isDiscardableIfUnused())
94         GlobalIsNeeded(I);
95       else if (const Comdat *C = I->getComdat())
96         ComdatGVPairs.insert(std::make_pair(C, I));
97     }
98   }
99
100   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
101        I != E; ++I) {
102     Changed |= RemoveUnusedGlobalValue(*I);
103     // Externally visible & appending globals are needed, if they have an
104     // initializer.
105     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
106       if (!I->isDiscardableIfUnused())
107         GlobalIsNeeded(I);
108       else if (const Comdat *C = I->getComdat())
109         ComdatGVPairs.insert(std::make_pair(C, I));
110     }
111   }
112
113   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
114        I != E; ++I) {
115     Changed |= RemoveUnusedGlobalValue(*I);
116     // Externally visible aliases are needed.
117     if (!I->isDiscardableIfUnused()) {
118       GlobalIsNeeded(I);
119     } else if (const Comdat *C = I->getComdat()) {
120       ComdatGVPairs.insert(std::make_pair(C, I));
121     }
122   }
123
124   for (ComdatGVPairsTy::iterator I = ComdatGVPairs.begin(),
125                                  E = ComdatGVPairs.end();
126        I != E;) {
127     ComdatGVPairsTy::iterator UB = ComdatGVPairs.upper_bound(I->first);
128     bool CanDiscard = std::all_of(I, UB, [](ComdatGVPairsTy::value_type Pair) {
129       return Pair.second->isDiscardableIfUnused();
130     });
131     if (!CanDiscard) {
132       std::for_each(I, UB, [this](ComdatGVPairsTy::value_type Pair) {
133         GlobalIsNeeded(Pair.second);
134       });
135     }
136     I = UB;
137   }
138
139   // Now that all globals which are needed are in the AliveGlobals set, we loop
140   // through the program, deleting those which are not alive.
141   //
142
143   // The first pass is to drop initializers of global variables which are dead.
144   std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
145   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
146        I != E; ++I)
147     if (!AliveGlobals.count(I)) {
148       DeadGlobalVars.push_back(I);         // Keep track of dead globals
149       I->setInitializer(nullptr);
150     }
151
152   // The second pass drops the bodies of functions which are dead...
153   std::vector<Function*> DeadFunctions;
154   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
155     if (!AliveGlobals.count(I)) {
156       DeadFunctions.push_back(I);         // Keep track of dead globals
157       if (!I->isDeclaration())
158         I->deleteBody();
159     }
160
161   // The third pass drops targets of aliases which are dead...
162   std::vector<GlobalAlias*> DeadAliases;
163   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
164        ++I)
165     if (!AliveGlobals.count(I)) {
166       DeadAliases.push_back(I);
167       I->setAliasee(nullptr);
168     }
169
170   // Look for available externally constants that we can turn into normal
171   // externals by deleting their initalizers. This allows us to remove other
172   // globals that are referenced by the initializer.
173   if (!DiscardableGlobalInitializers.empty()) {
174     for (GlobalVariable *GV : DiscardableGlobalInitializers) {
175       if (!ContainsUsedGlobal(GV->getInitializer())) {
176         GV->setInitializer(nullptr);
177         GV->setLinkage(GlobalValue::ExternalLinkage);
178         Changed = true;
179       }
180     }
181   }
182
183   if (!DeadFunctions.empty()) {
184     // Now that all interferences have been dropped, delete the actual objects
185     // themselves.
186     for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
187       RemoveUnusedGlobalValue(*DeadFunctions[i]);
188       M.getFunctionList().erase(DeadFunctions[i]);
189     }
190     NumFunctions += DeadFunctions.size();
191     Changed = true;
192   }
193
194   if (!DeadGlobalVars.empty()) {
195     for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
196       RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
197       M.getGlobalList().erase(DeadGlobalVars[i]);
198     }
199     NumVariables += DeadGlobalVars.size();
200     Changed = true;
201   }
202
203   // Now delete any dead aliases.
204   if (!DeadAliases.empty()) {
205     for (unsigned i = 0, e = DeadAliases.size(); i != e; ++i) {
206       RemoveUnusedGlobalValue(*DeadAliases[i]);
207       M.getAliasList().erase(DeadAliases[i]);
208     }
209     NumAliases += DeadAliases.size();
210     Changed = true;
211   }
212
213   // Make sure that all memory is released
214   AliveGlobals.clear();
215   SeenConstants.clear();
216
217   return Changed;
218 }
219
220 /// GlobalIsNeeded - the specific global value as needed, and
221 /// recursively mark anything that it uses as also needed.
222 void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
223   // If the global is already in the set, no need to reprocess it.
224   if (!AliveGlobals.insert(G))
225     return;
226   
227   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
228     // If this is a global variable, we must make sure to add any global values
229     // referenced by the initializer to the alive set.
230     if (GV->hasInitializer()) {
231       if (GV->hasAvailableExternallyLinkage())
232         DiscardableGlobalInitializers.insert(GV);
233       else
234         MarkUsedGlobalsAsNeeded(GV->getInitializer());
235     }
236   } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(G)) {
237     // The target of a global alias is needed.
238     MarkUsedGlobalsAsNeeded(GA->getAliasee());
239   } else {
240     // Otherwise this must be a function object.  We have to scan the body of
241     // the function looking for constants and global values which are used as
242     // operands.  Any operands of these types must be processed to ensure that
243     // any globals used will be marked as needed.
244     Function *F = cast<Function>(G);
245
246     if (F->hasPrefixData())
247       MarkUsedGlobalsAsNeeded(F->getPrefixData());
248
249     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
250       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
251         for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
252           if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
253             GlobalIsNeeded(GV);
254           else if (Constant *C = dyn_cast<Constant>(*U))
255             MarkUsedGlobalsAsNeeded(C);
256   }
257 }
258
259 void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
260   if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
261     return GlobalIsNeeded(GV);
262
263   // Loop over all of the operands of the constant, adding any globals they
264   // use to the list of needed globals.
265   for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
266     // If we've already processed this constant there's no need to do it again.
267     Constant *Op = dyn_cast<Constant>(*I);
268     if (Op && SeenConstants.insert(Op))
269       MarkUsedGlobalsAsNeeded(Op);
270   }
271 }
272
273 bool GlobalDCE::ContainsUsedGlobal(Constant *C) {
274   // C contains a used global If C is alive or we visited it while marking
275   // values alive.
276   if (AliveGlobals.count(C) || SeenConstants.count(C))
277     return true;
278
279   // Now check all operands of a ConstantExpr.
280   for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I) {
281     Constant *Op = dyn_cast<Constant>(*I);
282     if (Op && ContainsUsedGlobal(Op))
283       return true;
284   }
285   return false;
286 }
287
288 // RemoveUnusedGlobalValue - Loop over all of the uses of the specified
289 // GlobalValue, looking for the constant pointer ref that may be pointing to it.
290 // If found, check to see if the constant pointer ref is safe to destroy, and if
291 // so, nuke it.  This will reduce the reference count on the global value, which
292 // might make it deader.
293 //
294 bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
295   if (GV.use_empty()) return false;
296   GV.removeDeadConstantUsers();
297   return GV.use_empty();
298 }