Can we keep debug information of local variable when in the optimization condition?

Hi, I’m curious that whether we can keep debug information of local variable when in the optimization condition (for example -O2, -O3) in LLVM.

For example this simple C source code:

int main()

{
int i = 5;
if(i > 5) {
return 1;
} else {
return 0;
}
}

If we compile clang -g a.c, we can get our expected result. We can check and update the local variable i in the debugger.

However, when we compile it using clang -O3 -g a.c, we can only check the variable i but we can not update the local variable i.

I know, the design of LLVM opt-debug is that debug can not affect optimization, so this case llvm-opt will turn the llvm.dbg.declare and related alloc / store instruction to llvm.dbg.value, we don’t have symbol of local variable i. So we can only check local variable i but we can not update the value of local variable i like set variable i = 7 in the gdb.

I think keep debug information of local variable in some condition is very useful and I want to explore it. However, I find there are many places do this work of local variable debug info. I want to know whether I have one simple way like disabling some passes or modify some llvm code to continue this way.

Thanks in advance.

I don’t think there’s any simple approach to this - there’s been some idea that -O1 (or -Og, or that -O1 shuold be -Og) could be made to be this mode, where values are still findable/etc. (though I’m not sure “modifiable” is a goal there - the ability to see the behavior of the program correctly is one thing, but making sure all values are modifiable would be a larger goal and probably really limit the ability to optimize the program)

  • Dave

In this specific example, with optimization, the compiler sees that in the source code, the value of the variable ‘i’ is set once and does not change afterward. Therefore the compiler can substitute the known value into the expressions that use the variable, and when it is done optimizing, in fact there is no need for a register or memory location for the variable. That is why you cannot modify the value in the debugger. The debug information correctly reflects that the variable has the value ‘5’ and that is as much as we can do with the optimized code.

If you have a particular function that you want to debug, you can use the optnone attribute or #pragma clang optimize pragma to suppress optimization.

–paulr