Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/IPO/GlobalDCE.cpp
Line
Count
Source
1
//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
2
//
3
// 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
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// 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.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "llvm/Transforms/IPO/GlobalDCE.h"
18
#include "llvm/ADT/SmallPtrSet.h"
19
#include "llvm/ADT/Statistic.h"
20
#include "llvm/IR/Instructions.h"
21
#include "llvm/IR/IntrinsicInst.h"
22
#include "llvm/IR/Module.h"
23
#include "llvm/Pass.h"
24
#include "llvm/Transforms/IPO.h"
25
#include "llvm/Transforms/Utils/CtorUtils.h"
26
#include "llvm/Transforms/Utils/GlobalStatus.h"
27
28
using namespace llvm;
29
30
#define DEBUG_TYPE "globaldce"
31
32
STATISTIC(NumAliases  , "Number of global aliases removed");
33
STATISTIC(NumFunctions, "Number of functions removed");
34
STATISTIC(NumIFuncs,    "Number of indirect functions removed");
35
STATISTIC(NumVariables, "Number of global variables removed");
36
37
namespace {
38
  class GlobalDCELegacyPass : public ModulePass {
39
  public:
40
    static char ID; // Pass identification, replacement for typeid
41
27.1k
    GlobalDCELegacyPass() : ModulePass(ID) {
42
27.1k
      initializeGlobalDCELegacyPassPass(*PassRegistry::getPassRegistry());
43
27.1k
    }
44
45
    // run - Do the GlobalDCE pass on the specified module, optionally updating
46
    // the specified callgraph to reflect the changes.
47
    //
48
27.1k
    bool runOnModule(Module &M) override {
49
27.1k
      if (skipModule(M))
50
4
        return false;
51
27.1k
52
27.1k
      // We need a minimally functional dummy module analysis manager. It needs
53
27.1k
      // to at least know about the possibility of proxying a function analysis
54
27.1k
      // manager.
55
27.1k
      FunctionAnalysisManager DummyFAM;
56
27.1k
      ModuleAnalysisManager DummyMAM;
57
27.1k
      DummyMAM.registerPass(
58
27.1k
          [&] { return FunctionAnalysisManagerModuleProxy(DummyFAM); });
59
27.1k
60
27.1k
      auto PA = Impl.run(M, DummyMAM);
61
27.1k
      return !PA.areAllPreserved();
62
27.1k
    }
63
64
  private:
65
    GlobalDCEPass Impl;
66
  };
67
}
68
69
char GlobalDCELegacyPass::ID = 0;
70
INITIALIZE_PASS(GlobalDCELegacyPass, "globaldce",
71
                "Dead Global Elimination", false, false)
