I use LLVM/Clang to compile some program.
I found that if we use -O0 flag, the program will use ebp to access local variables.
For example : mov ecx,DWORD PTR [ebp-0x8]
If we use -O2 flag, the program will use esp to access local variables.
For example : mov eax,DWORD PTR [esp+0x8]
Is there any different between them?
Can user decide esp or ebp to access the local variable?
Or can I modify LLVM backend code to do it?
Is there any calling convention related to it?
I found it is the same in gcc.
When EBP is used, it’s known as the frame pointer. It points to a fixed location on the stack throughout the body of the function. It makes local variables easy to find because they are always at the same place relative to EBP. ESP’s value can change through the function as other functions are called. So the location of a local variable can require a different offset depending on how much ESP has been changed throughout the function. Having a frame pointer makes a debugging tool like gdb’s job easier. But using a frame pointer ties up another register. Leaving only 6 registers available for computation in 32-bit mode. So by default for optimized code we try not to use it. There are still situations where it is required. You can force the frame pointer to always be used by passing -fno-omit-frame-pointer to clang.
Some more information can be found here https://stackoverflow.com/questions/579262/what-is-the-purpose-of-the-ebp-frame-pointer-register