Linking to any LLVM from CMake

Hi all,

Maybe I’m missing something in the documentation somewhere, but I’ve found
the officially suggested way to link an application to LLVM to be quite
brittle. I’m referring to the way listed here: https://llvm.org/docs/CMake.html

If I use llvm_map_components_to_libnames with an LLVM that was built with
LLVM_LINK_LLVM_DYLIB set to true, and then try to link to both some LLVM
components and lldWasm, then my library will compile, but it will fail at
runtime since it is linked to both the shared LLVM library (via lldWasm)
and the static libraries I requested with the function. Linuxbrew builds
this way.

Furthermore, if only the shared library was built and packaged, then the
function will throw a fatal error. This broke our build on Gentoo.

For context, I work on the Halide CMake build and you can see the hoops we
have to jump through here:

https://github.com/halide/Halide/blob/master/dependencies/llvm/CMakeLists.txt

What is the correct way to link to LLVM, no matter the configuration?

Thanks,

Alex

Hi Alexander,

The best way I’ve found is to use LLVM_LINK_COMPONENTS, which ends up calling llvm_map_components_to_libnames() underneath hood.
The biggest pitfall is that lldWasm needs to be linked the same way so that both link against libLLVM.so or both not.

It’s possible you’re trying to work around issues in the way that lldWasm is linked…

Steve

Hi Steve,

The best way I’ve found is to use LLVM_LINK_COMPONENTS, which ends up calling llvm_map_components_to_libnames() underneath hood.

I tried grepping for LLVM_LINK_COMPONENTS in my installed lib/cmake/llvm
directory, but I only see it used as a global variable. Should it also be
a function?

I see that symbol in AddLLVM.cmake and TableGen.cmake. In the former, it
appears in add_llvm_executable and add_llvm_library. The documentation I
linked to earlier states that add_llvm_library is an “internal” macro, so
I assume that it shouldn’t be used by fully external client code? The uses
in TableGen.cmake don’t seem relevant.

The biggest pitfall is that lldWasm needs to be linked the same way so that both link against libLLVM.so or both not.

It’s possible you’re trying to work around issues in the way that lldWasm is linked…

The workaround we found for the way lldWasm is linked is simply to add an
error message to fail early in this case. The main issue was that nothing
was stopping our users from falling into this trap.

Best,

Alex