Use compiler-provided assume builtins when available

There are several benefits to this:
1. It's cleaner and more reliable to use the builtin to
   inform the compiler of assumptions instead of hoping that the
   optimizer understands your intentions.
2. `clang` will warn you if any of your assumptions would produce
   side-effects (which the compiler will discard). [This blog post](https://fastcompression.blogspot.com/2019/01/compiler-checked-contracts.html)
   by Yann Collet highlights that a hazard of using the
   `unreachable()`-based method of signaling assumptions is that it
   can sometimes result in additional instructions being generated (see
   [this Godbolt link](https://godbolt.org/z/lKNMs3) from the blog post
   for an example).
This commit is contained in:
Kevin Svetlitski 2023-07-27 11:49:07 -07:00 committed by Qi Wang
parent 3aae792b10
commit 4f50f782fa
2 changed files with 14 additions and 7 deletions

View File

@ -378,7 +378,7 @@ arena_dalloc(tsdn_t *tsdn, void *ptr, tcache_t *tcache,
if (caller_alloc_ctx != NULL) { if (caller_alloc_ctx != NULL) {
alloc_ctx = *caller_alloc_ctx; alloc_ctx = *caller_alloc_ctx;
} else { } else {
util_assume(!tsdn_null(tsdn)); util_assume(tsdn != NULL);
emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr, emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr,
&alloc_ctx); &alloc_ctx);
} }

View File

@ -65,12 +65,19 @@ get_errno(void) {
#endif #endif
} }
JEMALLOC_ALWAYS_INLINE void #ifdef _MSC_VER
util_assume(bool b) { #define util_assume __assume
if (!b) { #elif defined(__clang__) && (__clang_major__ > 3 || \
unreachable(); (__clang_major__ == 3 && __clang_minor__ >= 6))
} #define util_assume __builtin_assume
} #else
#define util_assume(expr) \
do { \
if (!(expr)) { \
unreachable(); \
} \
} while(0)
#endif
/* ptr should be valid. */ /* ptr should be valid. */
JEMALLOC_ALWAYS_INLINE void JEMALLOC_ALWAYS_INLINE void