1

From experience, I have seen that,

lea rax, [2*rax + rax +1]

is equivanelt to:

mul rax, 3
inc rax

But, what is LEA exactly doing? If rax = 3 prior to the instruction, is it returning the address of wherever 10 is stored in memory? How can that address be the number 10 itself?

Any help would be appreciated. Thank you.

user2999870
  • 345
  • 4
  • 12
  • I have very limited knowledge of assembly, but I think reading [THIS](https://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction) question might help you understand the LEA command. – VTodorov Nov 07 '17 at 09:02
  • @VTodorov, Ok, I think I understand it. From what I see, the text inside [ ] is itself the address and lea just extracts that value and loads it to destination. So [addr] is a pointer which points to address # addr – user2999870 Nov 07 '17 at 09:10
  • 1
    Possible duplicate of [What's the purpose of the LEA instruction?](https://stackoverflow.com/questions/1658294/whats-the-purpose-of-the-lea-instruction) – Johan Nov 07 '17 at 10:04
  • Also related: https://stackoverflow.com/questions/46597055/address-computation-instruction-leaq/46597375#46597375 answers another question about using LEA for non-address math. – Peter Cordes Nov 07 '17 at 14:14

1 Answers1

4

The intel-x86 architecture allows for some complex address calculations when doing memory accesses. This is what's inside the [] brackets.

Since the address calculation is so powerful intel added the LEA instruction which does just the address calculation part of an memory access. It does not access memory at all but stores the result of the calculation in a register instead.

Because all the arithmetic logic was already in the chip this versatile instruction was cheap to add, so intel just did that.

Regarding the use: It is easier to think about LEA as a specialized ADD instruction that can add registers, constants and registers using a limited number of shifts.

Technically it is using the address calculation part of the processor, but it will never access the memory. For you as a programmer it does not make a difference except that LEA will not change the flags.

Nils Pipenbrinck
  • 83,631
  • 31
  • 151
  • 221
  • You managed to explain this much more succinctly than I did when I took a stab at answering another duplicate of this: https://stackoverflow.com/questions/46597055/address-computation-instruction-leaq/46597375#46597375. But you still make most of the important points. (BTW, on most modern CPUs LEA doesn't use the AGUs, but it does of course use the addressing-mode decoders to decode ModR/M (+SIB) (+disp8/disp32). Or RIP-relative addressing modes.) – Peter Cordes Nov 07 '17 at 14:18
  • @PeterCordes I know you're the low-level guy here, peter. Thanks for the compliments. :-) ' – Nils Pipenbrinck Nov 07 '17 at 14:41