Re: [PATCH 1/3] Compiler Attributes: Add __assume macro
From: Nathan Chancellor
Date: Wed Sep 10 2025 - 21:32:48 EST
Hi Heiko,
On Wed, Sep 10, 2025 at 05:12:14PM +0200, Heiko Carstens wrote:
> Make the statement attribute "assume" with a new __assume macro available.
>
> This allows compilers to generate better code, however code which makes use
> of __assume must be written as if the compiler ignores the hint. Otherwise
> this may lead to subtle bugs if code is compiled with compilers which do
> not support the attribute.
>
> Signed-off-by: Heiko Carstens <hca@xxxxxxxxxxxxx>
> ---
> include/linux/compiler_attributes.h | 16 ++++++++++++++++
> 1 file changed, 16 insertions(+)
>
> diff --git a/include/linux/compiler_attributes.h b/include/linux/compiler_attributes.h
> index c16d4199bf92..16c3d4a865e2 100644
> --- a/include/linux/compiler_attributes.h
> +++ b/include/linux/compiler_attributes.h
> @@ -54,6 +54,22 @@
> */
> #define __always_inline inline __attribute__((__always_inline__))
>
> +/*
> + * Beware: Code which makes use of __assume must be written as if the compiler
> + * ignores the hint. Otherwise this may lead to subtle bugs if code is compiled
> + * with compilers which do not support the attribute.
It may be worth noting that careful analysis should be performed when
adding this attribute since clang's documentation [1] (more on that
below...) notes that it could hurt optimizations just as much as it
could help it.
> + *
> + * Optional: only supported since GCC >= 13.1, clang >= 12.0
> + *
> + * gcc: https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html#index-assume-statement-attribute
> + * clang: https://clang.llvm.org/docs/AttributeReference.html#assume
Looking at this link sent me down a bit of a rabbit hole :) Prior to
Clang 19.1.0 [2], assume was an OpenMP attribute, which has completely
different semantics and errors out when used in the way the series does:
In file included from kernel/bounds.c:13:
In file included from include/linux/log2.h:12:
In file included from include/linux/bitops.h:67:
arch/s390/include/asm/bitops.h:173:12: error: expected string literal as argument of '__assume__' attribute
173 | __assume(bit <= 64);
| ^
Unfortunately, I think __assume will need to be handled in the compiler
specific headers :/
[1]: https://clang.llvm.org/docs/AttributeReference.html#id13
[2]: https://github.com/llvm/llvm-project/commit/c44fa3e8a9a44c2e9a575768a3c185354b9f6c17
Cheers,
Nathan
> + */
> +#if __has_attribute(assume)
> +# define __assume(expr) __attribute__((__assume__(expr)))
> +#else
> +# define __assume(expr)
> +#endif
> +
> /*
> * The second argument is optional (default 0), so we use a variadic macro
> * to make the shorthand.
> --
> 2.48.1
>