[libc++] Factor out common logic for calling aligned allocation
There were a couple of places where we needed to call the underlying
platform's aligned allocation/deallocation function. Instead of having
the same logic all over the place, extract the logic into a pair of
helper functions __libcpp_aligned_alloc and __libcpp_aligned_free.
The code in libcxxabi/src/fallback_malloc.cpp looks like it could be
simplified after this change -- I purposefully did not simplify it
further to keep this change as straightforward as possible, since it
is touching very important parts of the library.
Also, the changes in libcxx/src/new.cpp and libcxxabi/src/stdlib_new_delete.cpp
are basically the same -- I just kept both source files in sync.
The underlying reason for this refactoring is to make it easier to support
platforms that provide aligned allocation through C11's aligned_alloc
function instead of posix_memalign. After this change, we'll only have
to add support for that in a single place.
Differential Revision: https://reviews.llvm.org/D91379
GitOrigin-RevId: a78aaa1ad51214b2e04f41762e76bb43067ea1fd
diff --git a/src/fallback_malloc.cpp b/src/fallback_malloc.cpp
index 75c01ef..7872018 100644
--- a/src/fallback_malloc.cpp
+++ b/src/fallback_malloc.cpp
@@ -17,6 +17,7 @@
#include <stdlib.h> // for malloc, calloc, free
#include <string.h> // for memset
+#include <new> // for std::__libcpp_aligned_{alloc,free}
// A small, simple heap manager based (loosely) on
// the startup heap manager from FreeBSD, optimized for space.
@@ -204,7 +205,7 @@
void* __aligned_malloc_with_fallback(size_t size) {
#if defined(_WIN32)
- if (void* dest = _aligned_malloc(size, alignof(__aligned_type)))
+ if (void* dest = std::__libcpp_aligned_alloc(alignof(__aligned_type), size))
return dest;
#elif defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION)
if (void* dest = ::malloc(size))
@@ -212,8 +213,7 @@
#else
if (size == 0)
size = 1;
- void* dest;
- if (::posix_memalign(&dest, __alignof(__aligned_type), size) == 0)
+ if (void* dest = std::__libcpp_aligned_alloc(__alignof(__aligned_type), size))
return dest;
#endif
return fallback_malloc(size);
@@ -234,11 +234,7 @@
if (is_fallback_ptr(ptr))
fallback_free(ptr);
else {
-#if defined(_WIN32)
- ::_aligned_free(ptr);
-#else
- ::free(ptr);
-#endif
+ std::__libcpp_aligned_free(ptr);
}
}