Search code examples
assemblyx86cpu-registersaccumulator

Does it matter which registers you use when writing assembly?


If you're writing assembly, does it matter which registers you allocate values to? Say, you store an accumulated/intermediate value in %ebx instead of %eax, which was traditionally used for that purpose. Is that bad practice? Will it affect performance?

In other words, can you treat them equally as storage space, or should you stick to using them for specific purposes?


Solution

  • First and foremost, you have to use registers that support the instructions you want to use.  Many instructions on x86 (and other architectures, though less so) have some restrictions on how registers are supported.

    Take certain double register multiply and divide instructions, for example, which specifically involve eax and edx in particular uses.

    Next, you want to use registers that are efficient, i.e. registers:

    • for which encodings are shorter (here is a good discussion on x64 around instruction length).  Short encodings make better usage of cache resources, which can allow larger programs to run more efficiently.

    • that are un-encumbered, i.e. due to the calling conventions, which is to say they don't incur extra (software/calling-convention defined) overhead for their usage — unless that overhead has already been paid!

    • that are the eventual destinations of the values being produced: e.g. if the second parameter, then the register that corresponds to the second value to be passed (again according to the calling convention).  If we can place the value in the right register (as needed for passing or returning values), then we can forgo a data move (aka copy) instruction.