Reg. llvm.dbg.declare

Hi all,

I’m trying to generate IR with debug option (-g) for the following code snippet.

int func(int i) {
return i+1;
}

The corresponding IR for the function definition is:

define i32 @func(i32 %i) #0 !dbg !7 {
entry:
%i.addr = alloca i32, align 4
store i32 %i, i32* %i.addr, align 4
call void @llvm.dbg.declare(metadata i32* %i.addr, metadata !11, metadata !12), !dbg !13
%0 = load i32, i32* %i.addr, align 4, !dbg !14
%add = add nsw i32 %0, 1, !dbg !15
ret i32 %add, !dbg !16
}

I’m confused about why the “call void @llvm.dbg.declare(metadata i32* %i.addr, metadata !11, metadata !12), !dbg !13” appears after an usage of %i.addr (store i32 %i, i32* %i.addr, align 4). Should the use of %i.addr happen after llvm.dbg.declare or does it have any specific reason for this? Am I missing something here?

Thank you very much,
Akash Banerjee

Hi Akash,

I'm confused about why the "call void @llvm.dbg.declare(metadata i32* %i.addr, metadata !11, metadata !12), !dbg !13" appears after an usage of %i.addr (store i32 %i, i32* %i.addr, align 4).

Putting the dbg.declare (tagged with the first line of the function)
after that initial store ensures that a debugger will never see an
invalid value for formal parameters like that. Whenever a debugger
stops on the line, "i" will have been initialized from the incoming
register (or stack slot), which seems like a good thing to me.

On the other hand Clang doesn't seem so picky for normal local
variables, which only get their stable value on the next line after
they've been declared. So it's quite likely (IMO) that it's just a
quirk of how Clang goes about generating IR and the order it does
things in (generate allocas -> call target-specific code to marshal
args but don't make it worry about debugging info -> officially
declare any args).

You might get a more definitive answer to "why" if you asked this in
the cfe-dev mailing list, especially if you catch the attention of
whoever wrote the code. Here we're more able to answer questions on
the implications of that order for debugging.

Cheers.

Tim.