mold icon indicating copy to clipboard operation
mold copied to clipboard

Safe ICF without .llvm_addrsig?

Open rui314 opened this issue 3 years ago • 3 comments

I realized that we may be able to do Safe Identical Code Folding (Safe ICF) just by looking at relocations.

To implement Safe-version ICF, it is critical to determine whether a symbol's address is significant or not. That is, if an address of a symbol is taken, we can't merge it with other symbols, and vice versa.

Simply put, if a symbol is referenced only by R_X86_64_PC32 or R_X86_64_PLT32 (or equivalent relocation types in other targets), it is very unlikely that the symbol's address is taken, and therefore it is safe to merge it in ICF. Theoretically, you can take a relative symbol address with these relocations and add the current program counter to get the symbol's address, but as far as I know, there's no compiler that emits such machine code.

In fact, we use that assumption to determine whether we promote a PLT entry to a canonical one. So, we already depends on that assumption.

This scheme doesn't work for read-only data (as opposed to functions). But that may not be a big problem because IIUC, most space savings of ICF come from function merging and not data merging.

In hindsight, the above idea looks obvious, so I'm not sure why no one has implemented it to any major linker. I may be missing something.

CC @ishitatsuyuki @MaskRay

Related to https://github.com/rui314/mold/issues/484

rui314 avatar Jul 02 '22 05:07 rui314

This sounds good to me, although I'm by no means an expert on the topic of soundness of these optimizations.

Perhaps we could look into how LLVM determines addrsig attributes to check if there's any edge case not covered by relocations.

ishitatsuyuki avatar Jul 02 '22 06:07 ishitatsuyuki

Oh, looks like I also missed some context from https://discourse.llvm.org/t/problems-with-mach-o-address-significance-table-generation/63392/16.

ishitatsuyuki avatar Jul 02 '22 07:07 ishitatsuyuki

I'm sorry for not sharing that URL!

rui314 avatar Jul 02 '22 10:07 rui314