Skip to content

Commit 7bcaa43

Browse files
committed
Update base for Update on "[Executorch] Make module constructors uniform across"
Existing constructors dont compose well such that if you want data loader or data files constructor then you cannot get to override memory allocator. Fix that. Differential Revision: [D86120037](https://our.internmc.facebook.com/intern/diff/D86120037/) [ghstack-poisoned]
1 parent 93291c3 commit 7bcaa43

File tree

1 file changed

+9
-15
lines changed

1 file changed

+9
-15
lines changed

extension/memory_allocator/cpu_caching_malloc_allocator.cpp

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,6 @@
44

55
namespace executorch::extension {
66

7-
namespace {
8-
size_t get_alignment_adjusted_size(size_t size, size_t alignment) {
9-
if (size % alignment != 0) {
10-
// Adjust size to the next multiple of alignment
11-
// This is needed for aligned_alloc to work
12-
return (size + alignment) & ~(alignment - 1);
13-
} else {
14-
return size;
15-
}
16-
}
17-
} // namespace
18-
197
CPUCachingAllocator::CPUCachingAllocator(uint32_t max_size)
208
: MemoryAllocator(0, nullptr) {
219
max_size_ = max_size;
@@ -30,7 +18,6 @@ void* CPUCachingAllocator::allocate(size_t size, size_t alignment) {
3018
return nullptr;
3119
}
3220
alignment = std::max(alignment, kCachingAllocatorDefaultAlignment);
33-
size = get_alignment_adjusted_size(size, alignment);
3421

3522
std::lock_guard<std::mutex> guard(mutex_);
3623
const auto& it = available_map_.find(size);
@@ -39,7 +26,14 @@ void* CPUCachingAllocator::allocate(size_t size, size_t alignment) {
3926
// 2. Allocate new memory
4027
// 2 can lead to current_size > max_size_
4128
if (it == available_map_.end() || it->second.empty()) {
42-
void* ptr = std::malloc(size);
29+
void* ptr = nullptr;
30+
#if defined(__ANDROID__)
31+
ptr = memalign(alignment, size);
32+
#elif defined(_MSC_VER)
33+
ptr = _aligned_malloc(size, alignment);
34+
#else
35+
ptr = std::aligned_alloc(alignment, size);
36+
#endif
4337
if (ptr == nullptr) {
4438
ET_LOG(Error, "Failed to allocate memory");
4539
return nullptr;
@@ -51,7 +45,7 @@ void* CPUCachingAllocator::allocate(size_t size, size_t alignment) {
5145
void* ptr = it->second.back();
5246
it->second.pop_back();
5347
allocation_map_[ptr] = size;
54-
return ptr;
48+
return alignPointer(ptr, alignment);
5549
}
5650

5751
void CPUCachingAllocator::free_everything() {

0 commit comments

Comments
 (0)