Clang/Bootstrapping

From Gentoo Wiki
< Clang
Jump to:navigation Jump to:search

Advanced users may choose to 'bootstrap' Clang by building it using the full LLVM toolchain. This is optional and not required

The only time this would be required is if looking to move a system to be entirely GCC-free (which is currently not possible on glibc systems) - that is not yet supported and is dangerous.

Bootstrapping the Clang toolchain

Mixing Clang and its toolchain / libraries with the GCC toolchain / libraries (especially the linker) will often lead to issues like linker errors during emerges.

To prevent this, the Clang toolchain is built first with GCC and then with itself to get a self-providing compiler.

Preparing the environment

Prepare the environment for the Clang toolchain:

FILE /etc/portage/env/compiler-clang
CC="clang"
CXX="clang++"

LDFLAGS="-fuse-ld=lld -rtlib=compiler-rt -unwindlib=libunwind -Wl,--as-needed"

# Hardening
_HARDENING_FLAGS="-fstack-protector-strong -D_FORTIFY_SOURCE=2"
CFLAGS="${CFLAGS} ${_HARDENING_FLAGS}"
CXXFLAGS="${CXXFLAGS} ${_HARDENING_FLAGS}"
LDFLAGS="${LDFLAGS} -Wl,-z,relro,-z,now -unwindlib=libunwind"

This example replaces not only the compiler but also the GNU linker ld.bfd with the LLVM linker lld. It is a drop-in replacement, but significantly faster than the bfd linker.

Set USE flags default-compiler-rt default-lld llvm-libunwind for Clang via /etc/portage/package.use:

FILE /etc/portage/package.use/clang
sys-devel/clang default-compiler-rt default-lld llvm-libunwind

Then install Clang, LLVM, compiler-rt, llvm-libunwind, and lld with the default GCC environment:

root #emerge clang llvm compiler-rt llvm-libunwind lld

It is also possible to add the default-libcxx USE flag to use LLVM's C++ STL with clang, however this is heavily discouraged because libstdc++ and libc++ are not ABI compatible. i.e. A program built against libstdc++ will likely break when using a library built against libc++, and vice versa.

Note that sys-libs/llvm-libunwind deals with linking issues that sys-libs/libunwind has, so it is preferred to use and replace the non-llvm libunwind package if installed (it builds with -lgcc_s to resolve issues with __register_frame / __deregister_frame undefined symbols).

Finalizing

Enable the Clang environment for these packages now:

FILE /etc/portage/package.env
sys-devel/llvm compiler-clang
sys-libs/libcxx compiler-clang
sys-libs/libcxxabi compiler-clang
sys-libs/compiler-rt compiler-clang
sys-libs/compiler-rt-sanitizers compiler-clang
sys-libs/llvm-libunwind compiler-clang
sys-devel/lld compiler-clang
sys-devel/clang compiler-clang

Repeat the emerge step with the new environment - the toolchain will now be rebuilt with itself instead of GCC:

root #emerge clang llvm libcxx libcxxabi compiler-rt llvm-libunwind lld

Clang may now be used with other packages!