Skip to content

Commit 3452949

Browse files
sebastianasgitster
authored andcommitted
bswap.h: provide a built-in based version of bswap32/64 if possible
The compiler is in general able to recognize the endian shift and replace it with an optimized opcode if possible. On certain architectures such as RiscV or MIPS the situation can get complicated. They don't provide an optimized opcode and masking the "higher" bits may required loading a constant which needs shifting. This causes the compiler to emit a lot of instructions for the operation. The provided builtin directive on these architecture calls a function which does the operation instead of emitting the code for operation. Bring back the change from commit 6547d1c (bswap.h: add support for built-in bswap functions, 2025-04-23). The bswap32/64 macro can now be defined unconditionally so it won't regress on big endian architectures. Signed-off-by: Sebastian Andrzej Siewior <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 13c2acd commit 3452949

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

compat/bswap.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ static inline uint64_t default_bswap64(uint64_t val)
3232
((val & (uint64_t)0xff00000000000000ULL) >> 56));
3333
}
3434

35+
/*
36+
* __has_builtin is available since Clang 10 and GCC 10.
37+
* Below is a fallback for older compilers.
38+
*/
39+
#ifndef __has_builtin
40+
# define __has_builtin(x) 0
41+
#endif
42+
3543
#undef bswap32
3644
#undef bswap64
3745

@@ -46,6 +54,11 @@ static inline uint64_t default_bswap64(uint64_t val)
4654
#define GIT_BIG_ENDIAN 4321
4755
#define GIT_BYTE_ORDER GIT_LITTLE_ENDIAN
4856

57+
#elif __has_builtin(__builtin_bswap32) && __has_builtin(__builtin_bswap64)
58+
59+
#define bswap32(x) __builtin_bswap32((x))
60+
#define bswap64(x) __builtin_bswap64((x))
61+
4962
#endif
5063

5164
#if defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && defined(__BIG_ENDIAN)

0 commit comments

Comments
 (0)