eef90632b6b68bc99c925eccf3888124b6438d3c
[gnulib.git] / tests / test-stdalign.c
1 /* Test of <stdalign.h>.
2    Copyright 2009-2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Paul Eggert, inspired by Bruno Haible's test-alignof.c.  */
18
19 #include <config.h>
20
21 #include <stdalign.h>
22
23 #include <stddef.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26
27 #include "verify.h"
28
29 typedef long double longdouble;
30 typedef struct { char a[1]; } struct1;
31 typedef struct { char a[2]; } struct2;
32 typedef struct { char a[3]; } struct3;
33 typedef struct { char a[4]; } struct4;
34
35 verify (__alignof_is_defined == 1);
36 #ifndef alignof
37 # error "alignof is not a macro"
38 #endif
39
40 #if __alignas_is_defined
41 verify (__alignas_is_defined == 1);
42 # ifndef alignas
43 #  error "alignas is not a macro"
44 # endif
45 # define DECLARE_ALIGNED(type, name) \
46     type alignas (1 << 3) name##_alignas; \
47     type _Alignas (1 << 3) name##_Alignas;
48 # define CHECK_ALIGNED(name) \
49     (((uintptr_t) &name##_alignas % (1 << 3) ? abort () : (void) 0), \
50      ((uintptr_t) &name##_Alignas % (1 << 3) ? abort () : (void) 0))
51 #else
52 # define DECLARE_ALIGNED(type, name)
53 # define CHECK_ALIGNED(name) ((void) 0)
54 #endif
55
56 #define CHECK_STATIC(type) \
57   typedef struct { char slot1; type slot2; } type##_helper; \
58   verify (alignof (type) == offsetof (type##_helper, slot2)); \
59   verify (_Alignof (type) == alignof (type)); \
60   const int type##_alignment = alignof (type); \
61   DECLARE_ALIGNED(type, static_##type)
62
63 #define CHECK_AUTO(type) \
64   { \
65     DECLARE_ALIGNED(type, auto_##type) \
66     CHECK_ALIGNED(static_##type); \
67     CHECK_ALIGNED(auto_##type); \
68   }
69
70 #ifdef INT64_MAX
71 # define if_INT64_MAX(x) x
72 #else
73 # define if_INT64_MAX(x)
74 #endif
75
76 #define CHECK_TYPES(check) \
77   check (char) \
78   check (short) \
79   check (int) \
80   check (long) \
81   if_INT64_MAX (check (int64_t)) \
82   check (float) \
83   check (double) \
84   check (longdouble) \
85   check (struct1) \
86   check (struct2) \
87   check (struct3) \
88   check (struct4)
89
90 CHECK_TYPES (CHECK_STATIC)
91
92 int
93 main ()
94 {
95   CHECK_TYPES (CHECK_AUTO)
96   return 0;
97 }