[libc-commits] [libc] 4a96893 - [libc] Fix exp2f and prevent misuse of likely/unlikely

Guillaume Chatelet via libc-commits libc-commits at lists.llvm.org
Fri Feb 10 06:02:04 PST 2023


Author: Guillaume Chatelet
Date: 2023-02-10T14:01:48Z
New Revision: 4a96893fc5ca0ed681b60ffd4a5eba3f094c2f1b

URL: https://github.com/llvm/llvm-project/commit/4a96893fc5ca0ed681b60ffd4a5eba3f094c2f1b
DIFF: https://github.com/llvm/llvm-project/commit/4a96893fc5ca0ed681b60ffd4a5eba3f094c2f1b.diff

LOG: [libc] Fix exp2f and prevent misuse of likely/unlikely

Let's make sure that we only accept boolean expressions when using likely/unlikely.

Differential Revision: https://reviews.llvm.org/D143732

Added: 
    

Modified: 
    libc/src/__support/macros/attributes.h
    libc/src/math/generic/exp2f.cpp

Removed: 
    


################################################################################
diff  --git a/libc/src/__support/macros/attributes.h b/libc/src/__support/macros/attributes.h
index 7be34bd72303e..e949627b2a288 100644
--- a/libc/src/__support/macros/attributes.h
+++ b/libc/src/__support/macros/attributes.h
@@ -19,8 +19,18 @@
 
 #define LIBC_INLINE inline
 #define LIBC_INLINE_ASM __asm__ __volatile__
-#define LIBC_LIKELY(x) __builtin_expect(!!(x), 1)
-#define LIBC_UNLIKELY(x) __builtin_expect(x, 0)
+
+// We use a template to implement likely/unlikely to make sure that we don't
+// accidentally pass an integer.
+namespace __llvm_libc::details {
+template <typename T>
+constexpr LIBC_INLINE bool expects_bool_condition(T value, T expected) {
+  return __builtin_expect(value, expected);
+}
+} // namespace __llvm_libc::details
+#define LIBC_LIKELY(x) __llvm_libc::details::expects_bool_condition(x, true)
+#define LIBC_UNLIKELY(x) __llvm_libc::details::expects_bool_condition(x, false)
+
 #define LIBC_UNUSED __attribute__((unused))
 
 #endif // LLVM_LIBC_SUPPORT_MACROS_ATTRIBUTES_H

diff  --git a/libc/src/math/generic/exp2f.cpp b/libc/src/math/generic/exp2f.cpp
index 835f3edcbc000..52ae89a61022c 100644
--- a/libc/src/math/generic/exp2f.cpp
+++ b/libc/src/math/generic/exp2f.cpp
@@ -69,7 +69,7 @@ LLVM_LIBC_FUNCTION(float, exp2f, (float x)) {
   }
 
   // Check exceptional values.
-  if (LIBC_UNLIKELY(x_u & exval_mask) == exval_mask) {
+  if (LIBC_UNLIKELY((x_u & exval_mask) == exval_mask)) {
     if (LIBC_UNLIKELY(x_u == exval1)) { // x = 0x1.853a6ep-9f
       if (fputil::get_round() == FE_TONEAREST)
         return 0x1.00870ap+0f;


        


More information about the libc-commits mailing list