LLVM sets CMAKE_INSTALL_RPATH in its top-level CMakeLists.txt to "\$ORIGIN/../lib${LLVM_LIBDIR_SUFFIX}". When Clang is built with LLVM, this propagates to Clang as well and ensures that even if CMAKE_INSTALL_PREFIX is set, installed binaries always find their dependent libraries.
When compiling clang as a separate build, no such rpath is set. If CMAKE_INSTALL_PREFIX is not set and libraries are installed to standard locations, this is not a problem. But when defining CMAKE_INSTALL_PREFIX, even if the same as that of LLVM, and installing and then executing binaries like clang, it results in
error while loading shared libraries: libLLVMBPFCodeGen.so.4.0: cannot open shared object file: No such file or directory
A fix was proposed to Clang: https://reviews.llvm.org/D25267. It was suggested that this problem be resolved by patching LLVM's 'add_llvm_executable' function and remove the rpath logic from the top-level CMakeLists.txt entirely.
This patch is based on the rpath logic of the top-level CMakeLists.txt. It has been tested by building LLVM with "CMAKE_INSTALL_PREFIX=/usr/lib/llvm-9999" and building Clang separately with "CMAKE_INSTALL_PREFIX=/usr/lib/clang-9999" (the version number is a Gentoo Linux convention). Testing with readelf -d /usr/lib/llvm-9999/bin/llvm-extract | grep 'RUNPATH', for instance, correctly prints:
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN/../lib64]
and readelf -d /usr/lib/clang-9999/bin/clang++ | grep 'RUNPATH' correctly prints
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN/../lib64:/usr/lib64/llvm-9999/lib64]
Update: Patch updated based on previous suggestions.
Please rename this to follow the conventions in this file (i.e. llvm_set_rpath).