72
73
// Public interface to the GlobalDCEPass.
74
27.1k
ModulePass *llvm::createGlobalDCEPass() {
75
27.1k
  return new GlobalDCELegacyPass();
76
27.1k
}
77
78
/// Returns true if F is effectively empty.
79
418
static bool isEmptyFunction(Function *F) {
80
418
  BasicBlock &Entry = F->getEntryBlock();
81
419
  for (auto &I : Entry) {
82
419
    if (isa<DbgInfoIntrinsic>(I))
83
1
      continue;
84
418
    if (auto *RI = dyn_cast<ReturnInst>(&I))
85
5
      return !RI->getReturnValue();
86
413
    break;
87
413
  }
88
418
  
return false413
;
89
418
}
90
91
/// Compute the set of GlobalValue that depends from V.
92
/// The recursion stops as soon as a GlobalValue is met.
93
void GlobalDCEPass::ComputeDependencies(Value *V,
94
6.87M
                                        SmallPtrSetImpl<GlobalValue *> &Deps) {
95
6.87M
  if (auto *I = dyn_cast<Instruction>(V)) {
96
5.42M
    Function *Parent = I->getParent()->getParent();
97
5.42M
    Deps.insert(Parent);
98
5.42M
  } else 
if (auto *1.45M
GV1.45M
= dyn_cast<GlobalValue>(V)) {
99
81.5k
    Deps.insert(GV);
100
1.37M
  } else if (auto *CE = dyn_cast<Constant>(V)) {
101
1.37M
    // Avoid walking the whole tree of a big ConstantExprs multiple times.
102
1.37M
    auto Where = ConstantDependenciesCache.find(CE);
103
1.37M
    if (Where != ConstantDependenciesCache.end()) {
104
219k
      auto const &K = Where->second;
105
219k
      Deps.insert(K.begin(), K.end());
106
1.15M
    } else {
107
1.15M
      SmallPtrSetImpl<GlobalValue *> &LocalDeps = ConstantDependenciesCache[CE];
108
1.15M
      for (User *CEUser : CE->users())
109
1.97M
        ComputeDependencies(CEUser, LocalDeps);
110
1.15M
      Deps.insert(LocalDeps.begin(), LocalDeps.end());
111
1.15M
    }
112
1.37M
  }
113
6.87M
}
114
115
1.76M
void GlobalDCEPass::UpdateGVDependencies(GlobalValue &GV) {
116
1.76M
  SmallPtrSet<GlobalValue *, 8> Deps;
117
1.76M
  for (User *User : GV.users())
118
4.89M
    ComputeDependencies(User, Deps);
119
1.76M
  Deps.erase(&GV); // Remove self-reference.
120
3.12M
  for (GlobalValue *GVU : Deps) {
121
3.12M
    GVDependencies[GVU].insert(&GV);
122
3.12M
  }
123
1.76M
}
124
125
/// Mark Global value as Live
126
void GlobalDCEPass::MarkLive(GlobalValue &GV,
127
3.61M
                             SmallVectorImpl<GlobalValue *> *Updates) {
128
3.61M
  auto const Ret = AliveGlobals.insert(&GV);
129
3.61M
  if (!Ret.second)
130
1.85M
    return;
131
1.76M
132
1.76M
  if (Updates)
133
1.27M
    Updates->push_back(&GV);
134
1.76M
  if (Comdat *C = GV.getComdat()) {
135
721
    for (auto &&CM : make_range(ComdatMembers.equal_range(C)))
136
1.01k
      MarkLive(*CM.second, Updates); // Recursion depth is only two because only
137
721
                                     // globals in the same comdat are visited.
138
721
  }
139
1.76M
}
140
141
27.5k
PreservedAnalyses GlobalDCEPass::run(Module &M, ModuleAnalysisManager &MAM) {
142
27.5k
  bool Changed = false;
143
27.5k
144
27.5k
  // The algorithm first computes the set L of global variables that are
145
27.5k
  // trivially live.  Then it walks the initialization of these variables to
146
27.5k
  // compute the globals used to initialize them, which effectively builds a
147
27.5k
  // directed graph where nodes are global variables, and an edge from A to B
148
27.5k
  // means B is used to initialize A.  Finally, it propagates the liveness
149
27.5k
  // information through the graph starting from the nodes in L. Nodes note
150
27.5k
  // marked as alive are discarded.
151
27.5k
152
27.5k
  // Remove empty functions from the global ctors list.
153
27.5k
  Changed |= optimizeGlobalCtorsList(M, isEmptyFunction);
154
27.5k
155
27.5k
  // Collect the set of members for each comdat.
156
27.5k
  for (Function &F : M)
157
865k
    if (Comdat *C = F.getComdat())
158
453
      ComdatMembers.insert(std::make_pair(C, &F));
159
27.5k
  for (GlobalVariable &GV : M.globals())
160
896k
    if (Comdat *C = GV.getComdat())
161
244
      ComdatMembers.insert(std::make_pair(C, &GV));
162
27.5k
  for (GlobalAlias &GA : M.aliases())
163
145
    if (Comdat *C = GA.getComdat())
164
47
      ComdatMembers.insert(std::make_pair(C, &GA));
165
27.5k
166
27.5k
  // Loop over the module, adding globals which are obviously necessary.
167
1.76M
  for (GlobalObject &GO : M.global_objects()) {
168
1.76M
    Changed |= RemoveUnusedGlobalValue(GO);
169
1.76M
    // Functions with external linkage are needed if they have a body.
170
1.76M
    // Externally visible & appending globals are needed, if they have an
171
1.76M
    // initializer.
172
1.76M
    if (!GO.isDeclaration())
173
1.42M
      if (!GO.isDiscardableIfUnused())
174
485k
        MarkLive(GO);
175
1.76M
176
1.76M
    UpdateGVDependencies(GO);
177
1.76M
  }
178
27.5k
179
27.5k
  // Compute direct dependencies of aliases.
180
27.5k
  for (GlobalAlias &GA : M.aliases()) {
181
145
    Changed |= RemoveUnusedGlobalValue(GA);
182
145
    // Externally visible aliases are needed.
183
145
    if (!GA.isDiscardableIfUnused())
184
133
      MarkLive(GA);
185
145
186
145
    UpdateGVDependencies(GA);
187
145
  }
188
27.5k
189
27.5k
  // Compute direct dependencies of ifuncs.
190
27.5k
  for (GlobalIFunc &GIF : M.ifuncs()) {
191
9
    Changed |= RemoveUnusedGlobalValue(GIF);
192
9
    // Externally visible ifuncs are needed.
193
9
    if (!GIF.isDiscardableIfUnused())
194
7
      MarkLive(GIF);
195
9
196
9
    UpdateGVDependencies(GIF);
197
9
  }
198
27.5k
199
27.5k
  // Propagate liveness from collected Global Values through the computed
200
27.5k
  // dependencies.
201
27.5k
  SmallVector<GlobalValue *, 8> NewLiveGVs{AliveGlobals.begin(),
202
27.5k
                                           AliveGlobals.end()};
203
1.78M
  while (!NewLiveGVs.empty()) {
204
1.76M
    GlobalValue *LGV = NewLiveGVs.pop_back_val();
205
1.76M
    for (auto *GVD : GVDependencies[LGV])
206
3.12M
      MarkLive(*GVD, &NewLiveGVs);
207
1.76M
  }
208
27.5k
209
27.5k
  // Now that all globals which are needed are in the AliveGlobals set, we loop
210
27.5k
  // through the program, deleting those which are not alive.
211
27.5k
  //
212
27.5k
213
27.5k
  // The first pass is to drop initializers of global variables which are dead.
214
27.5k
  std::vector<GlobalVariable *> DeadGlobalVars; // Keep track of dead globals
215
27.5k
  for (GlobalVariable &GV : M.globals())
216
896k
    if (!AliveGlobals.count(&GV)) {
217
122
      DeadGlobalVars.push_back(&GV);         // Keep track of dead globals
218
122
      if (GV.hasInitializer()) {
219
86
        Constant *Init = GV.getInitializer();
220
86
        GV.setInitializer(nullptr);
221
86
        if (isSafeToDestroyConstant(Init))
222
16
          Init->destroyConstant();
223
86
      }
224
122
    }
225
27.5k
226
27.5k
  // The second pass drops the bodies of functions which are dead...
227
27.5k
  std::vector<Function *> DeadFunctions;
228
27.5k
  for (Function &F : M)
229
865k
    if (!AliveGlobals.count(&F)) {
230
531
      DeadFunctions.push_back(&F);         // Keep track of dead globals
231
531
      if (!F.isDeclaration())
232
90
        F.deleteBody();
233
531
    }
234
27.5k
235
27.5k
  // The third pass drops targets of aliases which are dead...
236
27.5k
  std::vector<GlobalAlias*> DeadAliases;
237
27.5k
  for (GlobalAlias &GA : M.aliases())
238
145
    if (!AliveGlobals.count(&GA)) {
239
3
      DeadAliases.push_back(&GA);
240
3
      GA.setAliasee(nullptr);
241
3
    }
242
27.5k
243
27.5k
  // The fourth pass drops targets of ifuncs which are dead...
244
27.5k
  std::vector<GlobalIFunc*> DeadIFuncs;
245
27.5k
  for (GlobalIFunc &GIF : M.ifuncs())
246
9
    if (!AliveGlobals.count(&GIF)) {
247
1
      DeadIFuncs.push_back(&GIF);
248
1
      GIF.setResolver(nullptr);
249
1
    }
250
27.5k
251
27.5k
  // Now that all interferences have been dropped, delete the actual objects
252
27.5k
  // themselves.
253
27.5k
  auto EraseUnusedGlobalValue = [&](GlobalValue *GV) {
254
657
    RemoveUnusedGlobalValue(*GV);
255
657
    GV->eraseFromParent();
256
657
    Changed = true;
257
657
  };
258
27.5k
259
27.5k
  NumFunctions += DeadFunctions.size();
260
27.5k
  for (Function *F : DeadFunctions)
261
531
    EraseUnusedGlobalValue(F);
262
27.5k
263
27.5k
  NumVariables += DeadGlobalVars.size();
264
27.5k
  for (GlobalVariable *GV : DeadGlobalVars)
265
122
    EraseUnusedGlobalValue(GV);
266
27.5k
267
27.5k
  NumAliases += DeadAliases.size();
268
27.5k
  for (GlobalAlias *GA : DeadAliases)
269
3
    EraseUnusedGlobalValue(GA);
270
27.5k
271
27.5k
  NumIFuncs += DeadIFuncs.size();
272
27.5k
  for (GlobalIFunc *GIF : DeadIFuncs)
273
1
    EraseUnusedGlobalValue(GIF);
274
27.5k
275
27.5k
  // Make sure that all memory is released
276
27.5k
  AliveGlobals.clear();
277
27.5k
  ConstantDependenciesCache.clear();
278
27.5k
  GVDependencies.clear();
279
27.5k
  ComdatMembers.clear();
280
27.5k
281
27.5k
  if (Changed)
282
135
    return PreservedAnalyses::none();
283
27.3k
  return PreservedAnalyses::all();
284
27.3k
}
285
286
// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
287
// 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
//
292
1.76M
bool GlobalDCEPass::RemoveUnusedGlobalValue(GlobalValue &GV) {
293
1.76M
  if (GV.use_empty())
294
308k
    return false;
295
1.45M
  GV.removeDeadConstantUsers();
296
1.45M
  return GV.use_empty();
297
1.45M
}