2.4.3. Local variables

Local variables in a function are placed on the stack. The compiler uses the SP register to access these local variables. The stack frame for a function consists of local variables and other compiler generated data. For frames that exceed 63 words in size (the maximum reach of the SP offset addressing mode), the compiler uses XAR2 as a frame pointer (FP).

To take advantage of SP-relative addressing, keep the local frame less than 64 words. Table 2.5 illustrates the impact of stack frame size on the efficiency of generated code. The only difference between the two code snippets is that in the example on the left, the stack frame is larger than 64 words. In this example, volatile is used to ensure the compiler reads the local variables a and b from memory vs. allocating them to registers

Table 2.5 Stack frame size and efficiency of generated code

Stack frame >= 64 words

Stack frame < 64 words

int16_t local_variables1()
{
    volatile int16_t a;
    int16_t array[64];
    volatile int16_t b;

    a = 42;
    b = 44;
    update(array, 64);

    return a + b;
}
int16_t local_variables2()
{
    volatile int16_t a;
    int16_t array[32];
    volatile int16_t b;

    a = 42;
    b = 44;
    update(array, 32);

    return a + b;
}

Table 2.6 illustrated how the compiler is able to use the more efficient SP-relative addressing when the frame size is < 64 words.

Table 2.6 Structure size and efficiency of generated code

Frame size >= 64 requires use of FP (AR2)

Frame size < 64 uses SP relative addressing

||local_variables1||:
            MOVL      *SP++,XAR1
            MOVL      *SP++,XAR2
            MOVZ      AR2,SP
            SUBB      FP,#6
            ADDB      SP,#66
            MOVZ      AR4,SP
            MOVB      *+FP[7],#42,UNC
            MOVB      AL,#64
            SUBB      XAR4,#64
            MOVB      *+FP[6],#44,UNC
            MOVZ      AR4,AR4
            LCR       #||update||

            MOV       AL,*+FP[6]
            ADD       AL,*+FP[7]
            SUBB      SP,#66
            MOVL      XAR2,*--SP
            MOVL      XAR1,*--SP
            LRETR
||local_variables2||:
        ADDB      SP,#34
        MOVZ      AR4,SP
        MOVB      *-SP[33],#42,UNC
        MOVB      AL,#32
        SUBB      XAR4,#32
        MOVB      *-SP[34],#44,UNC
        MOVZ      AR4,AR4
        LCR       #||update||

        MOV       AL,*-SP[34]
        ADD       AL,*-SP[33]
        SUBB      SP,#34
        LRETR