Debian Codegraph @

mfbt/Alignment.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /* Functionality related to memory alignment. */
8
9 #ifndef mozilla_Alignment_h
10 #define mozilla_Alignment_h
11
12 #include "mozilla/Attributes.h"
13 #include <stddef.h>
14 #include <stdint.h>
15
16 namespace mozilla {
17
18 /*
19 * Declare the MOZ_ALIGNED_DECL macro for declaring aligned types.
20 *
21 * For instance,
22 *
23 * MOZ_ALIGNED_DECL(8, char arr[2]);
24 *
25 * will declare a two-character array |arr| aligned to 8 bytes.
26 */
27
28 #if defined(__GNUC__)
29 # define MOZ_ALIGNED_DECL(_align, _type) _type __attribute__((aligned(_align)))
30 #elif defined(_MSC_VER)
31 # define MOZ_ALIGNED_DECL(_align, _type) __declspec(align(_align)) _type
32 #else
33 # warning "We don't know how to align variables on this compiler."
34 # define MOZ_ALIGNED_DECL(_align, _type) _type
35 #endif
36
37 /*
38 * AlignedElem<N> is a structure whose alignment is guaranteed to be at least N
39 * bytes.
40 *
41 * We support 1, 2, 4, 8, and 16-byte alignment.
42 */
43 template <size_t Align>
44 struct AlignedElem;
45
46 /*
47 * We have to specialize this template because GCC doesn't like
48 * __attribute__((aligned(foo))) where foo is a template parameter.
49 */
50
51 template <>
52 struct AlignedElem<1> {
53 MOZ_ALIGNED_DECL(1, uint8_t elem);
54 };
55
56 template <>
57 struct AlignedElem<2> {
58 MOZ_ALIGNED_DECL(2, uint8_t elem);
59 };
60
61 template <>
62 struct AlignedElem<4> {
63 MOZ_ALIGNED_DECL(4, uint8_t elem);
64 };
65
66 template <>
67 struct AlignedElem<8> {
68 MOZ_ALIGNED_DECL(8, uint8_t elem);
69 };
70
71 template <>
72 struct AlignedElem<16> {
73 MOZ_ALIGNED_DECL(16, uint8_t elem);
74 };
75
76 template <typename T>
77 struct MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS AlignedStorage2 {
78 union U {
79 char mBytes[sizeof(T)];
80 uint64_t mDummy;
81 } u;
82
83 const T* addr() const { return reinterpret_cast<const T*>(u.mBytes); }
84 T* addr() { return static_cast<T*>(static_cast<void*>(u.mBytes)); }
85
86 AlignedStorage2() = default;
87
88 // AlignedStorage2 is non-copyable: the default copy constructor violates
89 // strict aliasing rules, per bug 1269319.
90 AlignedStorage2(const AlignedStorage2&) = delete;
91 void operator=(const AlignedStorage2&) = delete;
92 };
93
94 } /* namespace mozilla */
95
96 #endif /* mozilla_Alignment_h */