Getting the original variable name for an LLVM Value

Will picture Will · Jan 28, 2014 · Viewed 7.5k times · Source

The operands for an llvm::User (e.g. instruction) are llvm::Values.

After the mem2reg pass, variables are in SSA form, and their names as corresponding to the original source code are lost. Value::getName() is only set for some things; for most variables, which are intermediaries, its not set.

The instnamer pass can be run to give all the variables names like tmp1 and tmp2, but this doesn't capture where they originally come from. Here's some LLVM IR beside the original C code:

enter image description here

I am building a simple html page to visualise and debug some optimisations I am working on, and I want to show the SSA variables as namever notation, rather than just temporary instnamer names. Its just to aid my readability.

I am getting my LLVM IR from clang with a commandline such as:

 clang -g3 -O1 -emit-llvm -o test.bc -c test.c

There are calls to llvm.dbg.declare and llvm.dbg.value in the IR; how do you turn into the original sourcecode names and SSA version numbers?

So how can I determine the original variable (or named constant name) from an llvm::Value? Debuggers must be able to do this, so how can I?

Answer

Eli Bendersky picture Eli Bendersky · Jan 28, 2014

This is part of the debug information that's attached to LLVM IR in the form of metadata. Documentation is here. An old blog post with some background is also available.


$ cat  > z.c
long fact(long arg, long farg, long bart)
{
    long foo = farg + bart;
    return foo * arg;
}

$ clang -emit-llvm -O3 -g -c z.c
$ llvm-dis z.bc -o -

Produces this:

define i64 @fact(i64 %arg, i64 %farg, i64 %bart) #0 {
entry:
  tail call void @llvm.dbg.value(metadata !{i64 %arg}, i64 0, metadata !10), !dbg !17
  tail call void @llvm.dbg.value(metadata !{i64 %farg}, i64 0, metadata !11), !dbg !17
  tail call void @llvm.dbg.value(metadata !{i64 %bart}, i64 0, metadata !12), !dbg !17
  %add = add nsw i64 %bart, %farg, !dbg !18
  tail call void @llvm.dbg.value(metadata !{i64 %add}, i64 0, metadata !13), !dbg !18
  %mul = mul nsw i64 %add, %arg, !dbg !19
  ret i64 %mul, !dbg !19
}

With -O0 instead of -O3, you won't see llvm.dbg.value, but you will see llvm.dbg.declare.