From 65af215162f87099f949b31c5c401152e70a0914 Mon Sep 17 00:00:00 2001 From: Matthew Fernandez Date: Wed, 9 Mar 2022 18:57:17 -0800 Subject: [PATCH] avoid use of '__builtin_unreachable' in 'UNREACHABLE' macro MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit There was some discussion on !2503¹ around the effect of `__builtin_unreachable` and whether we are really confident applying such a strong compiler hint to complex control flow logic that is, in some cases, only partially understood. This change softens the effect of the `UNREACHABLE` macro to a reliable program abort rather than undefined behavior if mistakenly tagged unreachable code is reached. The result is slightly less efficient but safer code. ¹ https://gitlab.com/graphviz/graphviz/-/merge_requests/2503#note_866261546 --- lib/cgraph/unreachable.h | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/lib/cgraph/unreachable.h b/lib/cgraph/unreachable.h index f3d69b730..919d71534 100644 --- a/lib/cgraph/unreachable.h +++ b/lib/cgraph/unreachable.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include /** Marker for a point in code which execution can never reach. @@ -9,9 +10,7 @@ * * _Noreturn void UNREACHABLE(void); * - * Calling this teaches the compiler that the call site can never be executed, - * and it can optimize with this assumption in mind. This can be used to explain - * that a switch is exhaustive: + * This can be used to explain that a switch is exhaustive: * * switch (…) { * default: UNREACHABLE(); @@ -26,22 +25,9 @@ * UNREACHABLE(); * } */ -#ifdef __GNUC__ #define UNREACHABLE() \ do { \ - assert(0 && "unreachable"); \ - __builtin_unreachable(); \ - } while (0) -#elif defined(_MSC_VER) -#define UNREACHABLE() \ - do { \ - assert(0 && "unreachable"); \ - __assume(0); \ - } while (0) -#else -#define UNREACHABLE() \ - do { \ - assert(0 && "unreachable"); \ + fprintf(stderr, "%s:%d: claimed unreachable code was reached", __FILE__, \ + __LINE__); \ abort(); \ } while (0) -#endif -- 2.40.0