25112 Rev. 3.06 September 2005

Software Optimization Guide for AMD64 Processors

5.11Sorting and Padding C and C++ Structures

Optimization

Sort and pad C and C++ structures to achieve natural alignment.

Application

This optimization applies to:

32-bit software

64-bit software

Rationale

By sorting and padding structures at the source-code level, if the first member of a structure is naturally aligned, then all other members are naturally aligned as well. This allows, for example, arrays of structures to be perfectly aligned.

Sorting and Padding C and C++ Structures

To sort and pad a C or C++ structure, follow these steps:

1.Sort the structure members according to their type sizes, declaring members with larger type sizes ahead of members with smaller type sizes.

2.Pad the structure so the size of the structure is a multiple of the largest member’s type size.

Example

Consider the following structure declaration in a C function:

struct { char a[5]; long k; double x;

} baz;

Instead of allocating the members in the order in which they are declared, allocate them from lower to higher addresses in the following order and add padding:

x, k, a[4], a[3], a[2], a[1], a[0], pad_byte6,..., pad_byte0

Chapter 5

Cache and Memory Optimizations

117

Page 133
Image 133
AMD 250 manual Sorting and Padding C and C++ Structures, 117