Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant Assembly Instructions?

Recently I've been trying to learn reverse-engineering. As such, I've been delving into a lot of assembly code. I'm mystified by the following:

movq    %rax,0xf8(%rbp)
movq    0xf8(%rbp),%rax

I've seen this several times. Is it not redundant? Why does the compiler do this? The binary I'm looking at was compiled with gcc.

like image 542
Jarsen Avatar asked Jan 20 '23 10:01

Jarsen


1 Answers

You probably compiled without optimization (-O). What you're seeing is a direct, naive translation of the intermediate representation. Snippets like this are usually due to the value being stored in a local variable, in this case 0xf8(%rbp). The value is then used immediately afterwards, so it loads it again into a register, %rax. The optimizer will spot that storing from %rax only to restore back to the very same register is redundant and remove the sequence altogether. If all optimization stages fail, at the very least a peephole will spot these two instructions being consecutive.

If you really do have optimization turned on, then this is indeed odd, but might be explained if you post a larger (but not excessively large) sequence. There's still plenty of cases where something blatantly sub-optimal will be generated, but nothing as blatant as that.

like image 196
John Ripley Avatar answered Jan 25 '23 02:01

John Ripley