What is the difference between “lea eax, [ebx + eax]” and “add eax, ebx” in x86-32 assembly?

StackOverflow https://stackoverflow.com/questions/4316526

  •  29-09-2019
  •  | 
  •  

Question

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

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]
Was it helpful?

Solution

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 :)

OTHER TIPS

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.)

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:

  1. 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.

  2. 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 or lea depending on context can eliminate these (very small) stalls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top