Missing optimization: mempcpy(3) vs memcpy(3)

Alejandro Colomar alx.manpages@gmail.com
Fri Dec 9 17:11:17 GMT 2022


Hi!

I expect mempcpy(3) to be at least as fast as memcpy(3), since it performs the 
same operations, with the exception that mempcpy(3) returns something useful (as 
opposed to memcpy(3), which could perfectly return void), and in fact something 
more likely to be in cache, if the copy is performed upwards.

The following two files are alternative implementations of a function, each one 
written in terms of one of memcpy(3) and mempcpy(3):


$ cat usts2stp1.c
     #include <string.h>

     struct ustr_s {
     	size_t  len;
     	char    *ustr;
     };

     char *
     usts2stp(char *restrict dst, const struct ustr_s *restrict src)
     {
     	memcpy(dst, src->ustr, src->len);
     	dst[src->len] = '\0';

     	return dst + src->len;
     }

$ cat usts2stp3.c
     #define _GNU_SOURCE
     #include <string.h>

     struct ustr_s {
     	size_t  len;
     	char    *ustr;
     };

     char *
     usts2stp(char *restrict dst, const struct ustr_s *restrict src)
     {
     	char *end;

     	end = mempcpy(dst, src->ustr, src->len);
     	*end = '\0';

     	return end;
     }


I expect the compiler to be knowledgeable enough to call whatever is fastest, 
whatever it is, but be consistent in both cases.  However, here are the results:


$ cc -Wall -Wextra -O3 -S usts2stp*.c
$ diff -u usts2stp[13].s
--- usts2stp1.s	2022-12-09 18:06:11.708367061 +0100
+++ usts2stp3.s	2022-12-09 18:06:11.740366451 +0100
@@ -1,4 +1,4 @@
-	.file	"usts2stp1.c"
+	.file	"usts2stp3.c"
  	.text
  	.p2align 4
  	.globl	usts2stp
@@ -6,16 +6,13 @@
  usts2stp:
  .LFB0:
  	.cfi_startproc
-	pushq	%rbx
+	subq	$8, %rsp
  	.cfi_def_cfa_offset 16
-	.cfi_offset 3, -16
-	movq	(%rsi), %rbx
+	movq	(%rsi), %rdx
  	movq	8(%rsi), %rsi
-	movq	%rbx, %rdx
-	call	memcpy@PLT
-	leaq	(%rax,%rbx), %rax
+	call	mempcpy@PLT
  	movb	$0, (%rax)
-	popq	%rbx
+	addq	$8, %rsp
  	.cfi_def_cfa_offset 8
  	ret
  	.cfi_endproc


The code with memcpy(3) seems to be worse (assuming both calls to be 
equivalent).  Shouldn't GCC produce the same code for both implementations?

Cheers,

Alex


-- 
<http://www.alejandro-colomar.es/>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature
Type: application/pgp-signature
Size: 833 bytes
Desc: OpenPGP digital signature
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20221209/d19f4168/attachment.sig>


More information about the Gcc mailing list