Re: [PATCH] fat: Refactor fat_tolower with branchless implementation

From: OGAWA Hirofumi
Date: Tue Mar 18 2025 - 00:02:45 EST


I Hsin Cheng <richard120310@xxxxxxxxx> writes:

> Elimate the need of if-else branch within fat_tolower, replace it with a
> branchless bitwise operation. This can reduce the number of branch ~130
> regarding to the test script[1].
>
> Test size can also be reduced:
> $ ./scripts/bloat-o-meter vmlinux_old vmlinux_new
> add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-68 (-68)
> Function old new delta
> fat_parse_short 1901 1833 -68
> Total: Before=22471023, After=22470955, chg -0.00%
>
> Signed-off-by: I Hsin Cheng <richard120310@xxxxxxxxx>
> ---
> [1]:
> static inline unsigned char old_tolower(unsigned char c)
> {
> return ((c >= 'A') && (c <= 'Z')) ? c+32 : c;
> }
>
> static inline unsigned char new_tolower(unsigned char c)
> {
> return c | 0x20;
> }

Looks like doesn't work correctly. For example, new one changes TAB to ')'.

Thanks.

> int main(void) {
> for (unsigned char i = 0; i < 26; i++) {
> if (old_tolower('a' + i) != old_tolower('A' + i))
> return 1;
> }
>
> return 0;
> }
>
> Utilize perf to profile the difference when using old_tolower() and
> new_tolower().
>
> $ perf stat -e branches,branch-misses --repeat 100 ./old
>
> Performance counter stats for './old':
>
> 2,6302 branches:u
> 2334 branch-misses:u
>
> 0.000754710 seconds time elapsed
>
> 0.000000000 seconds user
> 0.000804000 seconds sys
>
> $ perf stat -e branches,branch-misses --repeat 100 ./new
>
> Performance counter stats for './main':
>
> 2,6172 branches:u
> 2338 branch-misses:u
>
> 0.000782670 seconds time elapsed
>
> 0.000853000 seconds user
> 0.000000000 seconds sys
>
> Best regards,
> I Hsin Cheng
> ---
> fs/fat/dir.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/fs/fat/dir.c b/fs/fat/dir.c
> index acbec5bdd521..77d212b4d4db 100644
> --- a/fs/fat/dir.c
> +++ b/fs/fat/dir.c
> @@ -35,7 +35,7 @@
>
> static inline unsigned char fat_tolower(unsigned char c)
> {
> - return ((c >= 'A') && (c <= 'Z')) ? c+32 : c;
> + return c | 0x20;
> }
>
> static inline loff_t fat_make_i_pos(struct super_block *sb,

--
OGAWA Hirofumi <hirofumi@xxxxxxxxxxxxxxxxxx>