56d1b2e6743ee763978cebe0068de20abbd4018b
[alexxy/gromacs.git] / src / gromacs / utility / alignedallocator.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2016, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \libinternal \file
36  * \brief
37  * Declares gmx::AlignedAllocator that is used to make standard library
38  * containers compatible with SIMD contents that require aligned load/store.
39  *
40  * \author Erik Lindahl <erik.lindahl@gmail.com>
41  * \inlibraryapi
42  * \ingroup module_utility
43  */
44 #ifndef GMX_UTILITY_ALIGNEDALLOCATOR_H
45 #define GMX_UTILITY_ALIGNEDALLOCATOR_H
46
47 #include <cstddef>
48
49 #include <memory>
50 #include <new>
51
52 #include "gromacs/utility/basedefinitions.h"
53
54 namespace gmx
55 {
56
57 namespace internal
58 {
59
60 /*! \brief Allocate aligned memory
61  *
62  *  \param bytes Amount of memory (bytes) to allocate. It is valid to ask for
63  *               0 bytes, which will return a non-null pointer that is properly
64  *               aligned and padded (but that you should not use).
65  *
66  * \return Valid pointer if the allocation worked, otherwise nullptr.
67  *
68  * The memory will always be aligned to 128 bytes, which is our
69  * estimate of the longest cache lines on architectures currently in use.
70  * It will also be padded by the same amount at the end of the
71  * area, to help avoid false cache sharing.
72  *
73  *  \note Memory allocated with this routine must be released with
74  *        gmx::internal::alignedFree(), and absolutely not the system free().
75  */
76 void *
77 alignedMalloc(std::size_t bytes);
78
79 /*! \brief Free aligned memory
80  *
81  *  \param p  Memory pointer previously returned from gmx::internal::alignedMalloc()
82  *
83  *  \note This routine should only be called with pointers obtained from
84  *        gmx::internal::alignedMalloc(), and absolutely not any pointers obtained
85  *        the system malloc().
86  */
87 void
88 alignedFree(void *p);
89
90 }
91
92 /*! \libinternal \brief Aligned memory allocator.
93  *
94  *  \tparam T          Type of objects to allocate
95  *
96  * This class can be used for the optional allocator template parameter
97  * in standard library containers, which is necessary e.g. to use SIMD
98  * aligned load and store operations in those containers. The memory will always
99  * be aligned to 128 bytes, which is our estimate of the longest cache lines on
100  * architectures currently in use. It will also be padded by the same amount at
101  * the end of the area, to help avoid false cache sharing.
102  *
103  * \throws std::bad_alloc Instead of a GROMACS exception object we throw the
104  * standard one on allocation failures to make it as compatible as possible with
105  * the errors expected by code using the standard library containers.
106  *
107  * \inlibraryapi
108  * \ingroup module_utility
109  */
110 template <class T>
111 class AlignedAllocator
112 {
113     public:
114         // The standard library specification for a custom allocator
115         // requires these typedefs, with this capitalization/underscoring.
116         typedef T              value_type;      //!< Type of allocated elements
117         typedef T             &reference;       //!< Reference to allocated elements
118         typedef const T       &const_reference; //!< Constant reference to allocated elements
119         typedef T *            pointer;         //!< Pointer to allocated elements
120         typedef const T *      const_pointer;   //!< Constant pointer to allocated elements
121         typedef std::size_t    size_type;       //!< Integer type to use for size of objects
122         typedef std::ptrdiff_t difference_type; //!< Type to hold differences between pointers
123
124         /*! \libinternal \brief Standard-required typedef to use allocator with different class.
125          *
126          *  \tparam U new class
127          *
128          *  This is used for things like std::list where the size of each link
129          *  is larger than the class stored in the link.
130          *
131          *  Required by the specification for an allocator.
132          */
133         template <class U>
134         struct rebind
135         {
136             typedef AlignedAllocator<U> other; //!< Align class U with our alignment
137         };
138
139         /*! \brief Templated copy constructor
140          *
141          * This template constructor cannot be auto-generated, and is
142          * normally unused, except e.g. MSVC2015 standard library uses
143          * it in debug mode, presumably to implement some checks.
144          */
145         template <class U>
146         explicit AlignedAllocator(const AlignedAllocator<U> &) {}
147
148         /*! \brief Constructor
149          *
150          * No constructor can be auto-generated in the presence of any
151          * user-defined constructor, but we want the default constructor.
152          */
153         AlignedAllocator() {};
154
155         /*! \brief Return address of an object
156          *
157          *  \param r Reference to object of type T
158          *  \return Pointer to T memory
159          */
160         pointer
161         address(reference r) const { return &r; }
162
163         /*! \brief Return address of a const object
164          *
165          *  \param r Const reference to object of type T
166          *  \return Pointer to T memory
167          */
168         const_pointer
169         address(const_reference r) const { return &r; }
170
171         /*! \brief Do the actual memory allocation
172          *
173          *  \param n    Number of elements of type T to allocate. n can be
174          *              0 bytes, which will return a non-null properly aligned
175          *              and padded pointer that should not be used.
176          *  \param hint Optional value returned from previous call to allocate.
177          *              For now this is not used.
178          *  \return Pointer to allocated memory
179          *
180          *  \throws std::bad_alloc if the allocation fails.
181          */
182         pointer
183         allocate(std::size_t n, typename std::allocator<void>::const_pointer gmx_unused hint = 0)
184         {
185             void *p = internal::alignedMalloc(n*sizeof(T));
186
187             if (p == nullptr)
188             {
189                 throw std::bad_alloc();
190             }
191             else
192             {
193                 return static_cast<pointer>(p);
194             }
195         }
196
197         /*! \brief Release memory
198          *
199          * \param p  Pointer to previously allocated memory returned from allocate()
200          * \param n  number of objects previously passed to allocate()
201          */
202         void
203         deallocate(pointer p, std::size_t gmx_unused n)
204         {
205             internal::alignedFree(p);
206         }
207
208         /*! \brief Construct an object without allocating memory
209          *
210          * \tparam Args  Variable-length list of types for constructor args
211          * \param p      Adress of memory where to construct object
212          * \param args   Variable-length list of arguments to constructor
213          */
214         template<class ... Args>
215         void
216         construct(pointer p, Args && ... args) { ::new((void *)p)T(std::forward<Args>(args) ...); }
217
218         /*! \brief Call the destructor of object without releasing memory
219          *
220          * \param p  Address of memory where to destroy object
221          */
222         void
223         destroy(pointer p) { p->~value_type(); }
224
225         /*! \brief Return largest number of objects that can be allocated
226          *
227          * This will be set such that the number of objects T multiplied by
228          * the size of each object is the largest value that can be represented
229          * by size_type.
230          */
231         std::size_t
232         max_size() const { return (static_cast<size_t>(0) - static_cast<size_t>(1)) / sizeof(T); }
233
234         /*! \brief Return true if two allocators are identical
235          *
236          * \param rhs Other allocator
237          *
238          * This is a member function of the left-hand-side allocator.
239          */
240         template<class T2>
241         bool
242         operator==(const AlignedAllocator<T2> &gmx_unused rhs) const { return std::is_same<T, T2>::value; GMX_UNUSED_VALUE(rhs); }
243
244         /*! \brief Return true if two allocators are different
245          *
246          * \param rhs Other allocator.
247          *
248          * This is a member function of the left-hand-side allocator.
249          */
250         bool
251         operator!=(const AlignedAllocator &rhs) const { return !operator==(rhs); }
252 };
253
254 }      // namespace gmx
255
256 #endif // GMX_UTILITY_ALIGNEDALLOCATOR_H