Skip to content

Cache the default malloc zone #29978

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 21, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions stdlib/public/runtime/Heap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
#include "../SwiftShims/RuntimeShims.h"
#include <algorithm>
#include <stdlib.h>
#if defined(__APPLE__)
#include "swift/Basic/Lazy.h"
#include <malloc/malloc.h>
#endif

using namespace swift;

Expand Down Expand Up @@ -57,6 +61,13 @@ using namespace swift;
static_assert(_swift_MinAllocationAlignment > MALLOC_ALIGN_MASK,
"Swift's default alignment must exceed platform malloc mask.");

#if defined(__APPLE__)
static inline malloc_zone_t *DEFAULT_ZONE() {
static malloc_zone_t *z = SWIFT_LAZY_CONSTANT(malloc_default_zone());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The static and SWIFT_LAZY_CONSTANT create two levels of lazy initialization; we only need one of them IIUC.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! This shouldn't have the static.

return z;
}
#endif

// When alignMask == ~(size_t(0)), allocation uses the "default"
// _swift_MinAllocationAlignment. This is different than calling swift_slowAlloc
// with `alignMask == _swift_MinAllocationAlignment - 1` because it forces
Expand All @@ -77,7 +88,11 @@ void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
void *p;
// This check also forces "default" alignment to use AlignedAlloc.
if (alignMask <= MALLOC_ALIGN_MASK) {
#if defined(__APPLE__)
p = malloc_zone_malloc(DEFAULT_ZONE(), size);
#else
p = malloc(size);
#endif
} else {
size_t alignment = (alignMask == ~(size_t(0)))
? _swift_MinAllocationAlignment
Expand Down Expand Up @@ -106,7 +121,11 @@ void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
// consistent with allocation with the same alignment.
void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) {
if (alignMask <= MALLOC_ALIGN_MASK) {
#if defined(__APPLE__)
malloc_zone_free(DEFAULT_ZONE(), ptr);
#else
free(ptr);
#endif
} else {
AlignedFree(ptr);
}
Expand Down