Skip to content

Instantly share code, notes, and snippets.

@grooverdan
Created April 14, 2016 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grooverdan/19a7c8d8ac0e680ba6fcf4668962b9c4 to your computer and use it in GitHub Desktop.
Save grooverdan/19a7c8d8ac0e680ba6fcf4668962b9c4 to your computer and use it in GitHub Desktop.
/* from include/my_compiler.h */
#if defined __GNUC__ || defined __SUNPRO_C || defined __SUNPRO_CC
/* Specifies the minimum alignment of a type. */
# define MY_ALIGNOF(type) __alignof__(type)
/* Determine the alignment requirement of a type. */
# define MY_ALIGNED(n) __attribute__((__aligned__((n))))
/* Microsoft Visual C++ */
#elif defined _MSC_VER
# define MY_ALIGNOF(type) __alignof(type)
# define MY_ALIGNED(n) __declspec(align(n))
#else /* Make sure they are defined for other compilers. */
# define MY_ALIGNOF(type)
# define MY_ALIGNED(size)
#endif
#ifndef CPU_LEVEL1_DCACHE_LINESIZE
#if defined(__s390__)
#define CPU_LEVEL1_DCACHE_LINESIZE 256
#elif defined(__powerpc__) || defined(__aarch64__)
#define CPU_LEVEL1_DCACHE_LINESIZE 128
#else
#define CPU_LEVEL1_DCACHE_LINESIZE 64
#endif
#endif
struct s_one {
char first[30] MY_ALIGNED(CPU_LEVEL1_DCACHE_LINESIZE);
};
struct s_multiple {
char first[30] MY_ALIGNED(CPU_LEVEL1_DCACHE_LINESIZE);
unsigned long two;
char three[30];
char four[40] MY_ALIGNED(CPU_LEVEL1_DCACHE_LINESIZE);
};
struct s_one one_arr[2];
struct s_multiple multiple_arr[2];
struct s_simple {
char first[30];
};
struct s_simple simple_arr[2];
#include <stdio.h>
#include <stddef.h>
int main()
{
printf("Alignment %x\n\n", CPU_LEVEL1_DCACHE_LINESIZE);
printf("sizeof(one) %zx\n", sizeof(struct s_one));
printf("one[0] %p\n", &one_arr[0].first);
printf("one[1] %p\n", &one_arr[1].first);
printf("one ptrdiff %tx\n", (ptrdiff_t) (&one_arr[1].first - &one_arr[0].first));
printf("\nsizeof(multiple) %zx\n", sizeof(struct s_multiple));
printf("multiple[0].first %p\n", &multiple_arr[0].first);
printf("multiple[0].four %p\n", &multiple_arr[0].four);
printf("multiple[1].first %p\n", &multiple_arr[1].first);
printf("multiple diff %tx\n", (ptrdiff_t) (&multiple_arr[1].first - &multiple_arr[0].first));
printf("\nsimple diff %tx\n", (ptrdiff_t) (&simple_arr[1].first - &simple_arr[0].first));
}
X86_64
uname -m ; gcc -o align-test align-test.c && ./align-test
x86_64
Alignment 40
sizeof(one) 40
one[0] 0x601240
one[1] 0x601280
one ptrdiff 2
sizeof(multiple) c0
multiple[0].first 0x6010c0
multiple[0].four 0x601140
multiple[1].first 0x601180
multiple diff 6
simple diff 1
Power:
uname -m ; gcc -o align-test align-test.c && ./align-test
ppc64le
Alignment 80
sizeof(one) 80
one[0] 0x10020480
one[1] 0x10020500
one ptrdiff 4
sizeof(multiple) 100
multiple[0].first 0x10020280
multiple[0].four 0x10020300
multiple[1].first 0x10020380
multiple diff 8
simple diff 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment