From c1f63cafa8c50ae218f79847588b52ed30851dcb Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Mon, 6 Mar 2023 19:21:59 +0100 Subject: [PATCH 1/2] core/compiler_hints: add assume() hint --- core/lib/include/compiler_hints.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/lib/include/compiler_hints.h b/core/lib/include/compiler_hints.h index 78180e5b9ce9..3cca6cdfbc00 100644 --- a/core/lib/include/compiler_hints.h +++ b/core/lib/include/compiler_hints.h @@ -21,6 +21,7 @@ #ifndef COMPILER_HINTS_H #define COMPILER_HINTS_H +#include #include #ifdef __cplusplus @@ -164,6 +165,22 @@ extern "C" { */ #define unlikely(x) __builtin_expect((uintptr_t)(x), 0) +/** + * @brief Behaves like an `assert()`, but tells the compiler that @p cond can + * never be false. + * This allows the compiler to optimize the code accordingly even when + * `NDEBUG` is set / with `DEVELHELP=0`. + * + * @p cond being false will result in undefined behavior. + * + * @param[in] cond Condition that is guaranteed to be true + */ +#ifdef NDEBUG +#define assume(cond) ((cond) ? (void)0 : UNREACHABLE()) +#else +#define assume(cond) assert(cond) +#endif + #ifdef __cplusplus } #endif From a5bc1b37224355ef74749585c0281941daa03258 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Mon, 6 Mar 2023 20:23:41 +0100 Subject: [PATCH 2/2] core/compiler_hints: fix detection of __builtin_unreachable() --- core/lib/include/compiler_hints.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/lib/include/compiler_hints.h b/core/lib/include/compiler_hints.h index 3cca6cdfbc00..d300146fed49 100644 --- a/core/lib/include/compiler_hints.h +++ b/core/lib/include/compiler_hints.h @@ -90,7 +90,7 @@ extern "C" { * Use this if the compiler cannot tell that e.g. * an assembler instruction causes a longjmp, or a write causes a reboot. */ -#if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ >= 5) +#if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ >= 5) || defined(__clang__) #define UNREACHABLE() __builtin_unreachable() #else #define UNREACHABLE() do { /* nothing */ } while (1)