LLVM

From NixOS Wiki
Jump to: navigation, search

From Wikipedia:

The LLVM compiler infrastructure project is a "collection of modular and reusable compiler and toolchain technologies" used to develop compiler front ends and back ends.

Build LLVM/clang from source

LLVM/clang when compiled from source won't find headers/libraries/startup files without compiler wrapper. However it is possible to use the following shell.nix to get started and provide the missing flags to the compiler manually

with import <nixpkgs> {};
let
  gccForLibs = stdenv.cc.cc;
in stdenv.mkDerivation {
  name = "llvm-env";
  buildInputs = [
    bashInteractive
    ninja
    cmake
    llvmPackages_latest.llvm
  ];

  # where to find libgcc
  NIX_LDFLAGS="-L${gccForLibs}/lib/gcc/${targetPlatform.config}/${gccForLibs.version}";
  # teach clang about C startup file locations
  CFLAGS="-B${gccForLibs}/lib/gcc/${targetPlatform.config}/${gccForLibs.version} -B ${stdenv.cc.libc}/lib";

  cmakeFlags = [
    "-DGCC_INSTALL_PREFIX=${gcc}"
    "-DC_INCLUDE_DIRS=${stdenv.cc.libc.dev}/include"
    "-GNinja"
    # Debug for debug builds
    "-DCMAKE_BUILD_TYPE=Release"
    # inst will be our installation prefix
    "-DCMAKE_INSTALL_PREFIX=../inst"
    "-DLLVM_INSTALL_TOOLCHAIN_ONLY=ON"
    # change this to enable the projects you need
    "-DLLVM_ENABLE_PROJECTS=clang;libcxx;libcxxabi"
    # this makes llvm only to produce code for the current platform, this saves CPU time, change it to what you need
    "-DLLVM_TARGETS_TO_BUILD=host"
  ];
}

After that you can execute the following commands to get a working clang:

 $ git clone https://github.com/llvm/llvm-project/
 $ mkdir build && cd build
 $ cmake $cmakeFlags ../llvm-project/llvm
 $ ninja
 # installs everything to ../inst
 $ ninja install
 $ cd ..

Then assuming you have a test program called main.c:

 $ ./inst/bin/clang $CFLAGS -o main main.c