nolibc x86-64 string functions
cover nolibc x86-64 string functions
Hi Willy,
This is an RFC patchset for nolibc x86-64 string functions. There are 5 patches in this series.
## Patch 1-3: Use rep movsb, rep stosb, and rep cmpsb for:
- memcpy() and memmove()
- memset()
- memcmp()
respectively. They can simplify the generated ASM code.
Patch 4 and 5 are not related, just a small cleanup.
## Patch 4: Remove the _nolibc_memcpy_down() function This nolibc internal function is not used. Delete it. It was probably supposed to handle memmove(), but today the memmove() has its own implementation.
## Patch 5: Remove the _nolibc_memcpy_up() function
This function is only called by memcpy(), there is no real reason to have this wrapper. Delete this function and move the code to memcpy() directly.
Before this series:
```
0000000000001479 <memmove>:
1479: f3 0f 1e fa endbr64
147d: 48 39 f7 cmp %rsi,%rdi
1480: 48 c7 c1 ff ff ff ff mov $0xffffffffffffffff,%rcx
1487: 48 89 f8 mov %rdi,%rax
148a: 48 0f 43 ca cmovae %rdx,%rcx
148e: 48 19 ff sbb %rdi,%rdi
1491: 83 e7 02 and $0x2,%edi
1494: 48 ff cf dec %rdi
1497: 48 85 d2 test %rdx,%rdx
149a: 74 10 je 14ac <memmove+0x33>
149c: 48 01 f9 add %rdi,%rcx
149f: 48 ff ca dec %rdx
14a2: 44 8a 04 0e mov (%rsi,%rcx,1),%r8b
14a6: 44 88 04 08 mov %r8b,(%rax,%rcx,1)
14aa: eb eb jmp 1497 <memmove+0x1e>
14ac: c3 ret
00000000000014ad <memcpy>:
14ad: f3 0f 1e fa endbr64
14b1: 48 89 f8 mov %rdi,%rax
14b4: 31 c9 xor %ecx,%ecx
14b6: 48 39 ca cmp %rcx,%rdx
14b9: 74 0d je 14c8 <memcpy+0x1b>
14bb: 40 8a 3c 0e mov (%rsi,%rcx,1),%dil
14bf: 40 88 3c 08 mov %dil,(%rax,%rcx,1)
14c3: 48 ff c1 inc %rcx
14c6: eb ee jmp 14b6 <memcpy+0x9>
14c8: c3 ret
00000000000014c9 <memset>:
14c9: f3 0f 1e fa endbr64
14cd: 48 89 f8 mov %rdi,%rax
14d0: 31 c9 xor %ecx,%ecx
14d2: 48 39 ca cmp %rcx,%rdx
14d5: 74 09 je 14e0 <memset+0x17>
14d7: 40 88 34 08 mov %sil,(%rax,%rcx,1)
14db: 48 ff c1 inc %rcx
14de: eb f2 jmp 14d2 <memset+0x9>
14e0: c3 ret
```After this series:
```
000000000000140a <memmove>:
140a: 48 89 f8 mov %rdi,%rax
140d: 48 89 d1 mov %rdx,%rcx
1410: 48 8d 7c 0f ff lea -0x1(%rdi,%rcx,1),%rdi
1415: 48 8d 74 0e ff lea -0x1(%rsi,%rcx,1),%rsi
141a: fd std
141b: f3 a4 rep movsb %ds:(%rsi),%es:(%rdi)
141d: fc cld
141e: c3 ret
000000000000141f <memcpy>:
141f: 48 89 f8 mov %rdi,%rax
1422: 48 89 d1 mov %rdx,%rcx
1425: f3 a4 rep movsb %ds:(%rsi),%es:(%rdi)
1427: c3 ret
0000000000001428 <memset>:
1428: 48 89 f0 mov %rsi,%rax
142b: 48 89 d1 mov %rdx,%rcx
142e: 48 89 fa mov %rdi,%rdx
1431: f3 aa rep stos %al,%es:(%rdi)
1433: 48 89 d0 mov %rdx,%rax
1436: c3 ret
```---
Ammar Faizi (5):
tools/nolibc: x86-64: Use rep movsb for memcpy() and memmove() tools/nolibc: x86-64: Use rep stosb for memset() tools/nolibc: x86-64: Use rep cmpsb for memcmp() tools/nolibc: string: Remove the _nolibc_memcpy_down() function tools/nolibc: string: Remove the _nolibc_memcpy_up() function
tools/include/nolibc/arch-x86_64.h | 60 ++++++++++++++++++++++++++++++ tools/include/nolibc/string.h | 38 ++++++++----------- 2 files changed, 75 insertions(+), 23 deletions(-)
base-commit: 3c9b7c4a228bf8cca2f92abb65575cdd54065302
Signature · 1 line
Ammar Faizi
RFC PATCH 1/5 tools/nolibc: x86-64: Use `rep movsb` for `memcpy()` and `memmove()`
Simplify memcpy() and memmove() on the x86-64 arch.
The x86-64 arch has a 'rep movsb' instruction, which can perform memcpy() using only a single instruction, given:
%rdi = destination
%rsi = source
%rcx = length
Additionally, it can also handle the overlapping case by setting DF=1 (backward copy), which can be used as the memmove() implementation.
Before this patch:
```
00000000000010ab <memmove>:
10ab: 48 89 f8 mov %rdi,%rax
10ae: 31 c9 xor %ecx,%ecx
10b0: 48 39 f7 cmp %rsi,%rdi
10b3: 48 83 d1 ff adc $0xffffffffffffffff,%rcx
10b7: 48 85 d2 test %rdx,%rdx
10ba: 74 25 je 10e1 <memmove+0x36>
10bc: 48 83 c9 01 or $0x1,%rcx
10c0: 48 39 f0 cmp %rsi,%rax
10c3: 48 c7 c7 ff ff ff ff mov $0xffffffffffffffff,%rdi
10ca: 48 0f 43 fa cmovae %rdx,%rdi
10ce: 48 01 cf add %rcx,%rdi
10d1: 44 8a 04 3e mov (%rsi,%rdi,1),%r8b
10d5: 44 88 04 38 mov %r8b,(%rax,%rdi,1)
10d9: 48 01 cf add %rcx,%rdi
10dc: 48 ff ca dec %rdx
10df: 75 f0 jne 10d1 <memmove+0x26>
10e1: c3 ret
00000000000010e2 <memcpy>:
10e2: 48 89 f8 mov %rdi,%rax
10e5: 48 85 d2 test %rdx,%rdx
10e8: 74 12 je 10fc <memcpy+0x1a>
10ea: 31 c9 xor %ecx,%ecx
10ec: 40 8a 3c 0e mov (%rsi,%rcx,1),%dil
10f0: 40 88 3c 08 mov %dil,(%rax,%rcx,1)
10f4: 48 ff c1 inc %rcx
10f7: 48 39 ca cmp %rcx,%rdx
10fa: 75 f0 jne 10ec <memcpy+0xa>
10fc: c3 ret
```After this patch:
```
0000000000001093 <memmove>:
1093: 48 89 f8 mov %rdi,%rax
1096: 48 89 d1 mov %rdx,%rcx
1099: 48 8d 7c 0f ff lea -0x1(%rdi,%rcx,1),%rdi
109e: 48 8d 74 0e ff lea -0x1(%rsi,%rcx,1),%rsi
10a3: fd std
10a4: f3 a4 rep movsb %ds:(%rsi),%es:(%rdi)
10a6: fc cld
10a7: c3 ret
00000000000010a8 <memcpy>:
10a8: 48 89 f8 mov %rdi,%rax
10ab: 48 89 d1 mov %rdx,%rcx
10ae: f3 a4 rep movsb %ds:(%rsi),%es:(%rdi)
10b0: c3 ret
```--- tools/include/nolibc/arch-x86_64.h | 28 ++++++++++++++++++++++++++++ tools/include/nolibc/string.h | 4 ++++ 2 files changed, 32 insertions(+)
tools/include/nolibc/arch-x86_64.h +28 -0
@@ -173,4 +173,32 @@ void __attribute__((weak, noreturn, optimize("Os", "omit-frame-pointer"))) __no_ __builtin_unreachable(); } +#define NOLIBC_ARCH_HAS_MEMMOVE +void *memmove (void *dst,const void *src,size_t len); + +#define NOLIBC_ARCH_HAS_MEMCPY +void *memcpy (void *dst,const void *src,size_t len); + +__asm__ ( +".section .text.nolibc_memmove\n" +".weak memmove\n" +"memmove:\n" +"movq %rdi, %rax\n" +"movq %rdx, %rcx\n" +"leaq -1(%rdi, %rcx), %rdi\n" +"leaq -1(%rsi, %rcx), %rsi\n" +"std\n" +"rep movsb\n" +"cld\n" +"retq\n" + +".section .text.nolibc_memcpy\n" +".weak memcpy\n" +"memcpy:\n" +"movq %rdi, %rax\n" +"movq %rdx, %rcx\n" +"rep movsb\n" +"retq\n" +); +#endif /* _NOLIBC_ARCH_X86_64_H */
tools/include/nolibc/string.h +4 -0
@@ -49,6 +49,7 @@ void *_nolibc_memcpy_down(void *dst, const void *src, size_t len)return dst; } +#ifndef NOLIBC_ARCH_HAS_MEMMOVE /* might be ignored by the compiler without -ffreestanding, then found as * missing. */
@@ -72,13 +73,16 @@ void *memmove(void *dst, const void *src, size_t len) }return dst; } +#endif /* #ifndef NOLIBC_ARCH_HAS_MEMMOVE */ +#ifndef NOLIBC_ARCH_HAS_MEMCPY /* must be exported, as it's used by libgcc on ARM */ __attribute__((weak,unused,section (".text.nolibc_memcpy" )))void *memcpy (void *dst,const void *src,size_t len) {return _nolibc_memcpy_up (dst, src, len); } +#endif /* #ifndef NOLIBC_ARCH_HAS_MEMCPY */ /* might be ignored by the compiler without -ffreestanding, then found as * missing.
Signature · 1 line
Ammar Faizi
RFC PATCH 2/5 tools/nolibc: x86-64: Use `rep stosb` for `memset()`
In reply to Ammar FaiziSimplify memset() on the x86-64 arch.
The x86-64 arch has a 'rep stosb' instruction, which can perform memset() using only a single instruction, given:
%al = value (just like the second argument of memset()) %rdi = destination
%rcx = length
Before this patch:
```
00000000000010c9 <memset>:
10c9: 48 89 f8 mov %rdi,%rax
10cc: 48 85 d2 test %rdx,%rdx
10cf: 74 0e je 10df <memset+0x16>
10d1: 31 c9 xor %ecx,%ecx
10d3: 40 88 34 08 mov %sil,(%rax,%rcx,1)
10d7: 48 ff c1 inc %rcx
10da: 48 39 ca cmp %rcx,%rdx
10dd: 75 f4 jne 10d3 <memset+0xa>
10df: c3 ret
```After this patch:
```
00000000000010b1 <memset>:
10b1: 48 89 f0 mov %rsi,%rax
10b4: 48 89 d1 mov %rdx,%rcx
10b7: 48 89 fa mov %rdi,%rdx
10ba: f3 aa rep stos %al,%es:(%rdi)
10bc: 48 89 d0 mov %rdx,%rax
10bf: c3 ret
```--- tools/include/nolibc/arch-x86_64.h | 13 +++++++++++++ tools/include/nolibc/string.h | 2 ++ 2 files changed, 15 insertions(+)
tools/include/nolibc/arch-x86_64.h +13 -0
@@ -179,6 +179,9 @@ void *memmove(void *dst, const void *src, size_t len);#define NOLIBC_ARCH_HAS_MEMCPY void *memcpy (void *dst,const void *src,size_t len); +#define NOLIBC_ARCH_HAS_MEMSET +void *memset (void *dst,int c,size_t len); + __asm__ (".section .text.nolibc_memmove\n" ".weak memmove\n"
@@ -199,6 +202,16 @@ __asm__ ("movq %rdx, %rcx\n" "rep movsb\n" "retq\n" + +".section .text.nolibc_memset\n" +".weak memset\n" +"memset:\n" +"movq %rsi, %rax\n" +"movq %rdx, %rcx\n" +"movq %rdi, %rdx\n" +"rep stosb\n" +"movq %rdx, %rax\n" +"retq\n" );#endif /* _NOLIBC_ARCH_X86_64_H */
tools/include/nolibc/string.h +2 -0
@@ -84,6 +84,7 @@ void *memcpy(void *dst, const void *src, size_t len) }#endif /* #ifndef NOLIBC_ARCH_HAS_MEMCPY */ +#ifndef NOLIBC_ARCH_HAS_MEMSET /* might be ignored by the compiler without -ffreestanding, then found as * missing. */
@@ -99,6 +100,7 @@ void *memset(void *dst, int b, size_t len) }return dst; } +#endif /* #ifndef NOLIBC_ARCH_HAS_MEMSET */ static __attribute__((unused))char *strchr (const char *s,int c)
Signature · 1 line
Ammar Faizi
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 7 lines · Ammar Faizi
00000000000010b1<memset>:10b1: 48 89 f0 mov %rsi,%rax 10b4: 48 89 d1 mov %rdx,%rcx 10b7: 48 89 fa mov %rdi,%rdx 10ba: f3 aa rep stos %al,%es:(%rdi) 10bc: 48 89 d0 mov %rdx,%rax 10bf: c3 ret
Just a small idea to shrink this more, "mov %rdi, %rdx" and "mov %rdx, %rax" can be replaced with "push %rdi" and "pop %rax" (they are just a byte). So we can save 4 bytes more.
0000000000001500 <memset>:
1500: 48 89 f0 mov %rsi,%rax
1503: 48 89 d1 mov %rdx,%rcx
1506: 57 push %rdi
1507: f3 aa rep stos %al,%es:(%rdi)
1509: 58 pop %rax
150a: c3 retBut I know you don't like it because it costs extra memory access.
-- Viro
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 5 lines · Alviro Iskandar Setiawan
Just a small idea to shrink this more, "mov %rdi, %rdx" and "mov %rdx, %rax" can be replaced with "push %rdi" and "pop %rax" (they are just a byte). So we can save 4 bytes more.
0000000000001500 <memset>:
Quoted 8 lines
1500: 48 89 f0 mov %rsi,%rax 1503: 48 89 d1 mov %rdx,%rcx 1506: 57 push %rdi 1507: f3 aa rep stos %al,%es:(%rdi) 1509: 58 pop %rax 150a: c3 retBut I know you don't like it because it costs extra memory access.
Yes, that's an extra memory access. But I believe it doesn't hurt someone targetting -Os. In many cases, the compilers use push/pop to align the stack before a 'call' instruction. If they want to avoid extra memory access, they could have used "subq $8, %rsp" and "addq $8, %rsp".
For example: https://godbolt.org/z/Tzc1xWGEn
C code:
```
int fx(int b);
int fy(int a)
{
return 1 + fx(a);
}
```Targetting -Os, both clang and gcc compile it to:
```
fy:
pushq %rax
call fx
popq %rdx
incl %eax
ret
```Targetting -O2:
```
fy:
subq $8, %rsp
call fx
addq $8, %rsp
addl $1, %eax
ret
```That pushq/popq pair doesn't actually preserve anything; it's just to align the %rsp at 16 bytes on 'call'. IOW, sometimes having extra memory access to get a smaller code size is acceptable.
Signature · 1 line
Ammar Faizi
Willy Tarreau
maintainerRe: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 13 lines · Ammar Faizi
Quoted 12 lines · Alviro Iskandar Setiawan
Just a small idea to shrink this more, "mov %rdi, %rdx" and "mov %rdx, %rax" can be replaced with "push %rdi" and "pop %rax" (they are just a byte). So we can save 4 bytes more.
0000000000001500 <memset>:
1500: 48 89 f0 mov %rsi,%rax 1503: 48 89 d1 mov %rdx,%rcx 1506: 57 push %rdi 1507: f3 aa rep stos %al,%es:(%rdi) 1509: 58 pop %rax 150a: c3 ret
Quoted 6 lines
Quoted 1 line
But I know you don't like it because it costs extra memory access.
Yes, that's an extra memory access. But I believe it doesn't hurt someone targetting -Os. In many cases, the compilers use push/pop to align the stack before a 'call' instruction. If they want to avoid extra memory access, they could have used "subq $8, %rsp" and "addq $8, %rsp".
Then "xchg %esi, %eax" is just one byte with no memory access ;-)
Willy
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 1 line · Willy Tarreau
Then "xchg %esi, %eax" is just one byte with no memory access ;-)
Perfect!
Now I got this, shorter than "movl %esi, %eax":
```
0000000000001500 <memset>:
1500: 96 xchg %eax,%esi
1501: 48 89 d1 mov %rdx,%rcx
1504: 57 push %rdi
1505: f3 aa rep stos %al,%es:(%rdi)
1507: 58 pop %rax
1508: c3 ret
```Unfortunately, the xchg trick doesn't yield smaller machine code for %rdx, %rcx. Lol.
Signature · 1 line
Ammar Faizi
Willy Tarreau
maintainerRe: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 16 lines · Ammar Faizi
Quoted 1 line · Willy Tarreau
Then "xchg %esi, %eax" is just one byte with no memory access ;-)
Perfect!
Now I got this, shorter than "movl %esi, %eax":
``` 0000000000001500 <memset>: 1500: 96 xchg %eax,%esi 1501: 48 89 d1 mov %rdx,%rcx 1504: 57 push %rdi 1505: f3 aa rep stos %al,%es:(%rdi) 1507: 58 pop %rax 1508: c3 ret ```
Quoted 2 lines
Unfortunately, the xchg trick doesn't yield smaller machine code for %rdx, %rcx. Lol.
Normal, that's because historically "xchg ax, regX" was a single-byte 0x9X on 8086, then it turned to 32-bit keeping the same encoding, like many instructions (note that NOP is encoded as xchg ax,ax). It remains short when you can sacrifice the other register, or restore it later using yet another xchg. For rcx/rdx a push/pop could do it as they should also be a single-byte 0x5X even in long mode unless I'm mistaken. Thus if you absolutely want to squeeze that 9th byte to end up with a 8-byte function you could probably do:
xchg %eax, %esi 1
push %rdx 1
pop %rcx 1
push %rdi 1
rep movsb 2
pop %rax 1
ret 1
------------- Total: 8 bytes :-)Willy
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 9 lines · Willy Tarreau
Normal, that's because historically "xchg ax, regX" was a single-byte 0x9X on 8086, then it turned to 32-bit keeping the same encoding, like many instructions (note that NOP is encoded as xchg ax,ax). It remains short when you can sacrifice the other register, or restore it later using yet another xchg. For rcx/rdx a push/pop could do it as they should also be a single-byte 0x5X even in long mode unless I'm mistaken. Thus if you absolutely want to squeeze that 9th byte to end up with a 8-byte function you could probably do:
Quoted 8 lines
xchg %eax, %esi 1
push %rdx 1
pop %rcx 1
push %rdi 1
rep movsb 2 [sic]
pop %rax 1
ret 1
------------- Total: 8 bytes :-)Fun!
We're not doing a code golf game, though. So, I think I will leave the "mov %rdx, %rcx" as is. Otherwise, I would be tempted to do that all over the place.
Signature · 1 line
Ammar Faizi
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 9 lines · Ammar Faizi
Quoted 8 lines · Willy Tarreau
xchg %eax, %esi 1 push %rdx 1 pop %rcx 1 push %rdi 1 rep movsb 2 [sic] pop %rax 1 ret 1 ------------- Total: 8 bytes :-)
That's beautiful!
-- Viro
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
In reply to Ammar Faizitools/include/nolibc/arch-x86_64.h __asm__ ( · line 214
Quoted 9 lines · Ammar Faizi
+".section .text.nolibc_memset\n"
+".weak memset\n"
+"memset:\n"tools/include/nolibc/arch-x86_64.h +6
-0+"movq %rsi, %rax\n" +"movq %rdx, %rcx\n" +"movq %rdi, %rdx\n" +"rep stosb\n" +"movq %rdx, %rax\n" +"retq\n"
The first instruction could be:
movl %esi, %eax
That's smaller. Also, the second argument of memset() is an int anyway, so there is no need to have a full 64-bit copy of %rsi in %rax.
-- Viro
Re: [RFC PATCH v1 2/5] tools/nolibc: x86-64: Use `rep stosb` for `memset()`
Quoted 7 lines · Alviro Iskandar Setiawan
The first instruction could be:
movl %esi, %eax
That's smaller. Also, the second argument of
memset()is an int anyway, so there is no need to have a full 64-bit copy of %rsi in %rax.
Agree, noted.
Signature · 1 line
Ammar Faizi
RFC PATCH 3/5 tools/nolibc: x86-64: Use `rep cmpsb` for `memcmp()`
In reply to Ammar FaiziSimplify memcmp() on the x86-64 arch.
The x86-64 arch has a 'rep cmpsb' instruction, which can be used to implement the memcmp() function.
%rdi = source 1
%rsi = source 2
%rcx = length
--- tools/include/nolibc/arch-x86_64.h | 19 +++++++++++++++++++ tools/include/nolibc/string.h | 2 ++ 2 files changed, 21 insertions(+)
tools/include/nolibc/arch-x86_64.h +19 -0
@@ -214,4 +214,23 @@ __asm__ ("retq\n" ); +#define NOLIBC_ARCH_HAS_MEMCMP +static int memcmp (const void *s1,const void *s2,size_t n) +{ +const unsigned char *p1 = s1; +const unsigned char *p2 = s2; + +if (!n) +return 0 ; + + __asm__volatile ( +"rep cmpsb" + :"+D" (p2),"+S" (p1),"+c" (n) + :"m" (*(const unsigned char (*)[n])s1), +"m" (*(const unsigned char (*)[n])s2) + ); + +return p1[-1 ] - p2[-1 ]; +} +#endif /* _NOLIBC_ARCH_X86_64_H */
tools/include/nolibc/string.h +2 -0
@@ -15,6 +15,7 @@ static void *malloc(size_t len);* As much as possible, please keep functions alphabetically sorted. */ +#ifndef NOLIBC_ARCH_HAS_MEMCMP static __attribute__((unused))int memcmp (const void *s1,const void *s2,size_t n) {
@@ -26,6 +27,7 @@ int memcmp(const void *s1, const void *s2, size_t n) }return c1; } +#endif /* #ifndef NOLIBC_ARCH_HAS_MEMCMP */ static __attribute__((unused))void *_nolibc_memcpy_up (void *dst,const void *src,size_t len)
Signature · 1 line
Ammar Faizi
Willy Tarreau
maintainerRe: [RFC PATCH v1 3/5] tools/nolibc: x86-64: Use `rep cmpsb` for `memcmp()`
Quoted 31 lines · Ammar Faizi
Simplify
memcmp()on the x86-64 arch.The x86-64 arch has a 'rep cmpsb' instruction, which can be used to implement the
memcmp()function.%rdi = source 1
%rsi = source 2
%rcx = lengthSigned-off-by Ammar Faizi <[email protected]>--- tools/include/nolibc/arch-x86_64.h | 19 +++++++++++++++++++ tools/include/nolibc/string.h | 2 ++ 2 files changed, 21 insertions(+)tools/include/nolibc/arch-x86_64.h +8
-0@@ -214,4 +214,23 @@ __asm__ ("retq\n" ); +#define NOLIBC_ARCH_HAS_MEMCMP +static int memcmp (const void *s1,const void *s2,size_t n) +{ +const unsigned char *p1 = s1; +const unsigned char *p2 = s2; + +if (!n) +return 0 ;
tools/include/nolibc/arch-x86_64.h __asm__ ( · line 234
Quoted 10 lines
tools/include/nolibc/arch-x86_64.h +10
-0+ + __asm__volatile ( +"rep cmpsb" + :"+D" (p2),"+S" (p1),"+c" (n) + :"m" (*(const unsigned char (*)[n])s1), +"m" (*(const unsigned char (*)[n])s2) + ); + +return p1[-1 ] - p2[-1 ]; +}
Out of curiosity, given that you implemented the 3 other ones directly in an asm statement, is there a particular reason this one mixes a bit of C and asm ? It would probably be something around this, in the same vein:
memcmp:
xchg %esi,%eax // source1
mov %rdx,%rcx // count
rep cmpsb // source2 in rdi; sets ZF on equal, CF if src1<src2
seta %al // 0 if src2 <= src1, 1 if src2 > src1
sbb $0, %al // 0 if src2 == src1, -1 if src2 < src1, 1 if src2 > src1
movsx %al, %eax // sign extend to %eaxret
Note that the output logic could have to be revisited, I'm not certain but at first glance it looks valid.
Regards,
Willy
Re: [RFC PATCH v1 3/5] tools/nolibc: x86-64: Use `rep cmpsb` for `memcmp()`
Quoted 3 lines · Willy Tarreau
Out of curiosity, given that you implemented the 3 other ones directly in an asm statement, is there a particular reason this one mixes a bit of C and asm ?
Because this one maybe unused. The other are explicitly exported.
Quoted 9 lines
It would probably be something around this, in the same vein:
memcmp:
xchg %esi,%eax // source1 mov %rdx,%rcx // count rep cmpsb // source2 in rdi; sets ZF on equal, CF if src1<src2 seta %al // 0 if src2 <= src1, 1 if src2 > src1 sbb $0, %al // 0 if src2 == src1, -1 if src2 < src1, 1 if src2 > src1 movsx %al, %eax // sign extend to %eax
Quoted 4 lines
ret
Note that the output logic could have to be revisited, I'm not certain but at first glance it looks valid.
After thinking about this more, I think I'll drop the memcmp() patch because it will prevent optimization when comparing a small value.
For example, without __asm__:
memcmp(var, "abcd", 4);
may compile to:
cmpl $0x64636261, %reg
...something...But with __asm__, the compiler can't do that. Thus, it's not worth optimizing the memcmp() in this case.
Signature · 1 line
Ammar Faizi
Willy Tarreau
maintainerRe: [RFC PATCH v1 3/5] tools/nolibc: x86-64: Use `rep cmpsb` for `memcmp()`
Quoted 6 lines · Ammar Faizi
Quoted 3 lines · Willy Tarreau
Out of curiosity, given that you implemented the 3 other ones directly in an asm statement, is there a particular reason this one mixes a bit of C and asm ?
Because this one maybe unused. The other are explicitly exported.
Makes sense, indeed.
Quoted 21 lines
Quoted 9 lines
It would probably be something around this, in the same vein:
memcmp:
xchg %esi,%eax // source1 mov %rdx,%rcx // count rep cmpsb // source2 in rdi; sets ZF on equal, CF if src1<src2 seta %al // 0 if src2 <= src1, 1 if src2 > src1 sbb $0, %al // 0 if src2 == src1, -1 if src2 < src1, 1 if src2 > src1 movsx %al, %eax // sign extend to %eaxQuoted 4 lines
ret
Note that the output logic could have to be revisited, I'm not certain but at first glance it looks valid.
After thinking about this more, I think I'll drop the
memcmp()patch because it will prevent optimization when comparing a small value.For example, without
__asm__:memcmp(var, "abcd", 4);
Quoted 7 lines
may compile to:
cmpl $0x64636261, %reg ...something...But with
__asm__, the compiler can't do that. Thus, it's not worth optimizing thememcmp()in this case.
Ah you're totally right!
Willy
Re: [RFC PATCH v1 3/5] tools/nolibc: x86-64: Use `rep cmpsb` for `memcmp()`
Quoted 10 lines · Willy Tarreau
Quoted 9 lines · Ammar Faizi
After thinking about this more, I think I'll drop the
memcmp()patch because it will prevent optimization when comparing a small value.For example, without
__asm__:memcmp(var, "abcd", 4);may compile to:
Quoted 7 lines
Quoted 5 lines
cmpl $0x64636261, %reg ...something...But with
__asm__, the compiler can't do that. Thus, it's not worth optimizing thememcmp()in this case.Ah you're totally right!
So, it turns out that such assumption is wrong. The compiler cannot optimize the current memcmp() into that. I just posted a question on SO:
Given:
```
bool test_data(void *data)
{
return memcmp(data, "abcd", 4) == 0;
}
```The result when using default the <string.h> memcmp (good):
```
test_data:
cmpl $1684234849, (%rdi)
sete %al
ret
```The result when using nolibc memcmp() (bad):
```
test_data:
cmpb $97, (%rdi)
jne .L5
cmpb $98, 1(%rdi)
jne .L5
cmpb $99, 2(%rdi)
jne .L5
cmpb $100, 3(%rdi)
sete %al
ret
.L5:
xorl %eax, %eax
ret
```This is because apart from the input length, the current nolibc memcmp() must stop comparing the next byte if it finds a non-match byte. Imagine what happens if we call:
```
char xstr[] = {'a', 'b', 'x'};
test_data(x);
```In that case, the compiler may read past xstr if it uses a dword cmp, it can also lead to segfault in particular circumstances using a dword cmp.
What the current nolibc memcmp() does from the C language view:
1) Compare one byte at a time.
2) Must stop comparing the next byte if it finds a non-match byte.
Because point (2) comes in, the compiler is not allowed to optimize nolibc memcmp() into a wider load; otherwise, it may hit a segfault. That also means it cannot vectorize the memcmp() loop.
On the other hand, memcpy() and memset() don't have such a restriction so they can vectorize.
The real memcmp() assumes that both sources are at least n length in size, allowing for a wider load. The current nolibc memcmp() implementation doesn't reflect that assumption in the C code.
IOW, the real built-in memcmp() is undefined behavior for this code:
```
char x = 'q';
return memcmp(&x, "abcd", 4);
```but the current nolibc memcmp() is well-defined behavior (well, must be, as what the C code reflects).
We can improve nolibc memcmp() by casting the sources to a wider type like (ulong, uint, ushort). But that's another story for another RFC patchset.
Signature · 1 line
Ammar Faizi
RE: [RFC PATCH v1 3/5] tools/nolibc: x86-64: Use `rep cmpsb` for `memcmp()`
In reply to Willy TarreauFrom: Willy Tarreau
Quoted 50 lines
Sent: 30 August 2023 22:27
Quoted 31 lines · Ammar Faizi
Simplify
memcmp()on the x86-64 arch.The x86-64 arch has a 'rep cmpsb' instruction, which can be used to implement the
memcmp()function.%rdi = source 1
%rsi = source 2
%rcx = lengthSigned-off-by Ammar Faizi <[email protected]>--- tools/include/nolibc/arch-x86_64.h | 19 +++++++++++++++++++ tools/include/nolibc/string.h | 2 ++ 2 files changed, 21 insertions(+)tools/include/nolibc/arch-x86_64.h +8
-0@@ -214,4 +214,23 @@ __asm__ ("retq\n" ); +#define NOLIBC_ARCH_HAS_MEMCMP +static int memcmp (const void *s1,const void *s2,size_t n) +{ +const unsigned char *p1 = s1; +const unsigned char *p2 = s2; + +if (!n) +return 0 ;tools/include/nolibc/arch-x86_64.h __asm__ ( · line 234
Quoted 10 lines
tools/include/nolibc/arch-x86_64.h +10
-0+ + __asm__volatile ( +"rep cmpsb" + :"+D" (p2),"+S" (p1),"+c" (n) + :"m" (*(const unsigned char (*)[n])s1), +"m" (*(const unsigned char (*)[n])s2) + ); + +return p1[-1 ] - p2[-1 ]; +}Out of curiosity, given that you implemented the 3 other ones directly in an asm statement, is there a particular reason this one mixes a bit of C and asm ? It would probably be something around this, in the same vein:
Quoted 2 lines
memcmp:
xchg %esi,%eax // source1
Aren't the arguments in %rdi, %rsi and %rdx so you only need to move the count (below) ?
(Looks like you copied memchr())
David
Quoted 5 lines
mov %rdx,%rcx // count
rep cmpsb // source2 in rdi; sets ZF on equal, CF if src1<src2
seta %al // 0 if src2 <= src1, 1 if src2 > src1
sbb $0, %al // 0 if src2 == src1, -1 if src2 < src1, 1 if src2 > src1
movsx %al, %eax // sign extend to %eaxQuoted 7 lines
ret
Note that the output logic could have to be revisited, I'm not certain but at first glance it looks valid.
Regards,
Willy
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
RFC PATCH 4/5 tools/nolibc: string: Remove the `_nolibc_memcpy_down()` function
In reply to Ammar FaiziThis nolibc internal function is not used. Delete it. It was probably supposed to handle memmove(), but today the memmove() has its own implementation.
--- tools/include/nolibc/string.h | 10 ---------- 1 file changed, 10 deletions(-)
tools/include/nolibc/string.h +0 -10
@@ -41,16 +41,6 @@ void *_nolibc_memcpy_up(void *dst, const void *src, size_t len)return dst; } -static __attribute__((unused)) -void *_nolibc_memcpy_down (void *dst,const void *src,size_t len) -{ -while (len) { - len--; - ((char *)dst)[len] = ((const char *)src)[len]; - } -return dst; -} -#ifndef NOLIBC_ARCH_HAS_MEMMOVE /* might be ignored by the compiler without -ffreestanding, then found as * missing.
Signature · 1 line
Ammar Faizi
Willy Tarreau
maintainerRe: [RFC PATCH v1 4/5] tools/nolibc: string: Remove the `_nolibc_memcpy_down()` function
Quoted 3 lines · Ammar Faizi
This nolibc internal function is not used. Delete it. It was probably supposed to handle
memmove(), but today thememmove()has its own implementation.
Yeah good catch for these two, I'm pretty sure as well they were used for memmove().
Thanks!
Willy
RFC PATCH 5/5 tools/nolibc: string: Remove the `_nolibc_memcpy_up()` function
In reply to Ammar FaiziThis function is only called by memcpy(), there is no real reason to have this wrapper. Delete this function and move the code to memcpy() directly.
--- tools/include/nolibc/string.h | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-)
tools/include/nolibc/string.h +7 -13
@@ -29,18 +29,6 @@ int memcmp(const void *s1, const void *s2, size_t n) }#endif /* #ifndef NOLIBC_ARCH_HAS_MEMCMP */ -static __attribute__((unused)) -void *_nolibc_memcpy_up (void *dst,const void *src,size_t len) -{ -size_t pos =0 ; - -while (pos < len) { - ((char *)dst)[pos] = ((const char *)src)[pos]; - pos++; - } -return dst; -} -#ifndef NOLIBC_ARCH_HAS_MEMMOVE /* might be ignored by the compiler without -ffreestanding, then found as * missing.
@@ -72,7 +60,13 @@ void *memmove(void *dst, const void *src, size_t len) __attribute__((weak,unused,section (".text.nolibc_memcpy" )))void *memcpy (void *dst,const void *src,size_t len) { -return _nolibc_memcpy_up (dst, src, len); +size_t pos =0 ; + +while (pos < len) { + ((char *)dst)[pos] = ((const char *)src)[pos]; + pos++; + } +return dst; }#endif /* #ifndef NOLIBC_ARCH_HAS_MEMCPY */
Signature · 1 line
Ammar Faizi
Willy Tarreau
maintainerHi Ammar,
Quoted 5 lines · Ammar Faizi
Hi Willy,
This is an RFC patchset for nolibc x86-64 string functions. There are 5 patches in this series.
Quoted 7 lines
## Patch 1-3: Use
rep movsb,rep stosb, andrep cmpsbfor:
-memcpy()andmemmove()
-memset()
-memcmp()
respectively. They can simplify the generated ASM code.Patch 4 and 5 are not related, just a small cleanup.
So overall I'm fine with this, I think it's reasonable. As you said we're not trying to chase the very last byte, but for such functions it's also nice if they can remain small. Some of them might even benefit from being inlined by the way (in this case they'd rather move to C functions with an asm() statement), because the call instruction and the register moves or spilling code will generally be larger than the functions themselves. That might be worth checking. Ah no, we cannot because some of them are called from libgcc and friends. Or we may need to mark them inline and weak without static, I'm not sure how well that works.
Please just let me know if you intend to change a few things based on previous comments, and also this memcmp() stuff that's both C and asm.
Thanks!
Willy
From: Ammar Faizi <[email protected]>
Quoted 11 lines
Sent: 30 August 2023 14:57
This is an RFC patchset for nolibc x86-64 string functions. There are 5 patches in this series.
## Patch 1-3: Use
rep movsb,rep stosb, andrep cmpsbfor:
-memcpy()andmemmove()
-memset()
-memcmp()
respectively. They can simplify the generated ASM code.
...
Quoted 11 lines
After this series:
```
000000000000140a<memmove>:140a: 48 89 f8 mov %rdi,%rax 140d: 48 89 d1 mov %rdx,%rcx 1410: 48 8d 7c 0f ff lea -0x1(%rdi,%rcx,1),%rdi 1415: 48 8d 74 0e ff lea -0x1(%rsi,%rcx,1),%rsi 141a: fd std 141b: f3 a4 rep movsb %ds:(%rsi),%es:(%rdi) 141d: fc cld 141e: c3 ret
Isn't that completely broken?
You need to select between forwards and backwards moves. Since forwards moves are preferred it is best to do
if (dst - src < len)
backards_copy()
else
formwards_copy()
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
Willy Tarreau
maintainerQuoted 27 lines · David Laight
From: Ammar Faizi <[email protected]>
Quoted 11 lines
Sent: 30 August 2023 14:57
This is an RFC patchset for nolibc x86-64 string functions. There are 5 patches in this series.
## Patch 1-3: Use
rep movsb,rep stosb, andrep cmpsbfor:
-memcpy()andmemmove()
-memset()
-memcmp()
respectively. They can simplify the generated ASM code....
Quoted 11 lines
After this series:
```
000000000000140a<memmove>:140a: 48 89 f8 mov %rdi,%rax 140d: 48 89 d1 mov %rdx,%rcx 1410: 48 8d 7c 0f ff lea -0x1(%rdi,%rcx,1),%rdi 1415: 48 8d 74 0e ff lea -0x1(%rsi,%rcx,1),%rsi 141a: fd std 141b: f3 a4 rep movsb %ds:(%rsi),%es:(%rdi) 141d: fc cld 141e: c3 retIsn't that completely broken?
Quoted 8 lines
You need to select between forwards and backwards moves. Since forwards moves are preferred it is best to do
if (dst - src < len)
backards_copy()
else
formwards_copy()David
You're completely right indeed, reminds me about the copy_up/copy_down that were not used anymore :-)
Willy
Quoted 10 lines · Willy Tarreau
Quoted 9 lines · David Laight
Isn't that completely broken?
You need to select between forwards and backwards moves. Since forwards moves are preferred it is best to do
if (dst - src < len)
backards_copy()
else
formwards_copy()
Quoted 4 lines
Quoted 1 line
David
You're completely right indeed, reminds me about the copy_up/copy_down that were not used anymore :-)
I'm an idiot, will fix that. Another attempt as suggested below:
__asm__ (
".section .text.nolibc_memmove\n"
".weak memmove\n"
"memmove:\n"
" movq %rdx, %rcx\n" " movq %rdi, %rdx\n" " movq %rdi, %rax\n" " subq %rsi, %rdx\n" " cmpq %rcx, %rdx\n" " jnb .Lforward_copy\n" " leaq -1(%rdi, %rcx, 1), %rdi\n" " leaq -1(%rsi, %rcx, 1), %rsi\n" " std\n" ".Lforward_copy:\n" " rep movsb\n" " cld\n" " ret\n"
);
Signature · 1 line
Ammar Faizi
From: Ammar Faizi
Quoted 1 line
Sent: 01 September 2023 14:06
...
Quoted 5 lines
Quoted 2 lines
You're completely right indeed, reminds me about the copy_up/copy_down that were not used anymore :-)
I'm an idiot, will fix that. Another attempt as suggested below:
Quoted 7 lines
__asm__(
".section .text.nolibc_memmove\n"
".weak memmove\n"
"memmove:\n"" movq %rdx, %rcx\n" " movq %rdi, %rdx\n" " movq %rdi, %rax\n"
You seem to have confused yourself about whether you are using %eax or %edx.
Quoted 3 lines
" subq %rsi, %rdx\n" " cmpq %rcx, %rdx\n" " jnb .Lforward_copy\n"
I think I'd fall through to the forwards copy
and not worry about replicating the 'reps movsb' and 'ret'. IIRC 'cld' can be slow as well.
Quoted 11 lines
" leaq -1(%rdi, %rcx, 1), %rdi\n" " leaq -1(%rsi, %rcx, 1), %rsi\n" " std\n" ".Lforward_copy:\n" " rep movsb\n" " cld\n" " ret\n");
--
Ammar Faizi
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
Quoted 2 lines · David Laight
From: Ammar Faizi
Quoted 1 line
Sent: 01 September 2023 14:06
...
Quoted 9 lines
Quoted 7 lines
__asm__(
".section .text.nolibc_memmove\n"
".weak memmove\n"
"memmove:\n"" movq %rdx, %rcx\n" " movq %rdi, %rdx\n" " movq %rdi, %rax\n"You seem to have confused yourself about whether you are using %eax or %edx.
What do you mean? They're all 64-bit pointers.
What I know is that the %rdx will be clobbered by "subq %rsi, %rdx" below and the %rax should be return value. That's why I copy the %rdi twice. memmove() returns the dst pointer. Did I miss something?
Quoted 7 lines
Quoted 3 lines
" subq %rsi, %rdx\n" " cmpq %rcx, %rdx\n" " jnb .Lforward_copy\n"I think I'd fall through to the forwards copy
and not worry about replicating the 'reps movsb' and 'ret'. IIRC 'cld' can be slow as well.
Alright, I will avoid cld for the forward copy.
Quoted 8 lines
Quoted 8 lines
" leaq -1(%rdi, %rcx, 1), %rdi\n" " leaq -1(%rsi, %rcx, 1), %rsi\n" " std\n" ".Lforward_copy:\n" " rep movsb\n" " cld\n" " ret\n");
Signature · 1 line
Ammar Faizi
From: Ammar Faizi
Quoted 1 line
Sent: 01 September 2023 15:42
...
Quoted 7 lines
Quoted 5 lines
Quoted 3 lines
" movq %rdx, %rcx\n" " movq %rdi, %rdx\n" " movq %rdi, %rax\n"You seem to have confused yourself about whether you are using %eax or %edx.
What do you mean? They're all 64-bit pointers.
%ax, %eax, %rax - what is the difference :-)
Quoted 3 lines
What I know is that the %rdx will be clobbered by "subq %rsi, %rdx" below and the %rax should be return value. That's why I copy the %rdi twice.
memmove()returns the dst pointer. Did I miss something?
I'd forgotten about the (stupid) return value.
I'm pretty sure it is an accident from the original pdp-11 implementation from the days before C had an explicit 'return' statement.
(The pdp-11 I used ran RSX/11M - so had a Fortran compiler not a C one.)
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
Quoted 7 lines · David Laight
I'd forgotten about the (stupid) return value.
I'm pretty sure it is an accident from the original pdp-11 implementation from the days before C had an explicit 'return' statement.
(The pdp-11 I used ran RSX/11M - so had a Fortran compiler not a C one.)
You're old. I did not exist in that era. And my parents were still young :-)
Signature · 1 line
Ammar Faizi