Bug 99559 - LTO with -Os -ffreestanding -nodefaultlibs may generate call to memcpy, but fail linking even though memcpy is defined
Summary: LTO with -Os -ffreestanding -nodefaultlibs may generate call to memcpy, but f...
Status: RESOLVED DUPLICATE of bug 58203
Alias: None
Product: gcc
Classification: Unclassified
Component: lto (show other bugs)
Version: 10.2.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: link-failure, lto
Depends on:
Blocks:
 
Reported: 2021-03-12 10:06 UTC by Marek Behun
Modified: 2021-03-12 18:15 UTC (History)
6 users (show)

See Also:
Host:
Target: aarch64
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments
test.c (482 bytes, text/x-csrc)
2021-03-12 10:06 UTC, Marek Behun
Details

Note You need to log in before you can comment on or make changes to this bug.
Description Marek Behun 2021-03-12 10:06:29 UTC
Created attachment 50372 [details]
test.c

When compiling for target where the assignment operator

  *dst = *src;

will generate a call to memcpy (for example aarch64), and when also using compile flags

  -ffreestanding -Os -flto

and link flags

  -nodefaultlibs -nostartfiles

the linking will fail with

  undefined reference to `memcpy'

even if memcpy is defined in the source.

The memcpy is optimized away, even though it is used by the = operator. It needs to be declared with __attribute__((used)) to not be optimized away.

What is interesting is that if the memcpy function is used explicitly, the compilation may still fail with -Os, because the code will be inlined.

If memcpy is used explicitly multiple times, it may be generated with symbol name
  memcpy.constprop.0.isra.0
or
  memcpy.isra.0
depending on whether the arguments passed are the same or different.

But the linking fill still fail, because the assignment operator will generate a call to memcpy, and this symbol is not defined, only memcpy.isra.0 or memcpy.constprop.0.isra.0 is.

I discovered this recently while trying to make U-Boot compile with LTO. We have solved it by declaring "memcmp", "memset", "memcpy" and "memmove" with attribute used, since according to GCC man page, calls to this functions may still be done when -nodefaultlibs is used.
Comment 1 Richard Biener 2021-03-12 13:20:55 UTC
Yeah, we do remove unused (as in unused from the source) memcpy implementations early but then introduce uses ourselves.

I suppose we should avoid doing that with -ffreestanding, thus basically add
the used attribute on a select number of definitions automatically with this option.

I wonder for example whether a static definition of memcpy would need to be
preserved since I think this isn't really special to LTO.

Joseph?  Honza?
Comment 2 Andrew Pinski 2021-03-12 18:15:21 UTC
This is a dup of bug 58203.

*** This bug has been marked as a duplicate of bug 58203 ***