tags:

views:

91

answers:

4

Declaring a variable register is a suggestion to the compiler that particular automatic variable should be allocated to CPU register, if possible.

But how the compiler decides when to put the register variable to CPU register? Which algorithm/mechanism it uses to decide?

Thanks,

Naveen

+4  A: 

In case Norman Ramsey doesn't notice this and answer, perhaps a pointer to one of his papers would be in order.

Graph coloring is used primarily in static compilers (aka ahead of time compilers). For dynamic (Just In Time) compilers, you generally use something that gives results faster (e.g., a linear scan algorithm), even though it generally won't do as good of a job of register allocation.

Jerry Coffin
+1  A: 

As Jerry says, the compiler uses a register allocator. Register allocation is one of those simply defined, but hard, problems.

In the olden days, the compiler appreciated your help in solving the problem of which variables to put into registers and when. But today, the task is better understood and the compiler is too busy with program analysis to actually listen to what you have to say.

Unless optimization is completely turned off, your compiler will most likely ignore the register specifier.

Potatoswatter
@Potatoswatter: have you seen a (reasonably) recent compiler that paid attention to `register` with optimization turned off completely? Don't get me wrong. I'm not trying to argue the point; it's just something I haven't looked at (recently).
Jerry Coffin
@Jerry: GCC supports this for some reason.
Potatoswatter
@Potatoswatter: thanks for the info -- I hadn't noticed that.
Jerry Coffin
A: 

Apart from the ones mentioned, GCC(4.5.x+) uses a SSA-Tree based register allocator (more detail in the Passes section), though here is a good sample of SSA register allocation

Necrolis
SSA (either tree or DAG) is the class of language including most compiler IRs. So most graph coloring allocators will also be SSA. (I tried to configure/adapt that LLVM register allocator for a school project years ago… it was definitely "academic" code back then :vP .)
Potatoswatter
A: 

You can specify a register keyword for a variable. But its upto the compiler to determine whether to put it into the register or not. Usually in static compilation graph coloring is used which produces efficient allocation. Whereas in dynamic (JIT) compilation a method called linear-scan allocation is preferred since graph coloring takes more time.
Directed Acyclic Graphs (DAGs) can be used to produce optimal instruction sequences (or minimum register allocation sequence).
For more thorough reading see: 1.Towards a More Principled Compiler:Register Allocation and Instruction Selection Revisited by David Ryan Koes
2. Principles of Compiler Design by Alfred V Aho

jase21