How to compile a C implementation of memcpy with gcc?

Rich Felker
Fri Aug 2 21:34:00 GMT 2013

On Fri, Aug 02, 2013 at 05:12:19PM +0400, Alexander Monakov wrote:
> Hello,
> On Sun, 28 Jul 2013, Rich Felker wrote:
> >     Is there any reliable way, across GCC versions, to write memcpy in
> >     pure C without having to worry that the compiler will translate it
> >     into a function that calls itself?
> Using "-ffreestanding" flag should be the way to achieve that.  The fact that
> it does not have that effect is an extremely unfortunate bug in all recently
> released versions of GCC.  I think it can be fixed, but I don't know how hard
> that would be.  See comment 8 in PR 56888.

For the time being, it seems to me that -ffreestanding should just
imply -fno-tree-loop-distribute-patterns. Couldn't that even be done
at the specfile level? That will fix the issue except for the struct
copying issue in the ARM (and perhaps other archs) codegen.

> You can work around this bug by not using optimizations above -O2 and not
> using structures, but I understand if you say that this is not a good
> workaround.

Most of the optimizations that do anything worthwhile begin at -O3, so
yes, this is not a good workaround. For now, we're adding
-fno-tree-loop-distribute-patterns via configure if the compiler
supports it, and applying this just to the affected files, but I don't
want to play whack-a-mole with adding options every time GCC breaks

As for structures, it's not a huge issue. My hope was just that, by
copying as struct { char data[16]; } or similar, I could get the
compiler to generate something not-entirely-horrible for the
misaligned copy case. In fact, for x86 it did rather well, but for ARM
it generated a self-referential implementation. I'd rather GCC _work_
here, even if generating very poor performance, but from a practical
standpoint I'm just going to drop this strategy for the C fallback
code since it doesn't seem likely to produce good results.

> I believe that people on freenode/#gcc who claimed that -ffreestanding should
> not have such effect are in error.  Could you send me the chat log privately?

I thought I'd saved it before restarting my client, but I can't seem
to find it, so I think I must have forgotten to. Sorry.

> Also note that memset should also have this problem, not just memcpy.

Yes, we've hit the problem with memset now too...


More information about the Gcc-help mailing list