improve ThreadLocalBenchmark
[folly.git] / folly / Memory.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <folly/Traits.h>
20 #include <folly/functional/Invoke.h>
21
22 #include <cstddef>
23 #include <cstdlib>
24 #include <exception>
25 #include <limits>
26 #include <memory>
27 #include <stdexcept>
28 #include <type_traits>
29 #include <utility>
30
31 namespace folly {
32
33 /**
34  * For exception safety and consistency with make_shared. Erase me when
35  * we have std::make_unique().
36  *
37  * @author Louis Brandy (ldbrandy@fb.com)
38  * @author Xu Ning (xning@fb.com)
39  */
40
41 #if __cplusplus >= 201402L || __cpp_lib_make_unique >= 201304L || \
42     (__ANDROID__ && __cplusplus >= 201300L) || _MSC_VER >= 1900
43
44 /* using override */ using std::make_unique;
45
46 #else
47
48 template <typename T, typename... Args>
49 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
50 make_unique(Args&&... args) {
51   return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
52 }
53
54 // Allows 'make_unique<T[]>(10)'. (N3690 s20.9.1.4 p3-4)
55 template <typename T>
56 typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
57 make_unique(const size_t n) {
58   return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
59 }
60
61 // Disallows 'make_unique<T[10]>()'. (N3690 s20.9.1.4 p5)
62 template <typename T, typename... Args>
63 typename std::enable_if<
64   std::extent<T>::value != 0, std::unique_ptr<T>>::type
65 make_unique(Args&&...) = delete;
66
67 #endif
68
69 /**
70  * static_function_deleter
71  *
72  * So you can write this:
73  *
74  *      using RSA_deleter = folly::static_function_deleter<RSA, &RSA_free>;
75  *      auto rsa = std::unique_ptr<RSA, RSA_deleter>(RSA_new());
76  *      RSA_generate_key_ex(rsa.get(), bits, exponent, nullptr);
77  *      rsa = nullptr;  // calls RSA_free(rsa.get())
78  *
79  * This would be sweet as well for BIO, but unfortunately BIO_free has signature
80  * int(BIO*) while we require signature void(BIO*). So you would need to make a
81  * wrapper for it:
82  *
83  *      inline void BIO_free_fb(BIO* bio) { CHECK_EQ(1, BIO_free(bio)); }
84  *      using BIO_deleter = folly::static_function_deleter<BIO, &BIO_free_fb>;
85  *      auto buf = std::unique_ptr<BIO, BIO_deleter>(BIO_new(BIO_s_mem()));
86  *      buf = nullptr;  // calls BIO_free(buf.get())
87  */
88
89 template <typename T, void(*f)(T*)>
90 struct static_function_deleter {
91   void operator()(T* t) const {
92     f(t);
93   }
94 };
95
96 /**
97  *  to_shared_ptr
98  *
99  *  Convert unique_ptr to shared_ptr without specifying the template type
100  *  parameter and letting the compiler deduce it.
101  *
102  *  So you can write this:
103  *
104  *      auto sptr = to_shared_ptr(getSomethingUnique<T>());
105  *
106  *  Instead of this:
107  *
108  *      auto sptr = shared_ptr<T>(getSomethingUnique<T>());
109  *
110  *  Useful when `T` is long, such as:
111  *
112  *      using T = foobar::FooBarAsyncClient;
113  */
114 template <typename T, typename D>
115 std::shared_ptr<T> to_shared_ptr(std::unique_ptr<T, D>&& ptr) {
116   return std::shared_ptr<T>(std::move(ptr));
117 }
118
119 /**
120  *  to_weak_ptr
121  *
122  *  Make a weak_ptr and return it from a shared_ptr without specifying the
123  *  template type parameter and letting the compiler deduce it.
124  *
125  *  So you can write this:
126  *
127  *      auto wptr = to_weak_ptr(getSomethingShared<T>());
128  *
129  *  Instead of this:
130  *
131  *      auto wptr = weak_ptr<T>(getSomethingShared<T>());
132  *
133  *  Useful when `T` is long, such as:
134  *
135  *      using T = foobar::FooBarAsyncClient;
136  */
137 template <typename T>
138 std::weak_ptr<T> to_weak_ptr(const std::shared_ptr<T>& ptr) {
139   return std::weak_ptr<T>(ptr);
140 }
141
142 struct SysBufferDeleter {
143   void operator()(void* p) const {
144     ::free(p);
145   }
146 };
147
148 using SysBufferUniquePtr = std::unique_ptr<void, SysBufferDeleter>;
149 inline SysBufferUniquePtr allocate_sys_buffer(size_t size) {
150   return SysBufferUniquePtr(::malloc(size));
151 }
152
153 /**
154  * A SimpleAllocator must provide two methods:
155  *
156  *    void* allocate(size_t size);
157  *    void deallocate(void* ptr);
158  *
159  * which, respectively, allocate a block of size bytes (aligned to the
160  * maximum alignment required on your system), throwing std::bad_alloc
161  * if the allocation can't be satisfied, and free a previously
162  * allocated block.
163  *
164  * SysAlloc resembles the standard allocator.
165  */
166 class SysAlloc {
167  public:
168   void* allocate(size_t size) {
169     void* p = ::malloc(size);
170     if (!p) {
171       throw std::bad_alloc();
172     }
173     return p;
174   }
175   void deallocate(void* p) {
176     ::free(p);
177   }
178 };
179
180 /**
181  * StlAllocator wraps a SimpleAllocator into a STL-compliant
182  * allocator, maintaining an instance pointer to the simple allocator
183  * object.  The underlying SimpleAllocator object must outlive all
184  * instances of StlAllocator using it.
185  *
186  * But note that if you pass StlAllocator<MallocAllocator,...> to a
187  * standard container it will be larger due to the contained state
188  * pointer.
189  *
190  * @author: Tudor Bosman <tudorb@fb.com>
191  */
192
193 // This would be so much simpler with std::allocator_traits, but gcc 4.6.2
194 // doesn't support it.
195 template <class Alloc, class T> class StlAllocator;
196
197 template <class Alloc> class StlAllocator<Alloc, void> {
198  public:
199   typedef void value_type;
200   typedef void* pointer;
201   typedef const void* const_pointer;
202
203   StlAllocator() : alloc_(nullptr) { }
204   explicit StlAllocator(Alloc* a) : alloc_(a) { }
205
206   Alloc* alloc() const {
207     return alloc_;
208   }
209
210   template <class U> struct rebind {
211     typedef StlAllocator<Alloc, U> other;
212   };
213
214   bool operator!=(const StlAllocator<Alloc, void>& other) const {
215     return alloc_ != other.alloc_;
216   }
217
218   bool operator==(const StlAllocator<Alloc, void>& other) const {
219     return alloc_ == other.alloc_;
220   }
221
222  private:
223   Alloc* alloc_;
224 };
225
226 template <class Alloc, class T>
227 class StlAllocator {
228  public:
229   typedef T value_type;
230   typedef T* pointer;
231   typedef const T* const_pointer;
232   typedef T& reference;
233   typedef const T& const_reference;
234
235   typedef ptrdiff_t difference_type;
236   typedef size_t size_type;
237
238   StlAllocator() : alloc_(nullptr) { }
239   explicit StlAllocator(Alloc* a) : alloc_(a) { }
240
241   template <class U> StlAllocator(const StlAllocator<Alloc, U>& other)
242     : alloc_(other.alloc()) { }
243
244   T* allocate(size_t n, const void* /* hint */ = nullptr) {
245     return static_cast<T*>(alloc_->allocate(n * sizeof(T)));
246   }
247
248   void deallocate(T* p, size_t /* n */) { alloc_->deallocate(p); }
249
250   size_t max_size() const {
251     return std::numeric_limits<size_t>::max();
252   }
253
254   T* address(T& x) const {
255     return std::addressof(x);
256   }
257
258   const T* address(const T& x) const {
259     return std::addressof(x);
260   }
261
262   template <class... Args>
263   void construct(T* p, Args&&... args) {
264     new (p) T(std::forward<Args>(args)...);
265   }
266
267   void destroy(T* p) {
268     p->~T();
269   }
270
271   Alloc* alloc() const {
272     return alloc_;
273   }
274
275   template <class U> struct rebind {
276     typedef StlAllocator<Alloc, U> other;
277   };
278
279   bool operator!=(const StlAllocator<Alloc, T>& other) const {
280     return alloc_ != other.alloc_;
281   }
282
283   bool operator==(const StlAllocator<Alloc, T>& other) const {
284     return alloc_ == other.alloc_;
285   }
286
287  private:
288   Alloc* alloc_;
289 };
290
291 /**
292  * Helper function to obtain rebound allocators
293  *
294  * @author: Marcelo Juchem <marcelo@fb.com>
295  */
296 template <typename T, typename Allocator>
297 typename Allocator::template rebind<T>::other rebind_allocator(
298   Allocator const& allocator
299 ) {
300   return typename Allocator::template rebind<T>::other(allocator);
301 }
302
303 /*
304  * Helper classes/functions for creating a unique_ptr using a custom
305  * allocator.
306  *
307  * @author: Marcelo Juchem <marcelo@fb.com>
308  */
309
310 // Derives from the allocator to take advantage of the empty base
311 // optimization when possible.
312 template <typename Allocator>
313 class allocator_delete
314   : private std::remove_reference<Allocator>::type
315 {
316   typedef typename std::remove_reference<Allocator>::type allocator_type;
317
318  public:
319   typedef typename Allocator::pointer pointer;
320
321   allocator_delete() = default;
322
323   explicit allocator_delete(const allocator_type& allocator)
324     : allocator_type(allocator)
325   {}
326
327   explicit allocator_delete(allocator_type&& allocator)
328     : allocator_type(std::move(allocator))
329   {}
330
331   template <typename U>
332   allocator_delete(const allocator_delete<U>& other)
333     : allocator_type(other.get_allocator())
334   {}
335
336   allocator_type& get_allocator() const {
337     return *const_cast<allocator_delete*>(this);
338   }
339
340   void operator()(pointer p) const {
341     if (!p) {
342       return;
343     }
344     const_cast<allocator_delete*>(this)->destroy(p);
345     const_cast<allocator_delete*>(this)->deallocate(p, 1);
346   }
347 };
348
349 namespace detail {
350
351 FOLLY_CREATE_MEMBER_INVOKE_TRAITS(destroy_invoke_traits, destroy);
352
353 } // namespace detail
354
355 template <typename Allocator, typename Value>
356 using is_simple_allocator =
357     Negation<detail::destroy_invoke_traits::is_invocable<Allocator, Value*>>;
358
359 template <typename T, typename Allocator>
360 struct as_stl_allocator {
361   typedef typename std::conditional<
362     is_simple_allocator<
363       typename std::remove_reference<Allocator>::type,
364       typename std::remove_reference<T>::type
365     >::value,
366     folly::StlAllocator<
367       typename std::remove_reference<Allocator>::type,
368       typename std::remove_reference<T>::type
369     >,
370     typename std::remove_reference<Allocator>::type
371   >::type type;
372 };
373
374 template <typename T, typename Allocator>
375 typename std::enable_if<
376   is_simple_allocator<
377     typename std::remove_reference<Allocator>::type,
378     typename std::remove_reference<T>::type
379   >::value,
380   folly::StlAllocator<
381     typename std::remove_reference<Allocator>::type,
382     typename std::remove_reference<T>::type
383   >
384 >::type make_stl_allocator(Allocator&& allocator) {
385   return folly::StlAllocator<
386     typename std::remove_reference<Allocator>::type,
387     typename std::remove_reference<T>::type
388   >(&allocator);
389 }
390
391 template <typename T, typename Allocator>
392 typename std::enable_if<
393   !is_simple_allocator<
394     typename std::remove_reference<Allocator>::type,
395     typename std::remove_reference<T>::type
396   >::value,
397   typename std::remove_reference<Allocator>::type
398 >::type make_stl_allocator(Allocator&& allocator) {
399   return std::move(allocator);
400 }
401
402 /**
403  * AllocatorUniquePtr: a unique_ptr that supports both STL-style
404  * allocators and SimpleAllocator
405  *
406  * @author: Marcelo Juchem <marcelo@fb.com>
407  */
408
409 template <typename T, typename Allocator>
410 struct AllocatorUniquePtr {
411   typedef std::unique_ptr<T,
412     folly::allocator_delete<
413       typename std::conditional<
414         is_simple_allocator<
415           typename std::remove_reference<Allocator>::type,
416           typename std::remove_reference<T>::type
417         >::value,
418         folly::StlAllocator<typename std::remove_reference<Allocator>::type, T>,
419         typename std::remove_reference<Allocator>::type
420       >::type
421     >
422   > type;
423 };
424
425 /**
426  * Functions to allocate a unique_ptr / shared_ptr, supporting both
427  * STL-style allocators and SimpleAllocator, analog to std::allocate_shared
428  *
429  * @author: Marcelo Juchem <marcelo@fb.com>
430  */
431
432 template <typename T, typename Allocator, typename ...Args>
433 typename AllocatorUniquePtr<T, Allocator>::type allocate_unique(
434   Allocator&& allocator, Args&&... args
435 ) {
436   auto stlAllocator = folly::make_stl_allocator<T>(
437     std::forward<Allocator>(allocator)
438   );
439   auto p = stlAllocator.allocate(1);
440
441   try {
442     stlAllocator.construct(p, std::forward<Args>(args)...);
443
444     return {p,
445       folly::allocator_delete<decltype(stlAllocator)>(std::move(stlAllocator))
446     };
447   } catch (...) {
448     stlAllocator.deallocate(p, 1);
449     throw;
450   }
451 }
452
453 template <typename T, typename Allocator, typename ...Args>
454 std::shared_ptr<T> allocate_shared(Allocator&& allocator, Args&&... args) {
455   return std::allocate_shared<T>(
456     folly::make_stl_allocator<T>(std::forward<Allocator>(allocator)),
457     std::forward<Args>(args)...
458   );
459 }
460
461 /**
462  * IsArenaAllocator<T>::value describes whether SimpleAllocator has
463  * no-op deallocate().
464  */
465 template <class T> struct IsArenaAllocator : std::false_type { };
466
467 /*
468  * folly::enable_shared_from_this
469  *
470  * To be removed once C++17 becomes a minimum requirement for folly.
471  */
472 #if __cplusplus >= 201700L || \
473     __cpp_lib_enable_shared_from_this >= 201603L
474
475 // Guaranteed to have std::enable_shared_from_this::weak_from_this(). Prefer
476 // type alias over our own class.
477 /* using override */ using std::enable_shared_from_this;
478
479 #else
480
481 /**
482  * Extends std::enabled_shared_from_this. Offers weak_from_this() to pre-C++17
483  * code. Use as drop-in replacement for std::enable_shared_from_this.
484  *
485  * C++14 has no direct means of creating a std::weak_ptr, one must always
486  * create a (temporary) std::shared_ptr first. C++17 adds weak_from_this() to
487  * std::enable_shared_from_this to avoid that overhead. Alas code that must
488  * compile under different language versions cannot call
489  * std::enable_shared_from_this::weak_from_this() directly. Hence this class.
490  *
491  * @example
492  *   class MyClass : public folly::enable_shared_from_this<MyClass> {};
493  *
494  *   int main() {
495  *     std::shared_ptr<MyClass> sp = std::make_shared<MyClass>();
496  *     std::weak_ptr<MyClass> wp = sp->weak_from_this();
497  *   }
498  */
499 template <typename T>
500 class enable_shared_from_this : public std::enable_shared_from_this<T> {
501  public:
502   constexpr enable_shared_from_this() noexcept = default;
503
504   std::weak_ptr<T> weak_from_this() noexcept {
505     return weak_from_this_<T>(this);
506   }
507
508   std::weak_ptr<T const> weak_from_this() const noexcept {
509     return weak_from_this_<T>(this);
510   }
511
512  private:
513   // Uses SFINAE to detect and call
514   // std::enable_shared_from_this<T>::weak_from_this() if available. Falls
515   // back to std::enable_shared_from_this<T>::shared_from_this() otherwise.
516   template <typename U>
517   auto weak_from_this_(std::enable_shared_from_this<U>* base_ptr)
518   noexcept -> decltype(base_ptr->weak_from_this()) {
519     return base_ptr->weak_from_this();
520   }
521
522   template <typename U>
523   auto weak_from_this_(std::enable_shared_from_this<U> const* base_ptr)
524   const noexcept -> decltype(base_ptr->weak_from_this()) {
525     return base_ptr->weak_from_this();
526   }
527
528   template <typename U>
529   std::weak_ptr<U> weak_from_this_(...) noexcept {
530     try {
531       return this->shared_from_this();
532     } catch (std::bad_weak_ptr const&) {
533       // C++17 requires that weak_from_this() on an object not owned by a
534       // shared_ptr returns an empty weak_ptr. Sadly, in C++14,
535       // shared_from_this() on such an object is undefined behavior, and there
536       // is nothing we can do to detect and handle the situation in a portable
537       // manner. But in case a compiler is nice enough to implement C++17
538       // semantics of shared_from_this() and throws a bad_weak_ptr, we catch it
539       // and return an empty weak_ptr.
540       return std::weak_ptr<U>{};
541     }
542   }
543
544   template <typename U>
545   std::weak_ptr<U const> weak_from_this_(...) const noexcept {
546     try {
547       return this->shared_from_this();
548     } catch (std::bad_weak_ptr const&) {
549       return std::weak_ptr<U const>{};
550     }
551   }
552 };
553
554 #endif
555
556 } // namespace folly