• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. _module-pw_alignment:
2
3============
4pw_alignment
5============
6This module defines an interface for ensuring natural alignment of objects.
7
8Avoiding Atomic Libcalls
9========================
10The main motivation is to provide a portable way for
11preventing the compiler from emitting libcalls to builtin atomics
12functions and instead use native atomic instructions. This is especially
13useful for any pigweed user that uses ``std::atomic``.
14
15Take for example `std::atomic<std::optional<bool>>`. Accessing the underlying object
16would normally involve a call to a builtin `__atomic_*` function provided by a builtins
17library. However, if the compiler can determine that the size of the object is the same
18as its alignment, then it can replace a libcall to `__atomic_*` with native instructions.
19
20There can be certain situations where a compiler might not be able to assert this.
21Depending on the implementation of `std::optional<bool>`, this object could
22have a size of 2 bytes but an alignment of 1 byte which wouldn't satisfy the constraint.
23
24Basic usage
25-----------
26`pw_alignment` provides a wrapper class `pw::NaturallyAligned` for enforcing natural alignment without any
27changes to how the object is used. Since this is commonly used with atomics, an
28aditional class `pw::AlignedAtomic` is provided for simplifying things.
29
30.. code-block:: c++
31
32   // Passing a `std::optional<bool>` to `__atomic_exchange` might not replace the call
33   // with native instructions if the compiler cannot determine all instances of this object
34   // will happen to be aligned.
35   std::atomic<std::optional<bool>> maybe_nat_aligned_obj;
36
37   // `pw::NaturallyAligned<...>` forces the object to be aligned to its size, so passing
38   // it to `__atomic_exchange` will result in a replacement with native instructions.
39   std::atomic<pw::NaturallyAligned<std::optional<bool>>> nat_aligned_obj;
40
41   // Shorter spelling for the same as above.
42   std::AlignedAtomic<std::optional<bool>> also_nat_aligned_obj;
43