In an IR we can use as many virtual registers as we like. A real CPU has a fixed number; x86-64 has 16 general-purpose registers. Register allocation maps virtual registers onto those few physical ones.
The Interference Graph
Two values that are live at the same time cannot share a register. This is drawn as a graph: each value is a node, and values live at the same time are connected by an edge.
Here a and b interfere, but c and a do not, so c can reuse the register of a. Two registers are enough for this function.
When Colors Run Out
If the graph cannot be colored with as many colors as there are registers, some values are moved to memory. This is called a spill. Which value gets spilled matters: pushing a value that is used often inside a loop out to memory slows the program noticeably.
Between Fast and Good
- Graph coloring gives good results but can get slow on large functions.
- Linear scan is faster and is a common choice in just-in-time compilers.
- LLVM, for example, uses its Fast allocator for debug builds and the more thorough Greedy allocator by default.
Function calls affect allocation too: the calling convention says which registers survive a call and which may be clobbered.
Sources
- G. J. Chaitin. “Register allocation & spilling via graph coloring.” ACM SIGPLAN Notices 17(6), 1982, 98–101. doi:10.1145/872726.806984
- M. Poletto, V. Sarkar. “Linear scan register allocation.” ACM TOPLAS 21(5), 1999, 895–913. doi:10.1145/330249.330250
- The LLVM Target-Independent Code Generator, “Built in register allocators”. llvm.org/docs/CodeGenerator
- System V Application Binary Interface, AMD64 Architecture Processor Supplement. gitlab.com/x86-psABIs