Eliminate dead global variables
authorChris Lattner <sabre@nondot.org>
Mon, 29 Apr 2002 18:13:11 +0000 (18:13 +0000)
committerChris Lattner <sabre@nondot.org>
Mon, 29 Apr 2002 18:13:11 +0000 (18:13 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@2400 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Transforms/IPO/GlobalDCE.cpp

index 2f938079a8481fd7d90235edb1be43552704fb64..a0614e2bf3130ebcff840498eb3b7b14fe03c4b1 100644 (file)
@@ -6,9 +6,10 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/Transforms/IPO/GlobalDCE.h"
-#include "llvm/Analysis/CallGraph.h"
 #include "llvm/Module.h"
 #include "llvm/Function.h"
+#include "llvm/GlobalVariable.h"
+#include "llvm/Analysis/CallGraph.h"
 #include "Support/DepthFirstIterator.h"
 
 static bool RemoveUnreachableFunctions(Module *M, CallGraph &CallGraph) {
@@ -45,6 +46,22 @@ static bool RemoveUnreachableFunctions(Module *M, CallGraph &CallGraph) {
   return true;
 }
 
+static bool RemoveUnreachableGlobalVariables(Module *M) {
+  bool Changed = false;
+  // Eliminate all global variables that are unused, and that are internal, or
+  // do not have an initializer.
+  //
+  for (Module::giterator I = M->gbegin(); I != M->gend(); )
+    if (!(*I)->use_empty() ||
+        ((*I)->hasExternalLinkage() && (*I)->hasInitializer()))
+      ++I;                     // Cannot eliminate global variable
+    else {
+      delete M->getGlobalList().remove(I);
+      Changed = true;
+    }
+  return Changed;
+}
+
 namespace {
   struct GlobalDCE : public Pass {
     const char *getPassName() const { return "Dead Global Elimination"; }
@@ -53,7 +70,8 @@ namespace {
     // the specified callgraph to reflect the changes.
     //
     bool run(Module *M) {
-      return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>());
+      return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) |
+             RemoveUnreachableGlobalVariables(M);
     }
 
     // getAnalysisUsage - This function works on the call graph of a module.