2

I've never written any long programs in assembly. But from my superficial experience it appears not as hard as people make it seem like.

The only thing I can't quite wrap my head around is: How does one practically carry out register allocation? While in x86 there is not much space, x64 and RISC designs (AVR, ARM) give you a plenty of registers.

How do assembly programmers choose which variables should stay in the registers, when to transfer them from/to memory and finally, how do they keep track of every variable?

Michał B.
  • 23
  • 2
  • With a few registers, it's not too hard. With a lot of registers, it's a lot more work. This is why people use compilers :) – Greg Hewgill Jul 27 '14 at 20:48
  • It's not so much that it's hard to write long programs in assembly, it's that it's hard to write long programs that are any faster than what a compiler would generate. – Ross Ridge Jul 27 '14 at 22:28

1 Answers1

3

How do assembly programmers choose which variables should stay in the registers

Since registers are (almost always) faster than memory access, variables which are used (read or written) frequently should generally go into registers. An example is the index variable of a loop.

A counterexample is a variable of which you will take the address. That should go into memory since you can't (generally) grab a pointer to a register.

when to transfer them from/to memory

Don't, unless absolutely necessary.

and finally, how do they keep track of every variable?

Hardly. Joke aside, frequent commenting, consistent naming and register allocating conventions, the use of some sort of macro processor (either the assemblers own one or the C preprocessor) and disciplined coding in general make things a little bit easier.

  • Well said. It may help to know that some of us at least practice relentless assembly-code refactoring to get the contents of the registers organized to minimize loads and stores. It helps to have a convention to fall back on as a base line... e.g., use Rn for pointers to structs you are updateing, Rn+1 for structs you are climbing across, etc. Code enough, and you'll develop your own conventions out of habit. – Ira Baxter Jul 27 '14 at 21:20
  • @IraBaxter Exactly, exactly. – The Paramagnetic Croissant Jul 27 '14 at 21:28