Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does LEA do internally?

Tags:

x86

assembly

This question says that the LEA instruction can be used to do arithmetic.

As I understand it, instead of:

inc eax
mov ecx, 5
mul ecx
mov ebx, eax

I can simply write

lea ebx, [(eax + 1) * 5]

The LEA version is only a single instruction as opposed to the 4. However, I don't understand how LEA does the arithmetic without inc and mul.

Is the LEA version faster in any way, or does LEA simply run the original instructions in the background?

EDIT: This question is not about the purpose of LEA, but rather how it works internally.

like image 885
konsolas Avatar asked Nov 24 '25 19:11

konsolas


1 Answers

I don't understand how LEA does the arithmetic without INC and MUL.

The key is that LEA can only do certain types of arithmetic: the sort that's useful in computing memory addresses for things like array access.

Think of the CPU as having specialized circuitry for this sort of address computations, and LEA as the instruction for using that circuitry.

You can read up on the x86 addressing modes in Wikipedia. It shows that types of computations you can perform with LEA.

In a nutshell, it's a register multiplied by 1/2/4/8, plus a register, plus a constant. The only reason you can compute (eax + 1) * 5 with LEA is that it's equivalent to eax * 4 + eax + 5. If you, for example, were trying to compute (eax + 1) * 6, LEA would not be of any help, while the generic MUL and ADD would still work just fine.

like image 108
NPE Avatar answered Nov 27 '25 08:11

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!