blob: c91e8b454927f539de1512e18f0d128e9a31ff72 [file] [log] [blame]
Chris Lattner62b7fd12002-04-07 20:49:59 +00001//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd422e62001-11-26 18:42:17 +00009//
Chris Lattnerec6d7a62003-09-16 19:27:31 +000010// 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.
Chris Lattnerbd422e62001-11-26 18:42:17 +000015//
16//===----------------------------------------------------------------------===//
17
Davide Italiano66228c42016-05-03 19:39:15 +000018#include "llvm/Transforms/IPO/GlobalDCE.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000022#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000024#include "llvm/Pass.h"
25#include "llvm/Transforms/IPO.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000026#include "llvm/Transforms/Utils/CtorUtils.h"
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +000027#include "llvm/Transforms/Utils/GlobalStatus.h"
Mehdi Amini888dee42017-01-27 19:48:57 +000028
Chris Lattnerf52e03c2003-11-21 21:54:22 +000029using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000030
Chandler Carruth964daaa2014-04-22 02:55:47 +000031#define DEBUG_TYPE "globaldce"
32
Duncan Sands821d13c2009-01-05 20:39:50 +000033STATISTIC(NumAliases , "Number of global aliases removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000034STATISTIC(NumFunctions, "Number of functions removed");
David Majnemer95549492016-05-04 00:20:48 +000035STATISTIC(NumIFuncs, "Number of indirect functions removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000036STATISTIC(NumVariables, "Number of global variables removed");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000037
Chris Lattner1631bcb2006-12-19 22:09:18 +000038namespace {
Davide Italiano66228c42016-05-03 19:39:15 +000039 class GlobalDCELegacyPass : public ModulePass {
40 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000041 static char ID; // Pass identification, replacement for typeid
Davide Italiano66228c42016-05-03 19:39:15 +000042 GlobalDCELegacyPass() : ModulePass(ID) {
43 initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000044 }
Duncan Sandsf5dbbae2009-01-05 20:37:33 +000045
Chris Lattner04805fa2002-02-26 21:46:54 +000046 // run - Do the GlobalDCE pass on the specified module, optionally updating
47 // the specified callgraph to reflect the changes.
48 //
Davide Italiano66228c42016-05-03 19:39:15 +000049 bool runOnModule(Module &M) override {
50 if (skipModule(M))
51 return false;
52
Chandler Carruthe8c66b22017-01-23 08:33:24 +000053 // 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;
Chandler Carruth164a2aa62016-06-17 00:11:01 +000057 ModuleAnalysisManager DummyMAM;
Chandler Carruthe8c66b22017-01-23 08:33:24 +000058 DummyMAM.registerPass(
59 [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); });
60
Chandler Carruth164a2aa62016-06-17 00:11:01 +000061 auto PA = Impl.run(M, DummyMAM);
Davide Italiano66228c42016-05-03 19:39:15 +000062 return !PA.areAllPreserved();
63 }
Chris Lattner8f3acc62002-08-18 01:28:30 +000064
65 private:
Davide Italiano66228c42016-05-03 19:39:15 +000066 GlobalDCEPass Impl;
Chris Lattner04805fa2002-02-26 21:46:54 +000067 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000068}
Nico Weber4b2acde2014-05-02 18:35:25 +000069
Davide Italiano66228c42016-05-03 19:39:15 +000070char GlobalDCELegacyPass::ID = 0;
71INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
72 "Dead Global Elimination", false, false)
73
74// Public interface to the GlobalDCEPass.
75ModulePass *llvm::createGlobalDCEPass() {
76 return new GlobalDCELegacyPass();
77}
78
Nico Weber4b2acde2014-05-02 18:35:25 +000079/// Returns true if F contains only a single "ret" instruction.
Richard Smithc167d652014-05-06 01:44:26 +000080static bool isEmptyFunction(Function *F) {
Nico Weber4b2acde2014-05-02 18:35:25 +000081 BasicBlock &Entry = F->getEntryBlock();
82 if (Entry.size() != 1 || !isa<ReturnInst>(Entry.front()))
83 return false;
84 ReturnInst &RI = cast<ReturnInst>(Entry.front());
Craig Topper66f09ad2014-06-08 22:29:17 +000085 return RI.getReturnValue() == nullptr;
Nico Weber4b2acde2014-05-02 18:35:25 +000086}
Chris Lattnerd5d56782002-01-31 00:45:11 +000087
Mehdi Amini888dee42017-01-27 19:48:57 +000088/// Compute the set of GlobalValue that depends from V.
89/// The recursion stops as soon as a GlobalValue is met.
90void GlobalDCEPass::ComputeDependencies(Value *V,
91 SmallPtrSetImpl<GlobalValue *> &Deps) {
92 if (auto *I = dyn_cast<Instruction>(V)) {
93 Function *Parent = I->getParent()->getParent();
94 Deps.insert(Parent);
95 } else if (auto *GV = dyn_cast<GlobalValue>(V)) {
96 Deps.insert(GV);
97 } else if (auto *CE = dyn_cast<Constant>(V)) {
98 // Avoid walking the whole tree of a big ConstantExprs multiple times.
99 auto Where = ConstantDependenciesCache.find(CE);
100 if (Where != ConstantDependenciesCache.end()) {
101 auto const &K = Where->second;
102 Deps.insert(K.begin(), K.end());
103 } else {
104 SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
105 for (User *CEUser : CE->users())
106 ComputeDependencies(CEUser, LocalDeps);
107 Deps.insert(LocalDeps.begin(), LocalDeps.end());
108 }
109 }
110}
111
112void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
113 SmallPtrSet<GlobalValue *, 8> Deps;
114 for (User *User : GV.users())
115 ComputeDependencies(User, Deps);
116 Deps.erase(&GV); // Remove self-reference.
117 for (GlobalValue *GVU : Deps) {
118 GVDependencies.insert(std::make_pair(GVU, &GV));
119 }
120}
121
122/// Mark Global value as Live
123void GlobalDCEPass::MarkLive(GlobalValue &GV,
124 SmallVectorImpl<GlobalValue *> *Updates) {
125 auto const Ret = AliveGlobals.insert(&GV);
126 if (!Ret.second)
127 return;
128
129 if (Updates)
130 Updates->push_back(&GV);
131 if (Comdat *C = GV.getComdat()) {
132 for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
133 MarkLive(*CM.second, Updates); // Recursion depth is only two because only
134 // globals in the same comdat are visited.
135 }
136}
137
Chandler Carruthe8c66b22017-01-23 08:33:24 +0000138PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {
Chris Lattner8f3acc62002-08-18 01:28:30 +0000139 bool Changed = false;
Nico Weber4b2acde2014-05-02 18:35:25 +0000140
Mehdi Amini888dee42017-01-27 19:48:57 +0000141 // The algorithm first computes the set L of global variables that are
142 // trivially live. Then it walks the initialization of these variables to
143 // compute the globals used to initialize them, which effectively builds a
144 // directed graph where nodes are global variables, and an edge from A to B
145 // means B is used to initialize A. Finally, it propagates the liveness
146 // information through the graph starting from the nodes in L. Nodes note
147 // marked as alive are discarded.
148
Nico Weber4b2acde2014-05-02 18:35:25 +0000149 // Remove empty functions from the global ctors list.
Richard Smithc167d652014-05-06 01:44:26 +0000150 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
Nico Weber4b2acde2014-05-02 18:35:25 +0000151
Peter Collingbourne0dbc7082015-03-19 18:23:29 +0000152 // Collect the set of members for each comdat.
153 for (Function &F : M)
154 if (Comdat *C = F.getComdat())
155 ComdatMembers.insert(std::make_pair(C, &F));
156 for (GlobalVariable &GV : M.globals())
157 if (Comdat *C = GV.getComdat())
158 ComdatMembers.insert(std::make_pair(C, &GV));
159 for (GlobalAlias &GA : M.aliases())
160 if (Comdat *C = GA.getComdat())
161 ComdatMembers.insert(std::make_pair(C, &GA));
162
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000163 // Loop over the module, adding globals which are obviously necessary.
Peter Collingbourne6d88fde2016-06-22 20:29:42 +0000164 for (GlobalObject &GO : M.global_objects()) {
165 Changed |= RemoveUnusedGlobalValue(GO);
166 // Functions with external linkage are needed if they have a body.
Chris Lattnerc8dfbbb2003-09-20 19:00:50 +0000167 // Externally visible & appending globals are needed, if they have an
168 // initializer.
Peter Collingbourne6d88fde2016-06-22 20:29:42 +0000169 if (!GO.isDeclaration() && !GO.hasAvailableExternallyLinkage())
170 if (!GO.isDiscardableIfUnused())
Mehdi Amini888dee42017-01-27 19:48:57 +0000171 MarkLive(GO);
172
173 UpdateGVDependencies(GO);
Chris Lattner8f3acc62002-08-18 01:28:30 +0000174 }
175
Mehdi Amini888dee42017-01-27 19:48:57 +0000176 // Compute direct dependencies of aliases.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000177 for (GlobalAlias &GA : M.aliases()) {
178 Changed |= RemoveUnusedGlobalValue(GA);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000179 // Externally visible aliases are needed.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000180 if (!GA.isDiscardableIfUnused())
Mehdi Amini888dee42017-01-27 19:48:57 +0000181 MarkLive(GA);
182
183 UpdateGVDependencies(GA);
David Majnemerdad0a642014-06-27 18:19:56 +0000184 }
185
Mehdi Amini888dee42017-01-27 19:48:57 +0000186 // Compute direct dependencies of ifuncs.
David Majnemer95549492016-05-04 00:20:48 +0000187 for (GlobalIFunc &GIF : M.ifuncs()) {
188 Changed |= RemoveUnusedGlobalValue(GIF);
189 // Externally visible ifuncs are needed.
190 if (!GIF.isDiscardableIfUnused())
Mehdi Amini888dee42017-01-27 19:48:57 +0000191 MarkLive(GIF);
192
193 UpdateGVDependencies(GIF);
194 }
195
196 // Propagate liveness from collected Global Values through the computed
197 // dependencies.
198 SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
199 AliveGlobals.end()};
200 while (!NewLiveGVs.empty()) {
201 GlobalValue *LGV = NewLiveGVs.pop_back_val();
202 for (auto &&GVD : make_range(GVDependencies.equal_range(LGV)))
203 MarkLive(*GVD.second, &NewLiveGVs);
David Majnemer95549492016-05-04 00:20:48 +0000204 }
205
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000206 // Now that all globals which are needed are in the AliveGlobals set, we loop
207 // through the program, deleting those which are not alive.
Chris Lattner8f3acc62002-08-18 01:28:30 +0000208 //
Chris Lattner8f3acc62002-08-18 01:28:30 +0000209
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000210 // The first pass is to drop initializers of global variables which are dead.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000211 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
212 for (GlobalVariable &GV : M.globals())
213 if (!AliveGlobals.count(&GV)) {
214 DeadGlobalVars.push_back(&GV); // Keep track of dead globals
215 if (GV.hasInitializer()) {
216 Constant *Init = GV.getInitializer();
217 GV.setInitializer(nullptr);
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +0000218 if (isSafeToDestroyConstant(Init))
219 Init->destroyConstant();
220 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000221 }
222
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000223 // The second pass drops the bodies of functions which are dead...
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000224 std::vector<Function *> DeadFunctions;
225 for (Function &F : M)
226 if (!AliveGlobals.count(&F)) {
227 DeadFunctions.push_back(&F); // Keep track of dead globals
Chandler Carruth6acdca72017-01-24 12:55:57 +0000228 if (!F.isDeclaration())
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000229 F.deleteBody();
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000230 }
231
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000232 // The third pass drops targets of aliases which are dead...
233 std::vector<GlobalAlias*> DeadAliases;
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000234 for (GlobalAlias &GA : M.aliases())
235 if (!AliveGlobals.count(&GA)) {
236 DeadAliases.push_back(&GA);
237 GA.setAliasee(nullptr);
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000238 }
239
Mehdi Amini888dee42017-01-27 19:48:57 +0000240 // The fourth pass drops targets of ifuncs which are dead...
David Majnemer95549492016-05-04 00:20:48 +0000241 std::vector<GlobalIFunc*> DeadIFuncs;
242 for (GlobalIFunc &GIF : M.ifuncs())
243 if (!AliveGlobals.count(&GIF)) {
244 DeadIFuncs.push_back(&GIF);
245 GIF.setResolver(nullptr);
246 }
247
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000248 // Now that all interferences have been dropped, delete the actual objects
249 // themselves.
250 auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
251 RemoveUnusedGlobalValue(*GV);
252 GV->eraseFromParent();
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000253 Changed = true;
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000254 };
Chris Lattner8f3acc62002-08-18 01:28:30 +0000255
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000256 NumFunctions += DeadFunctions.size();
257 for (Function *F : DeadFunctions)
258 EraseUnusedGlobalValue(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000259
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000260 NumVariables += DeadGlobalVars.size();
261 for (GlobalVariable *GV : DeadGlobalVars)
262 EraseUnusedGlobalValue(GV);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000263
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000264 NumAliases += DeadAliases.size();
265 for (GlobalAlias *GA : DeadAliases)
266 EraseUnusedGlobalValue(GA);
267
Peter Collingbourne4f3b2df2016-10-25 02:57:27 +0000268 NumIFuncs += DeadIFuncs.size();
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000269 for (GlobalIFunc *GIF : DeadIFuncs)
270 EraseUnusedGlobalValue(GIF);
David Majnemer95549492016-05-04 00:20:48 +0000271
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000272 // Make sure that all memory is released
273 AliveGlobals.clear();
Mehdi Amini888dee42017-01-27 19:48:57 +0000274 ConstantDependenciesCache.clear();
275 GVDependencies.clear();
Peter Collingbourne0dbc7082015-03-19 18:23:29 +0000276 ComdatMembers.clear();
Devang Patelc5aa8c62009-08-11 06:31:57 +0000277
Davide Italiano66228c42016-05-03 19:39:15 +0000278 if (Changed)
279 return PreservedAnalyses::none();
280 return PreservedAnalyses::all();
Chris Lattner8f3acc62002-08-18 01:28:30 +0000281}
282
Reid Spencer5f681592004-07-18 00:25:04 +0000283// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
Chris Lattner8f3acc62002-08-18 01:28:30 +0000284// GlobalValue, looking for the constant pointer ref that may be pointing to it.
285// If found, check to see if the constant pointer ref is safe to destroy, and if
286// so, nuke it. This will reduce the reference count on the global value, which
287// might make it deader.
288//
Davide Italiano66228c42016-05-03 19:39:15 +0000289bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000290 if (GV.use_empty())
291 return false;
Chris Lattner9238d782004-07-18 07:22:58 +0000292 GV.removeDeadConstantUsers();
293 return GV.use_empty();
294}