Remove meta information from host allocator policy
[alexxy/gromacs.git] / src / gromacs / utility / allocator.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2017,2018, 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 /*! \file
36  * \brief
37  * Declares gmx::Allocator template whose allocation functionality is
38  * configured both by type of object allocated and a policy class that
39  * configures the necessary matching malloc and free operation.
40  *
41  * \author Erik Lindahl <erik.lindahl@gmail.com>
42  * \author Mark Abraham <mark.j.abraham@gmail.com>
43  * \inpublicapi
44  * \ingroup module_utility
45  */
46 #ifndef GMX_UTILITY_ALLOCATOR_H
47 #define GMX_UTILITY_ALLOCATOR_H
48
49 #include <cstddef>
50
51 #include <memory>
52 #include <new>
53
54 #include "gromacs/utility/basedefinitions.h"
55
56 namespace gmx
57 {
58
59 /*! \libinternal \brief Policy-based memory allocator.
60  *
61  *  \tparam T                 Type of objects to allocate
62  *  \tparam AllocationPolicy  Policy of (matching) allocation and deallocation functions.
63  *
64  * This class can be used for the optional allocator template
65  * parameter in standard library containers. It must be configured
66  * with both the type of object to allocate, and an AllocationPolicy
67  * which effectively wraps a matching pair of malloc and free
68  * functions. This permits implementing a family of related allocators
69  * e.g. with SIMD alignment, GPU host-side page locking, or perhaps
70  * both, in a way that preserves a common programming interface and
71  * duplicates minimal code.
72  *
73  * AllocationPolicy is used as a base class, so that if
74  * AllocationPolicy is stateless, then the empty base optimization
75  * will ensure that Allocation is also stateless, and objects made
76  * with the Allocator will incur no size penalty. (Embedding an
77  * AllocationPolicy object incurs a size penalty always, even if the
78  * object is empty.) Normally a stateless allocator will be used.
79  *
80  * However, an AllocationPolicy with state might be desirable for
81  * simplifying writing code that needs to allocate suitably for a
82  * transfer to a GPU. That code needs to specify an Allocator that can
83  * do the right job, which can be stateless. However, if we have code
84  * that will not know until run time whether a GPU transfer will
85  * occur, then the allocator needs to be aware of the state.  That
86  * will increase the size of a container that uses the stateful
87  * allocator.
88  *
89  * \throws std::bad_alloc Instead of a GROMACS exception object, we
90  * throw the standard one on allocation failures to make it as
91  * compatible as possible with the errors expected by code using the
92  * standard library containers.
93  *
94  * \inlibraryapi
95  * \ingroup module_utility
96  */
97 template <class T, typename AllocationPolicy>
98 class Allocator : public AllocationPolicy
99 {
100     public:
101         // The standard library specification for a custom allocator
102         // requires these typedefs, with this capitalization/underscoring.
103         typedef T              value_type;      //!< Type of allocated elements
104         typedef T             &reference;       //!< Reference to allocated elements
105         typedef const T       &const_reference; //!< Constant reference to allocated elements
106         typedef T *            pointer;         //!< Pointer to allocated elements
107         typedef const T *      const_pointer;   //!< Constant pointer to allocated elements
108         typedef std::size_t    size_type;       //!< Integer type to use for size of objects
109         typedef std::ptrdiff_t difference_type; //!< Type to hold differences between pointers
110
111         // This typedef is required by GROMACS for testing and assertions
112         typedef AllocationPolicy allocation_policy; //!< Type of the AllocationPolicy
113
114         /*! \libinternal \brief Standard-required typedef to use allocator with different class.
115          *
116          *  \tparam U new class
117          *
118          *  This is used for things like std::list where the size of each link
119          *  is larger than the class stored in the link.
120          *
121          *  Required by the specification for an allocator.
122          */
123         template <class U>
124         struct rebind
125         {
126             typedef Allocator<U, AllocationPolicy> other; //!< Align class U with our alignment
127         };
128
129         /*! \brief Constructor
130          *
131          * No constructor can be auto-generated in the presence of any
132          * user-defined constructor, but we want the default constructor.
133          */
134         Allocator() = default;
135
136         /*! \brief Constructor to accept an AllocationPolicy.
137          *
138          * This is useful for AllocationPolicies with state.
139          */
140         Allocator(const AllocationPolicy &p) : AllocationPolicy(p) {}
141
142         /*! \brief Return address of an object
143          *
144          *  \param r Reference to object of type T
145          *  \return Pointer to T memory
146          */
147         pointer
148         address(reference r) const { return &r; }
149
150         /*! \brief Return address of a const object
151          *
152          *  \param r Const reference to object of type T
153          *  \return Pointer to T memory
154          */
155         const_pointer
156         address(const_reference r) const { return &r; }
157
158         /*! \brief Do the actual memory allocation
159          *
160          *  \param n    Number of elements of type T to allocate. n can be
161          *              0 bytes, which will return a non-null properly aligned
162          *              and padded pointer that should not be used.
163          *  \param hint Optional value returned from previous call to allocate.
164          *              For now this is not used.
165          *  \return Pointer to allocated memory
166          *
167          *  \throws std::bad_alloc if the allocation fails.
168          */
169         pointer
170         allocate(std::size_t n, typename std::allocator<void>::const_pointer gmx_unused hint = nullptr)
171         {
172             void *p = AllocationPolicy::malloc(n*sizeof(T));
173
174             if (p == nullptr)
175             {
176                 throw std::bad_alloc();
177             }
178             else
179             {
180                 return static_cast<pointer>(p);
181             }
182         }
183
184         /*! \brief Release memory
185          *
186          * \param p  Pointer to previously allocated memory returned from allocate()
187          * \param n  number of objects previously passed to allocate()
188          */
189         void
190         deallocate(pointer p, std::size_t gmx_unused n)
191         {
192             AllocationPolicy::free(p);
193         }
194
195         //! Return the policy object for this allocator.
196         AllocationPolicy getPolicy() const
197         {
198             return *this;
199         }
200
201         /*! \brief Construct an object without allocating memory
202          *
203          * \tparam Args  Variable-length list of types for constructor args
204          * \param p      Adress of memory where to construct object
205          * \param args   Variable-length list of arguments to constructor
206          */
207         template<class ... Args>
208         void
209         construct(pointer p, Args && ... args) { ::new(p)T(std::forward<Args>(args) ...); }
210
211         /*! \brief Call the destructor of object without releasing memory
212          *
213          * \param p  Address of memory where to destroy object
214          */
215         void
216         destroy(pointer p) { p->~value_type(); }
217
218         /*! \brief Return largest number of objects that can be allocated
219          *
220          * This will be set such that the number of objects T multiplied by
221          * the size of each object is the largest value that can be represented
222          * by size_type.
223          */
224         std::size_t
225         max_size() const { return (static_cast<std::size_t>(0) - static_cast<std::size_t>(1)) / sizeof(T); }
226
227         /*! \brief Return true if two allocators are identical
228          *
229          * This is a member function of the left-hand-side allocator.
230          */
231         template<class T2>
232         bool
233         operator==(const Allocator<T2, AllocationPolicy> & /*unused*/) const { return std::is_same<T, T2>::value; }
234
235         /*! \brief Return true if two allocators are different
236          *
237          * \param rhs Other allocator.
238          *
239          * This is a member function of the left-hand-side allocator.
240          */
241         bool
242         operator!=(const Allocator &rhs) const { return !operator==(rhs); }
243
244         //! Obtain allocator for copy construction
245         Allocator select_on_container_copy_construction() const
246         {
247             return Allocator(AllocationPolicy::select_on_container_copy_construction());
248         }
249 };
250
251 }      // namespace gmx
252
253 #endif