Merging identical functions in GCC
Mark Mitchell
mark@codesourcery.com
Fri Sep 15 22:07:00 GMT 2006
Laurent GUERBY wrote:
> On Fri, 2006-09-15 at 13:54 -0700, Ian Lance Taylor wrote:
>> Laurent GUERBY <laurent@guerby.net> writes:
>>> For code sections (I assume read-only), isn't the linker always able to
>>> merge identical ones? What can the compiler do better than the linker?
>> The linker can't merge just any identical code section, it can only
>> merge code sections where that is permitted. For example, consider:
>>
>> int foo() { return 0; }
>> int bar() { return 0; }
>> int quux(int (*pfn)()) { return pfn == &foo; }
>>
>> Compile with -ffunction-sections. If the linker merges sections, that
>> program will break.
>
> Indeed.
>
> The compiler could merge (or mark for linker) static functions whose
> address is not taken, those are safe against this use.
I wrote an tech report for a company where I used to work about this
optimization about 10 years ago, in the context of C++ templates.
(Unfortunately, it was internal-only, so I don't have a copy. Or,
perhaps fortunately; I don't remember if I said stupid things...)
Anyhow, I think that a combination of compiler/linker help and
programmer help are useful. There are some cases where you can do this
automatically, and others where you might need programmer help. Just as
-ffast-math is useful, so might -fmerge-functions or
__attribute__((mergeable)), even if that resulted in non-standard
handling of function pointers.
We could certainly do this in the context of LTO. It might be a nice
trick to do it in the general GCC back end, and then it would work both
for a single module and for LTO; both cases are useful. It's also
possible to do some of this in the front end; the paper I wrote talked
about how you could notice that a particular template did not make any
particular use of the type of the argument (i.e,. that "T*" was treated
the same, independent of "T").
I think that *all* of these places might be useful eventually: in the
front end, the back end, and the linker. I'd be happy to start
anywhere. :-)
--
Mark Mitchell
CodeSourcery
mark@codesourcery.com
(650) 331-3385 x713
More information about the Gcc
mailing list