Search code examples
c++carmembeddedcross-compiling

Compiler Baremetal (arm-none-eabi) - Compiler Implementation


It is common practice to declare stack variables (variables allocated on the excecuting stack rather than dynamically or statically) at the entrypoint of the function rather than mixed with instructions inside the function. See Example 1.a and 1.b. This helps with a better readability and was with older language even required.

With modern C/C++ it is no longer required (..but still good practice).

My Question though: How does the compiler solve it if stack variables are inside a function rather than at the entry point. See Examples 2.a and 2.b how i can imagine he solves it. What is ACTUALLY HAPPENING?

1.a) Example (Common Practice / Best Practice)

void main()
{
    int a = 3;      // best practice
    bool c = false; // best practice

    a += 16;

    if(a == 5)
    {
        c=false;
    }
}

...rather than ...

1.b) Example (Uncommon)

void main()
{
    int a = 3;
    a += 16;

    bool c = false; // variable after some instructions executed..
    if(a == 5)
    {
        c=false;
    }
}

2.a) Possible compiler solution (A)

void main()
{
    int a = 3;
    a += 16;

    bool c = false; // COMPILER CUTS THIS LINE AND MOVES IT UP UNDER "int a = 3;"
    if(a == 5)
    {
        c=false;
    }
}

2.B) Possible compiler solution (B)

void main()
{
    int a = 3;
    a += 16;

    { // COMPILER ADDS SUBSECTION IN ORDER TO INTRODUCE NEW VARIABLES ON STACK
        bool c = false; 
        if(a == 5)
        {
            c=false;
        }
    }
}

Solution

  • When, how and where the compiler instantiates or allocates such variables is entirely implementation dependent. It may create a stack frame for all variables at the start of the function, or it may extend the stack frame at the point of declaration, or it may not use the stack at all and use register storage instead.

    The language only requires that the correct semantics are implemented; that the variable is not in scope (i.e. cannot be referenced by code) before it is declared, and that the scope ends after the closing } of the block in which it was declared.