2.4.2. Grouping global variables

Group global variables into structures can potentially enable the compiler to generate efficient direct addressing using the DP and minimize the number of updates to the DP between variable accesses.

Table 2.3 illustrates grouping global variables into fields in a struct.

Table 2.3 Global variables - grouping and efficiency

Global variables

Global variables grouped into a struct

int16_t global0;
int16_t global1;
int16_t global2;
int16_t global3;
int16_t global4;
int16_t global5[32];

int16_t foo()
{
    return global0 + global1 + global2 +
           global3 + global4 + global5[0];
}
typedef struct {
    int16_t global0;
    int16_t global1;
    int16_t global2;
    int16_t global3;
    int16_t global4;
    int16_t global5[32];
} Globals;

Globals g;

int16_t bar()
{
    return g.global0 + g.global1 + g.global2 +
           g.global3 + g.global4 + g.global5[0];
}

Table 2.4 illustrates the improvement in the generated assembly from grouping global variables - there are fewer updates to the DP between accesses - 3 vs. 1 for the 5 accesses.

Table 2.4 Efficiency improvements from grouping global variables into a struct
||foo||:
        MOVW      DP,#||global0||
        MOV       AL,@||global0||
        MOVW      DP,#||global5||
        ADD       AL,@||global5||
        MOVW      DP,#||global1||
        ADD       AL,@||global1||
        ADD       AL,@||global2||
        ADD       AL,@||global3||
        ADD       AL,@||global4||
        LRETR
||bar||:
        MOVW      DP,#||g||+1
        MOV       AL,@||g||+1
        ADD       AL,@||g||
        ADD       AL,@||g||+2
        ADD       AL,@||g||+3
        ADD       AL,@||g||+4
        ADD       AL,@||g||+5
        LRETR

Refer to TMS320C28x Optimizing C/C++ Compiler User’s Guide, Section 3.11, Data Page (DP) Pointer Load Optimization for details.