[FFmpeg-devel] [PATCH 01/12] avutil/avassert: Add av_unreachable and av_assume() macros

Andreas Rheinhardt andreas.rheinhardt at outlook.com
Sat May 25 00:58:21 EEST 2024


Useful to let the compiler and static analyzers know that
something is unreachable without adding an av_assert
(which would be either dead for the compiler or add runtime
overhead) for this.

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt at outlook.com>
---
I can add more macros if it is desired to differentiate between
ASSERT_LEVEL == 1 and ASSERT_LEVEL > 1.

 doc/APIchanges       |  3 +++
 libavutil/avassert.h | 33 +++++++++++++++++++++++++++++++++
 2 files changed, 36 insertions(+)

diff --git a/doc/APIchanges b/doc/APIchanges
index 60f056b863..5a3ae37999 100644
--- a/doc/APIchanges
+++ b/doc/APIchanges
@@ -2,6 +2,9 @@ The last version increases of all libraries were on 2024-03-07
 
 API changes, most recent first:
 
+2024-05-24 - xxxxxxxxxx - lavu 59.xx.100 - avassert.h
+  Add av_unreachable and av_assume() macros.
+
 2024-05-23 - xxxxxxxxxx - lavu 59.20.100 - channel_layout.h
   Add av_channel_layout_ambisonic_order().
 
diff --git a/libavutil/avassert.h b/libavutil/avassert.h
index 1895fb7551..41e29c7687 100644
--- a/libavutil/avassert.h
+++ b/libavutil/avassert.h
@@ -31,6 +31,7 @@
 #ifdef HAVE_AV_CONFIG_H
 #   include "config.h"
 #endif
+#include "attributes.h"
 #include "log.h"
 #include "macros.h"
 
@@ -68,6 +69,38 @@
 #define av_assert2_fpu() ((void)0)
 #endif
 
+/**
+ * Asserts that are used as compiler optimization hints depending
+ * upon ASSERT_LEVEL and NBDEBUG.
+ *
+ * Undefined behaviour occurs if execution reaches a point marked
+ * with av_unreachable or if a condition used with av_assume()
+ * is false.
+ *
+ * The condition used with av_assume() should not have side-effects
+ * and should be visible to the compiler.
+ */
+#if defined(ASSERT_LEVEL) && ASSERT_LEVEL > 0 || !defined(HAVE_AV_CONFIG_H) && !defined(NDEBUG)
+#define av_unreachable  av_assert0(0)
+#define av_assume(cond) av_assert0(cond)
+#elif AV_GCC_VERSION_AT_LEAST(4, 5) || AV_HAS_BUILTIN(__builtin_unreachable)
+#define av_unreachable __builtin_unreachable()
+#if AV_HAS_BUILTIN(__builtin_assume)
+#define av_assume(cond) __builtin_assume(cond)
+#else
+#define av_assume(cond) do {      \
+    if (!(cond))                  \
+        __builtin_unreachable();  \
+} while (0)
+#endif
+#elif  defined(_MSC_VER)
+#define av_unreachable  __assume(0)
+#define av_assume(cond) __assume(cond)
+#else
+#define av_unreachable
+#define av_assume(cond)
+#endif
+
 /**
  * Assert that floating point operations can be executed.
  *
-- 
2.40.1



More information about the ffmpeg-devel mailing list