Add GNU attribute 'retain'
authorFangrui Song <i@maskray.me>
Fri, 26 Feb 2021 19:59:53 +0000 (11:59 -0800)
committerFangrui Song <i@maskray.me>
Sat, 27 Feb 2021 00:37:50 +0000 (16:37 -0800)
commit8afdacba9dcd36fc838eb86fca86f7f903040030
treebba9167727ae7c03a880fa94619cbebdaf5339db
parent233ba2709bde54ea820cdaba0405d46b2c197e01
Add GNU attribute 'retain'

For ELF targets, GCC 11 will set SHF_GNU_RETAIN on the section of a
`__attribute__((retain))` function/variable to prevent linker garbage
collection. (See AttrDocs.td for the linker support).

This patch adds `retain` functions/variables to the `llvm.used` list, which has
the desired linker GC semantics. Note: `retain` does not imply `used`,
so an unused function/variable can be dropped by Sema.

Before 'retain' was introduced, previous ELF solutions require inline asm or
linker tricks, e.g.  `asm volatile(".reloc 0, R_X86_64_NONE, target");`
(architecture dependent) or define a non-local symbol in the section and use
`ld -u`. There was no elegant source-level solution.

With D97448, `__attribute__((retain))` will set `SHF_GNU_RETAIN` on ELF targets.

Differential Revision: https://reviews.llvm.org/D97447
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/lib/CodeGen/CGDecl.cpp
clang/lib/CodeGen/CodeGenModule.cpp
clang/lib/Sema/SemaDecl.cpp
clang/test/CodeGen/attr-retain.c [new file with mode: 0644]
clang/test/CodeGenCXX/attr-retain.cpp [new file with mode: 0644]
clang/test/Sema/attr-retain.c [new file with mode: 0644]