Who decides the actual storage of the register storage class?

I was recently asked after a Q in an interview: Who actually decides where the register of registers will be stored (in RAM or in a register).

I searched on google and I got this compiler. but how can the compiler decide? This needs to be resolved at runtime as per my understanding.

what if we are compiling and running the program on another machine, whereas the compiler can decide where to store the value of the storage class.

+3


source to share


2 answers


The class register

specifier is a hint for the compiler to access a variable "as quickly as possible", implying (on a register architecture) that its storage should be allocated to a register. This prohibits several things, for example, addressing the address of register variables has no addresses. However, the compiler may ignore this hint (& section; 6.7.1 and para; 5):

Declaring an identifier for an object with a storage class specifier register

suggests that the object should be accessed as quickly as possible. The extent to which such proposals are effective is implementation-defined.

When compiling your code, the compiler must choose how to map local variables and arithmetic operations to operations in CPU registers and the stack. This is called register allocation; these decisions are made at compile time and baked into the compiled function code.

Let's say we have a very naive compiler that does exactly what we say and doesn't optimize anything. If we give it this code:

int x;
x = 2;
x += 5;

      

Then we might expect to see this output on an x86 machine:



sub esp, 4          ; allocate stack space for an integer
mov dword [esp], 2
add dword [esp], 5

      

But if we write:

register int x;
x = 2;
x += 5;

      

Then we can expect to see:

mov eax, 2
add eax, 5

      

The latter is more efficient because it prefers register access via memory accesses. In practice, modern compilers have smart register allocation algorithms that make this storage class specifier unnecessary.

+3


source


During the compilation process, several types of optimizations are generated, and depending on these optimizations, a request is granted or denied.

The third final stage of compilation --- intermediate code generation retains the basis for creating intermediate three-address code (based on the opcode) coding, which is further optimized in the second last phase of the compiler optimization. The last phase of the compiler --- target code generation

allows you to guarantee whether the register store of the class variable will be given a register or not.



The request to grant access to the registry variable is done by the program, but finally it is the compiler that decides the allocation of the memory variable in the register depending on: -

  • Availability of registers in the CPU.

  • More stable optimizations, etc.

+1


source







All Articles