Monday, October 11, 2010

CMake and Clang/LLVM fun.

I have been using CMake in more projects lately, and have had some fun working around the kinks with alternative compilers (like using mingw from Linux to compile windows executables).

Recently wanted to build a software graphics renderer with Clang, and see if there was any speedup.
The major problem I encountered was getting CMake to let me use clang with its cool -O4 mode (yes, there really is an optimization beyond -O3 for clang). The first problem was -O4 outputs bytecode enhanced o files, ld had no clue, and I didn't want to use gold with plugins to use llvm plugin for ld, and it kept using gcc as the linker. The second problem was cmake forces -rdynamic in the flags to the linker, which the llvm-ld linker couldn't handle.

Here is my working toolchain_llvm.cmake file I use to make CMake work:
#include using cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake
INCLUDE(CMakeForceCompiler) #Disables checks
SET(CMAKE_SYSTEM_NAME Generic)
#Generic removes -rdynamic from linker, which llvm-ld doesn't support

CMAKE_FORCE_C_COMPILER( /usr/bin/clang CLang )
CMAKE_FORCE_CXX_COMPILER ( /usr/bin/clang++ CLang )
SET(CMAKE_RANLIB "/usr/bin/llvm-ranlib" CACHE INTERNAL STRING)
SET(CMAKE_AR "/usr/bin/llvm-ar" CACHE INTERNAL STRING)

SET(CMAKE_LINKER "/usr/bin/llvm-ld" CACHE INTERNAL STRING)
#SET(CMAKE_C_LINKER "/usr/bin/llvm-ld")
#SET(CMAKE_CXX_LINKER "/usr/bin/llvm-ld")

SET(CMAKE_C_LINK_EXECUTABLE "/usr/bin/llvm-ld <OBJECTS> -o <TARGET> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>")
SET(CMAKE_CXX_LINK_EXECUTABLE "/usr/bin/llvm-ld <OBJECTS> -o <TARGET> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>")

SET(CMAKE_FIND_ROOT_PATH /usr/bin)
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

Yeah, kind of a mouthful, but worth it. Now I can use it with any cmake projects I have, just by running cmake -DCMAKE_TOOLCHAIN_FILE=toolchain_llvm.cmake .

Will get around to posting this in the cmake forums later this week.