Hacker News new | ask | show | jobs
by moefh 1238 days ago
Compilers do it all the time, for example GCC compiles "x*4 + y" to a single LEA instruction: https://godbolt.org/z/TvdW5sK4b
1 comments

Aha, playing with it, it looks like the multiply is just a shift because if you try to do anything other than powers of two it has to break it down into more instructions.

Still clever, though. I guess it's to make it easier and quicker to index over words or multiples of words?

The addressing logic on the 80386+ can add an index shifted left by 0..3 bits (unscaled, x2, x4, x8) with a base register plus an immediate offset.

By using the same register for base and index you can also multiply one register by 3, 5 or 9.

Earlier (16 bit) x86 chips did not have the scaling feature and were limited to certain combinations of base and index (BX/BP as base, SI/DI as index), so LEA was less useful. If the registers are carefully assigned, it could still be used to do an addition and put the result into another register. Normal ALU operations always use one of the operands as their destination.