1// Copyright 2019 Google LLC
2//
3// This source code is licensed under the BSD-style license found in the
4// LICENSE file in the root directory of this source tree.
5
6#include <assert.h>
7#include <stddef.h>
8#include <stdlib.h>
9#ifdef __ANDROID__
10 #include <malloc.h>
11#endif
12
13#include <xnnpack/allocator.h>
14#include <xnnpack/common.h>
15
16
17extern int posix_memalign(void **memptr, size_t alignment, size_t size);
18
19
20static void* xnn_allocate(void* context, size_t size) {
21 return malloc(size);
22}
23
24static void* xnn_reallocate(void* context, void* pointer, size_t size) {
25 return realloc(pointer, size);
26}
27
28static void xnn_deallocate(void* context, void* pointer) {
29 if XNN_LIKELY(pointer != NULL) {
30 free(pointer);
31 }
32}
33
34static void* xnn_aligned_allocate(void* context, size_t alignment, size_t size) {
35#if XNN_ARCH_WASM
36 assert(alignment <= 2 * sizeof(void*));
37 return malloc(size);
38#elif XNN_PLATFORM_ANDROID
39 return memalign(alignment, size);
40#elif XNN_PLATFORM_WINDOWS
41 return _aligned_malloc(size, alignment);
42#else
43 void* memory_ptr = NULL;
44 if (posix_memalign(&memory_ptr, alignment, size) != 0) {
45 return NULL;
46 }
47 return memory_ptr;
48#endif
49}
50
51static void xnn_aligned_deallocate(void* context, void* pointer) {
52 if XNN_LIKELY(pointer != NULL) {
53 #if defined(_WIN32)
54 _aligned_free(pointer);
55 #else
56 free(pointer);
57 #endif
58 }
59}
60
61const struct xnn_allocator xnn_default_allocator = {
62 .allocate = xnn_allocate,
63 .reallocate = xnn_reallocate,
64 .deallocate = xnn_deallocate,
65 .aligned_allocate = xnn_aligned_allocate,
66 .aligned_deallocate = xnn_aligned_deallocate,
67};
68