Open In App

Register Allocation Algorithms in Compiler Design

Register allocation is an important method in the final phase of the compiler . Registers are faster to access than cache memory . Registers are available in small size up to few  hundred Kb .Thus it is necessary to use minimum number of registers for variable allocation . There are three popular Register allocation algorithms .

  1. Naive Register Allocation
  2. Linear Scan Algorithm
  3. Chaitin’s Algorithm

These are explained as following below.



1. Naïve Register Allocation :

a = b + c
d = a
c = a + d

Variables stored in Main Memory :



a b c d
2 fp 4 fp 6 fp 8 fp

Machine  Level Instructions :

LOAD  R1, _4fp
LOAD  R2, _6fp
ADD   R1, R2 
STORE R1, _2fp
LOAD  R1, _2fp
STORE R1, _8fp
LOAD  R1, _2fp
LOAD  R2, _8fp
ADD   R1, R2
STORE R1, _6fp

Advantages :

Disadvantages :

2. Linear Scan Algorithm :

a = b + c
d = e + f
d = d + e
IFZ a goto L0
b = a + d
goto L1
L0 : b = a - d 
L1 : i = b

Control Flow Graph :

   

If we draw horizontal line at any point on the above diagram we can see that we require exactly 4 registers to perform the operations in the program .

Splitting :

Disadvantages :

3.Graph Coloring (Chaitin’s Algorithm) :

A k-coloring of the graph is mapped to k registers .

Steps :

  1. Choose an arbitrary node of degree less than k .
  2. Push that node onto the stack and remove all of it’s outgoing edges .
  3. Check if the remaining edges have degree less than k, if YES goto  5 else goto #
  4. If the degree of any remaining vertex is less than k then push it onto to the stack .
  5. If there is no more edge available to push and if all edges are present in the stack POP each node and color them such that no two adjacent nodes have same color.
  6. Number of colors assigned to nodes is the minimum number of registers needed .

# spill some nodes based on their live ranges and then try again with same k value . If problem persists it means that the assumed  k value can’t be the minimum number of registers .Try increasing the k value by 1 and try the whole procedure again .

For the same instructions mentioned above the graph coloring will be as follows :

Assuming k=4 

before coloring

After performing the graph coloring, final graph is obtained as follows 

final graph with k(4) colors

Note : Any color(register) can be assigned to ‘i’ as  it has no edge to any other nodes .

Article Tags :