blob: 86b7f3e49ee6f83cbaa7beec1e87290bc122693c [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattnerbd422e62001-11-26 18:42:17 +00008//
Chris Lattnerec6d7a62003-09-16 19:27:31 +00009// This transform is designed to eliminate unreachable internal globals from the
10// program. It uses an aggressive algorithm, searching out globals that are
11// known to be alive. After it finds all of the globals which are needed, it
12// deletes whatever is left over. This allows it to delete recursive chunks of
13// the program which are unreachable.
Chris Lattnerbd422e62001-11-26 18:42:17 +000014//
15//===----------------------------------------------------------------------===//
16
Davide Italiano66228c42016-05-03 19:39:15 +000017#include "llvm/Transforms/IPO/GlobalDCE.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000020#include "llvm/IR/Instructions.h"
Adrian Prantl83d87522018-11-16 17:47:21 +000021#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Module.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000023#include "llvm/Pass.h"
24#include "llvm/Transforms/IPO.h"
Nico Weber4b2acde2014-05-02 18:35:25 +000025#include "llvm/Transforms/Utils/CtorUtils.h"
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +000026#include "llvm/Transforms/Utils/GlobalStatus.h"
Mehdi Amini888dee42017-01-27 19:48:57 +000027
Chris Lattnerf52e03c2003-11-21 21:54:22 +000028using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000029
Chandler Carruth964daaa2014-04-22 02:55:47 +000030#define DEBUG_TYPE "globaldce"
31
Duncan Sands821d13c2009-01-05 20:39:50 +000032STATISTIC(NumAliases , "Number of global aliases removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000033STATISTIC(NumFunctions, "Number of functions removed");
David Majnemer95549492016-05-04 00:20:48 +000034STATISTIC(NumIFuncs, "Number of indirect functions removed");
Chris Lattner1631bcb2006-12-19 22:09:18 +000035STATISTIC(NumVariables, "Number of global variables removed");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000036
Chris Lattner1631bcb2006-12-19 22:09:18 +000037namespace {
Davide Italiano66228c42016-05-03 19:39:15 +000038 class GlobalDCELegacyPass : public ModulePass {
39 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000040 static char ID; // Pass identification, replacement for typeid
Davide Italiano66228c42016-05-03 19:39:15 +000041 GlobalDCELegacyPass() : ModulePass(ID) {
42 initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Anderson6c18d1a2010-10-19 17:21:58 +000043 }
Duncan Sandsf5dbbae2009-01-05 20:37:33 +000044
Chris Lattner04805fa2002-02-26 21:46:54 +000045 // run - Do the GlobalDCE pass on the specified module, optionally updating
46 // the specified callgraph to reflect the changes.
47 //
Davide Italiano66228c42016-05-03 19:39:15 +000048 bool runOnModule(Module &M) override {
49 if (skipModule(M))
50 return false;
51
Chandler Carruthe8c66b22017-01-23 08:33:24 +000052 // We need a minimally functional dummy module analysis manager. It needs
53 // to at least know about the possibility of proxying a function analysis
54 // manager.
55 FunctionAnalysisManager DummyFAM;
Chandler Carruth164a2aa62016-06-17 00:11:01 +000056 ModuleAnalysisManager DummyMAM;
Chandler Carruthe8c66b22017-01-23 08:33:24 +000057 DummyMAM.registerPass(
58 [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); });
59
Chandler Carruth164a2aa62016-06-17 00:11:01 +000060 auto PA = Impl.run(M, DummyMAM);
Davide Italiano66228c42016-05-03 19:39:15 +000061 return !PA.areAllPreserved();
62 }
Chris Lattner8f3acc62002-08-18 01:28:30 +000063
64 private:
Davide Italiano66228c42016-05-03 19:39:15 +000065 GlobalDCEPass Impl;
Chris Lattner04805fa2002-02-26 21:46:54 +000066 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000067}
Nico Weber4b2acde2014-05-02 18:35:25 +000068
Davide Italiano66228c42016-05-03 19:39:15 +000069char GlobalDCELegacyPass::ID = 0;
70INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
71 "Dead Global Elimination", false, false)
72
73// Public interface to the GlobalDCEPass.
74ModulePass *llvm::createGlobalDCEPass() {
75 return new GlobalDCELegacyPass();
76}
77
Adrian Prantl83d87522018-11-16 17:47:21 +000078/// Returns true if F is effectively empty.
Richard Smithc167d652014-05-06 01:44:26 +000079static bool isEmptyFunction(Function *F) {
Nico Weber4b2acde2014-05-02 18:35:25 +000080 BasicBlock &Entry = F->getEntryBlock();
Adrian Prantl83d87522018-11-16 17:47:21 +000081 for (auto &I : Entry) {
82 if (isa<DbgInfoIntrinsic>(I))
83 continue;
84 if (auto *RI = dyn_cast<ReturnInst>(&I))
85 return !RI->getReturnValue();
86 break;
87 }
88 return false;
Nico Weber4b2acde2014-05-02 18:35:25 +000089}
Chris Lattnerd5d56782002-01-31 00:45:11 +000090
Mehdi Amini888dee42017-01-27 19:48:57 +000091/// Compute the set of GlobalValue that depends from V.
92/// The recursion stops as soon as a GlobalValue is met.
93void GlobalDCEPass::ComputeDependencies(Value *V,
94 SmallPtrSetImpl<GlobalValue *> &Deps) {
95 if (auto *I = dyn_cast<Instruction>(V)) {
96 Function *Parent = I->getParent()->getParent();
97 Deps.insert(Parent);
98 } else if (auto *GV = dyn_cast<GlobalValue>(V)) {
99 Deps.insert(GV);
100 } else if (auto *CE = dyn_cast<Constant>(V)) {
101 // Avoid walking the whole tree of a big ConstantExprs multiple times.
102 auto Where = ConstantDependenciesCache.find(CE);
103 if (Where != ConstantDependenciesCache.end()) {
104 auto const &K = Where->second;
105 Deps.insert(K.begin(), K.end());
106 } else {
107 SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
108 for (User *CEUser : CE->users())
109 ComputeDependencies(CEUser, LocalDeps);
110 Deps.insert(LocalDeps.begin(), LocalDeps.end());
111 }
112 }
113}
114
115void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
116 SmallPtrSet<GlobalValue *, 8> Deps;
117 for (User *User : GV.users())
118 ComputeDependencies(User, Deps);
119 Deps.erase(&GV); // Remove self-reference.
120 for (GlobalValue *GVU : Deps) {
Michael Zolotukhinc4fcc182017-10-17 23:47:06 +0000121 GVDependencies[GVU].insert(&GV);
Mehdi Amini888dee42017-01-27 19:48:57 +0000122 }
123}
124
125/// Mark Global value as Live
126void GlobalDCEPass::MarkLive(GlobalValue &GV,
127 SmallVectorImpl<GlobalValue *> *Updates) {
128 auto const Ret = AliveGlobals.insert(&GV);
129 if (!Ret.second)
130 return;
131
132 if (Updates)
133 Updates->push_back(&GV);
134 if (Comdat *C = GV.getComdat()) {
135 for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
136 MarkLive(*CM.second, Updates); // Recursion depth is only two because only
137 // globals in the same comdat are visited.
138 }
139}
140
Chandler Carruthe8c66b22017-01-23 08:33:24 +0000141PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {
Chris Lattner8f3acc62002-08-18 01:28:30 +0000142 bool Changed = false;
Nico Weber4b2acde2014-05-02 18:35:25 +0000143
Mehdi Amini888dee42017-01-27 19:48:57 +0000144 // The algorithm first computes the set L of global variables that are
145 // trivially live. Then it walks the initialization of these variables to
146 // compute the globals used to initialize them, which effectively builds a
147 // directed graph where nodes are global variables, and an edge from A to B
148 // means B is used to initialize A. Finally, it propagates the liveness
149 // information through the graph starting from the nodes in L. Nodes note
150 // marked as alive are discarded.
151
Nico Weber4b2acde2014-05-02 18:35:25 +0000152 // Remove empty functions from the global ctors list.
Richard Smithc167d652014-05-06 01:44:26 +0000153 Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
Nico Weber4b2acde2014-05-02 18:35:25 +0000154
Peter Collingbourne0dbc7082015-03-19 18:23:29 +0000155 // Collect the set of members for each comdat.
156 for (Function &F : M)
157 if (Comdat *C = F.getComdat())
158 ComdatMembers.insert(std::make_pair(C, &F));
159 for (GlobalVariable &GV : M.globals())
160 if (Comdat *C = GV.getComdat())
161 ComdatMembers.insert(std::make_pair(C, &GV));
162 for (GlobalAlias &GA : M.aliases())
163 if (Comdat *C = GA.getComdat())
164 ComdatMembers.insert(std::make_pair(C, &GA));
165
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000166 // Loop over the module, adding globals which are obviously necessary.
Peter Collingbourne6d88fde2016-06-22 20:29:42 +0000167 for (GlobalObject &GO : M.global_objects()) {
168 Changed |= RemoveUnusedGlobalValue(GO);
169 // Functions with external linkage are needed if they have a body.
Chris Lattnerc8dfbbb2003-09-20 19:00:50 +0000170 // Externally visible & appending globals are needed, if they have an
171 // initializer.
Xin Tong9b7e4512018-09-20 21:16:16 +0000172 if (!GO.isDeclaration())
Peter Collingbourne6d88fde2016-06-22 20:29:42 +0000173 if (!GO.isDiscardableIfUnused())
Mehdi Amini888dee42017-01-27 19:48:57 +0000174 MarkLive(GO);
175
176 UpdateGVDependencies(GO);
Chris Lattner8f3acc62002-08-18 01:28:30 +0000177 }
178
Mehdi Amini888dee42017-01-27 19:48:57 +0000179 // Compute direct dependencies of aliases.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000180 for (GlobalAlias &GA : M.aliases()) {
181 Changed |= RemoveUnusedGlobalValue(GA);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000182 // Externally visible aliases are needed.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000183 if (!GA.isDiscardableIfUnused())
Mehdi Amini888dee42017-01-27 19:48:57 +0000184 MarkLive(GA);
185
186 UpdateGVDependencies(GA);
David Majnemerdad0a642014-06-27 18:19:56 +0000187 }
188
Mehdi Amini888dee42017-01-27 19:48:57 +0000189 // Compute direct dependencies of ifuncs.
David Majnemer95549492016-05-04 00:20:48 +0000190 for (GlobalIFunc &GIF : M.ifuncs()) {
191 Changed |= RemoveUnusedGlobalValue(GIF);
192 // Externally visible ifuncs are needed.
193 if (!GIF.isDiscardableIfUnused())
Mehdi Amini888dee42017-01-27 19:48:57 +0000194 MarkLive(GIF);
195
196 UpdateGVDependencies(GIF);
197 }
198
199 // Propagate liveness from collected Global Values through the computed
200 // dependencies.
201 SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
202 AliveGlobals.end()};
203 while (!NewLiveGVs.empty()) {
204 GlobalValue *LGV = NewLiveGVs.pop_back_val();
Michael Zolotukhinc4fcc182017-10-17 23:47:06 +0000205 for (auto *GVD : GVDependencies[LGV])
206 MarkLive(*GVD, &NewLiveGVs);
David Majnemer95549492016-05-04 00:20:48 +0000207 }
208
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000209 // Now that all globals which are needed are in the AliveGlobals set, we loop
210 // through the program, deleting those which are not alive.
Chris Lattner8f3acc62002-08-18 01:28:30 +0000211 //
Chris Lattner8f3acc62002-08-18 01:28:30 +0000212
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000213 // The first pass is to drop initializers of global variables which are dead.
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000214 std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
215 for (GlobalVariable &GV : M.globals())
216 if (!AliveGlobals.count(&GV)) {
217 DeadGlobalVars.push_back(&GV); // Keep track of dead globals
218 if (GV.hasInitializer()) {
219 Constant *Init = GV.getInitializer();
220 GV.setInitializer(nullptr);
Bruno Cardoso Lopese2a1fa32014-08-25 17:51:14 +0000221 if (isSafeToDestroyConstant(Init))
222 Init->destroyConstant();
223 }
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000224 }
225
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000226 // The second pass drops the bodies of functions which are dead...
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000227 std::vector<Function *> DeadFunctions;
228 for (Function &F : M)
229 if (!AliveGlobals.count(&F)) {
230 DeadFunctions.push_back(&F); // Keep track of dead globals
Chandler Carruth6acdca72017-01-24 12:55:57 +0000231 if (!F.isDeclaration())
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000232 F.deleteBody();
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000233 }
234
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000235 // The third pass drops targets of aliases which are dead...
236 std::vector<GlobalAlias*> DeadAliases;
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000237 for (GlobalAlias &GA : M.aliases())
238 if (!AliveGlobals.count(&GA)) {
239 DeadAliases.push_back(&GA);
240 GA.setAliasee(nullptr);
Duncan Sandsbf3ba5a2009-02-17 23:05:26 +0000241 }
242
Mehdi Amini888dee42017-01-27 19:48:57 +0000243 // The fourth pass drops targets of ifuncs which are dead...
David Majnemer95549492016-05-04 00:20:48 +0000244 std::vector<GlobalIFunc*> DeadIFuncs;
245 for (GlobalIFunc &GIF : M.ifuncs())
246 if (!AliveGlobals.count(&GIF)) {
247 DeadIFuncs.push_back(&GIF);
248 GIF.setResolver(nullptr);
249 }
250
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000251 // Now that all interferences have been dropped, delete the actual objects
252 // themselves.
253 auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
254 RemoveUnusedGlobalValue(*GV);
255 GV->eraseFromParent();
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000256 Changed = true;
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000257 };
Chris Lattner8f3acc62002-08-18 01:28:30 +0000258
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000259 NumFunctions += DeadFunctions.size();
260 for (Function *F : DeadFunctions)
261 EraseUnusedGlobalValue(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000262
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000263 NumVariables += DeadGlobalVars.size();
264 for (GlobalVariable *GV : DeadGlobalVars)
265 EraseUnusedGlobalValue(GV);
Duncan Sandsf5dbbae2009-01-05 20:37:33 +0000266
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000267 NumAliases += DeadAliases.size();
268 for (GlobalAlias *GA : DeadAliases)
269 EraseUnusedGlobalValue(GA);
270
Peter Collingbourne4f3b2df2016-10-25 02:57:27 +0000271 NumIFuncs += DeadIFuncs.size();
Peter Collingbourne7695cb62016-10-25 01:58:26 +0000272 for (GlobalIFunc *GIF : DeadIFuncs)
273 EraseUnusedGlobalValue(GIF);
David Majnemer95549492016-05-04 00:20:48 +0000274
Chris Lattnerec6d7a62003-09-16 19:27:31 +0000275 // Make sure that all memory is released
276 AliveGlobals.clear();
Mehdi Amini888dee42017-01-27 19:48:57 +0000277 ConstantDependenciesCache.clear();
278 GVDependencies.clear();
Peter Collingbourne0dbc7082015-03-19 18:23:29 +0000279 ComdatMembers.clear();
Devang Patelc5aa8c62009-08-11 06:31:57 +0000280
Davide Italiano66228c42016-05-03 19:39:15 +0000281 if (Changed)
282 return PreservedAnalyses::none();
283 return PreservedAnalyses::all();
Chris Lattner8f3acc62002-08-18 01:28:30 +0000284}
285
Reid Spencer5f681592004-07-18 00:25:04 +0000286// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
Chris Lattner8f3acc62002-08-18 01:28:30 +0000287// GlobalValue, looking for the constant pointer ref that may be pointing to it.
288// If found, check to see if the constant pointer ref is safe to destroy, and if
289// so, nuke it. This will reduce the reference count on the global value, which
290// might make it deader.
291//
Davide Italiano66228c42016-05-03 19:39:15 +0000292bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
Yaron Keren3d49f6d2015-07-18 19:57:34 +0000293 if (GV.use_empty())
294 return false;
Chris Lattner9238d782004-07-18 07:22:58 +0000295 GV.removeDeadConstantUsers();
296 return GV.use_empty();
297}