#align directive

The #align directive is used to align struct member fields relative to the start of the struct. If you have a member field that is #align 64, and the base of the struct is also aligned 64, then the member field will also be aligned 64. If you make a member field #align 32, the member field will be aligned 32, and #align 16 will make a member field aligned 16. This directive is useful if you are working with cache-sensitive data structures that required alignment in a particular way.

If the base of the struct is not aligned correctly, the struct member will not align correctly since the base of the struct is not aligned correctly. #align assumes that the base of the struct is aligned correctly.

Here is an example of how to use the #align directive:

Accumulator :: struct {
  // make the 'accumulation' variable 64-bit cache-aligned
  accumulation: [2][256] s16 #align 64;
  computedAccumulation: s32;

#align x cannot be applied directly to a struct. If you want to align an array of structs to the appropriate alignment, add appropriate padding to pad the struct to the desired alignment. For example, in the following code:

Object :: struct {member: int} #align 64 // This has NO effect on the struct.

This will compile, but #align will have no effect on the code.

A global variable can be made cache aligned by applying the #align 64 directive, just like aligning object member fields.

global_var: [100] int #align 64; // makes the global variable 64-bit cache aligned

assert(cast(int)(*global_var) % 64 == 0); 

To align the base of the struct to a particular alignment, you can change the alignment parameter on the New heap allocation function so that the struct can have the appropriate alignment. Aligning a struct on the stack is currently not supported, but this will eventually be supported.

// perform heap allocation that is 64-bit aligned
object := New(Object, alignment=64);
1 Like