| 1 | // { dg-do run { target c++20 } } |
| 2 | // { dg-require-atomic-cmpxchg-word "" } |
| 3 | // { dg-add-options libatomic } |
| 4 | |
| 5 | #include <atomic> |
| 6 | |
| 7 | #include <testsuite_hooks.h> |
| 8 | |
| 9 | struct S |
| 10 | { |
| 11 | char c; |
| 12 | alignas(2) short s; |
| 13 | }; |
| 14 | |
| 15 | void __attribute__((noinline,noipa)) |
| 16 | set_padding(S& s, unsigned char x) |
| 17 | { reinterpret_cast<unsigned char*>(&s)[1] = x; } |
| 18 | |
| 19 | unsigned char __attribute__((noinline,noipa)) |
| 20 | get_padding(S& s) |
| 21 | { return reinterpret_cast<unsigned char*>(&s)[1]; } |
| 22 | |
| 23 | void |
| 24 | test01() |
| 25 | { |
| 26 | S s; |
| 27 | S ss; |
| 28 | ss.c = 'a'; |
| 29 | ss.s = 42; |
| 30 | set_padding(ss, 0xff); |
| 31 | |
| 32 | { |
| 33 | std::atomic_ref<S> as{ s }; |
| 34 | as.store(ss); // copy value bits, clear padding bits |
| 35 | } |
| 36 | VERIFY( get_padding(s) == 0 ); // padding was cleared on store |
| 37 | |
| 38 | ss.c = 'b'; |
| 39 | set_padding(ss, 0x11); |
| 40 | VERIFY( get_padding(ss) == 0x11 ); |
| 41 | { |
| 42 | std::atomic_ref<S> as{ s }; |
| 43 | as.exchange(ss); // copy value bits, clear padding bits |
| 44 | } |
| 45 | VERIFY( get_padding(s) == 0 ); // padding was cleared on store |
| 46 | |
| 47 | S exp = s; |
| 48 | set_padding(exp, 0xaa); |
| 49 | set_padding(s, 0xbb); |
| 50 | S n; |
| 51 | n.c = 'c'; |
| 52 | n.s = 71; |
| 53 | set_padding(n, 0xcc); |
| 54 | |
| 55 | // padding cleared on cmpexchg |
| 56 | { |
| 57 | std::atomic_ref<S> as{ s }; |
| 58 | // This assumes no spurious failures, hopefully true without contention. |
| 59 | VERIFY( as.compare_exchange_weak(exp, n) ); // padding in exp ignored |
| 60 | } |
| 61 | VERIFY( get_padding(s) == 0 ); // padding in n was not copied to s |
| 62 | |
| 63 | { |
| 64 | std::atomic_ref<S> as{ s }; |
| 65 | VERIFY( as.compare_exchange_strong(n, exp) ); // padding in n ignored |
| 66 | } |
| 67 | VERIFY( get_padding(s) == 0 ); // padding in exp was not copied to s |
| 68 | } |
| 69 | |
| 70 | int main() |
| 71 | { |
| 72 | test01(); |
| 73 | } |