AMD 250 Computer Hardware User Manual


 
Chapter 2 C and C++ Source-Level Optimizations 39
Software Optimization Guide for AMD64 Processors
25112 Rev. 3.06 September 2005
2.18 Sorting 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
In order to achieve better alignment for structures, many compilers have options that allow padding of
structures to make their sizes multiples of words, doublewords, or quadwords. In addition, to improve
the alignment of structure members, some compilers might allocate structure elements in an order that
differs from the order in which they are declared. However, some compilers might not offer any of
these features, or their implementations might not work properly in all situations.
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.
Examples
Avoid structure declarations in which the members are not declared in order of their type sizes and the
size of the structure is not a multiple of the size of the largest member’s type:
struct {
char a[5]; \\ Smallest type size (1 byte * 5)
long k; \\ 4 bytes in this example
double x; \\ Largest type size (8 bytes)
} baz;