0

Why can we write this:

mov rax, [array + 2*rcx]

and cannot this:

mov rax, [array + rcx*rcx]

Why can we do complex calculations in addition to main instruction (mov) in first case and cannot do only slightly more complex ones in second? And why can we add to memory:

add [array], 1

What is happening under the hood?

Jester
  • 56,577
  • 4
  • 81
  • 125
DSblizzard
  • 4,007
  • 7
  • 48
  • 76
  • 3
    Because it's the cpu doing the computations and it can only do a limited form. Also the machine encoding has corresponding limits obviously. Consult the manuals about specifics. TL;DR: `[base+index*scale+offset]` with `base` and `index` being a GPR and `scale` being 1,2,4 or 8 and `offset` a constant. Adding to memory is a read-modify-write. x86 allows that because it's CISC. – Jester Nov 07 '19 at 16:34
  • @Jester: I think stackoverflow.com needs an "auto-convert comment into answer" button. ;-) – Brendan Nov 07 '19 at 17:01
  • 1
    For more under-the-hood details on memory-destination `add` and other execution internals (how they decode to uops) on modern x86 CPUs, see Agner Fog's microarch guide: https://agner.org/optimize/. e.g. on modern Intel the load+add uops micro-fuse, and so do the store-address and store-data uops, so we have 2 fused-domain uops for 4 unfused-domain uops (that each need an execution unit) – Peter Cordes Nov 07 '19 at 18:42
  • 1
    It is not the assembler that is doing this calculation (i.e. this doesn't expand into multiple instructions), but rather it is an [addressing mode](https://en.wikipedia.org/wiki/Addressing_mode) encoding in the instruction set architecture/machine code that the processor can interpret. Addressing modes are provided to facilitate common pointer and array operations. The arithmetic done in an addressing mode can be done as separate instructions, but that would probably be longer and slower, and would take a scratch register. Different ISAs provide different addressing modes. – Erik Eidt Nov 07 '19 at 20:05

0 Answers0