What is the difference between "lea eax, [ebx + eax]" and "add eax, ebx" in x86-32 assembly?
GCC made me some assembly code, and inside theres this statement:
lea eax, [ebx+eax]
(Intel Syntax) Just curious, what would the difference between that, and:
add eax, ebx
开发者_StackOverflow社区Be?
eax, and ebx contains return values from functions :)
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC1
mov ebx, eax.
mov eax, DWORD PTR [ebp+8]
mov DWORD PTR [esp], eax
call CALC2
lea eax, [ebx+eax]
One difference that immediately springs to mind is that lea
doesn't affect the flags, whereas add
does.
It is impossible to say without seeing the rest of the assembly code whether this is of any relevance. It could simply be an artefact of the GCC's code generator (i.e. it could in fact be producing code for a more general case or just using lea
as a more flexible add
.)
You can put the result into another register than EAX, such as lea edx, eax + ebx
. add
cannot do it.
lea
can also have an additional third operand such as lea eax, ebp + esi + 12
which makes it a handier alternative to add
instruction.
You can also combine certain (word-sized) multiplication operations with it, such as lea eax, ebp + eax * 8
.
Not to mention that it describes the intent better :)
In terms of the numeric result, there is no difference.
However, there is more to an instruction than the actual result that is stored in the destination register:
As aix pointed out,
lea
does not set the flags based on the result of the addition. This is occasionally useful for instruction scheduling purposes.There are also timing differences on some micro-architectures (early Atom cores); specifically, there are stalls involved in forwarding results between the arithmetic and address-generation units, and using either
add
orlea
depending on context can eliminate these (very small) stalls.
精彩评论