Elimination of dead globals (functions/variables)

With llvm-gcc the following test case

static int alive, dead;
void foo(int v) { glob_alive = v; }
int FOO() { return glob_alive; }
static void bar(int v) { gdead = v; }
static int BAR() { return dead; }

is correctly pruned down to only foo, FOO, and alive, but with the following warnings:

warning: 'bar' defined but not used
warning: 'BAR' defined but not used

clang with -emit-llvm currently emits everything (with no warnings) and opt isn't able to reduce it. What needs to be done by clang to get the non-visible parts of the module stripped out? In addition to diagnostics is clang responsible for not generating code for unused functions, or is it simply responsible for passing some sort of information so that opt can do the chopping?

clang should mark static functions as internal functions to help optimizer identify dead code.

llvm-gcc emits
  define internal void @bar(i32 %v) { ... }
where as clang emits
  define void @bar(i32 %v) { ... }

I just implemented this, we now get:

$ clang t.c -emit-llvm | llvm-as | opt -std-compile-opts | llvm-dis

; ModuleID = '<stdin>'
target triple = "i686-apple-darwin9"
@glob_alive = internal global i32 0 ; <i32*> [#uses=2]

define void @foo(i32 %v) {
entry:
  store i32 %v, i32* @glob_alive, align 4
  ret void
}

define i32 @FOO() {
entry:
  %tmp = load i32* @glob_alive, align 4 ; <i32> [#uses=1]
  ret i32 %tmp
}

However, it would be even better to emit functions on demand, starting from ones that are intrinsically alive. Basically, only emit LLVM code for functions/globals if they have external linkage. Once those are emitted, emit all static functions/globals that are referenced from these. At the end, do a walk over static functions and emit the warning above for any that weren't emitted.

-Chris