konsolas
konsolas

Reputation: 1091

What does LEA do internally?

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.

Upvotes: 3

Views: 314

Answers (1)

NPE
NPE

Reputation: 500357

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.

Upvotes: 6

Related Questions