D78354 enabled installing PIC version of both libclang.a and libclang.so when LIBCLANG_BUILD_STATIC is ON. But it broke the no-PIC build when LLVM_ENABLE_PIC=OFF with the following error:
CMake Error at /b/s/w/ir/cache/builder/src/third_party/llvm/clang/tools/libclang/CMakeLists.txt:123 (target_compile_definitions): target_compile_definitions called with non-compilable target type
This is because as the code loops through ${name} and ${name}_static, it introduced a side effect, which is adding an empty libclang_static to targets. Later target_compile_definitions is called on libclang_static. That function requires that target must have been created by a command such as add_executable() or add_library(), so it crashed.
The solution is to not naively loop through both libclang and libclang_static, but only the ones that are actually added by llvm_add_library(). Here's the library build type to library target name mapping:
SHARED only | libclang |
STATIC only | libclang |
SHARED and STATIC | libclang and libclang_static |
So only when SHARED and STATIC are both set should we loop through two targets. Explicitly parse the STATIC argument and set the list accordingly.
Test plan:
Try all combinations of LIBCLANG_BUILD_STATIC and LLVM_ENABLE_PIC and make sure results are expected:
LIBCLANG_BUILD_STATIC | LLVM_ENABLE_PIC | Libraries built and installed |
---|---|---|
OFF | ON | libclang.so |
OFF | OFF | libclang.a |
ON | ON | libclang.a and libclang.so |
ON | OFF | libclang.a |
Super nit: you can do list(APPEND libs ${name}_static) instead.