Saturday, June 02, 2012

llvm / Clang hacking: Part 1

Part 1 in my N-part series on my exploration of hacking on llvm and Clang (c-language) tool chain.  I am running OS X 10.7, however I will try to highlight the steps where you should consider substituting for your platform.

Getting Started

Follow these steps, with the following exceptions if you prefer git (it is a lot faster); I am using the official llvm mirror on llvm.org.

  • Step 2, substitute the svn command for
    git clone http://llvm.org/git/llvm.git
  • Step 3, substitute the svn command for
    git clone http://llvm.org/git/clang.git
  • Step 4, substitute the svn command for
    git clone http://llvm.org/git/compiler-rt.git
  • Step 5, I am using CMake, so instead of ../llvm/configure
    cmake -G "Unix Makefiles" ../llvm
    make
    

Creating Xcode project for Clang

You could run

  • mkdir llvm
  • cd llvm
  • cmake -G Xcode ../llvm

to create an Xcode project for the entire llvm/Clang toolchain, however it ends up being thousands of source files and 223 targets! As I'm only interested in hacking on Clang, lets generate a project file for Clang and related projects only. Starting from the folder which contains build and llvm:

  • mkdir clang
  • cd clang
  • cmake -DCLANG_PATH_TO_LLVM_SOURCE=../llvm -DCLANG_PATH_TO_LLVM_BUILD=../build -DCMAKE_BUILD_TYPE=Debug ../llvm/tools/clang

Assuming all went well, you'll now have an Xcode project called Clang.xcodeproj with about 400 source files and 60 targets. Open it up and let Xcode index everything, which may take a few minutes depending on your hardware.  Once completed, switch to the clang target and build!

Note: On Windows, it is likely cmake will auto-detect your Visual Studio environment and the above commands will Just Work™

Xcode clang target

Assuming all goes well, a few minutes later you should see:

Clang build Succeeded

Back in Terminal, you can run the following command, which creates a Hello World program and tests your build of Clang.

From the clang folder

  • cd bin/Debug
  • echo "#include \nint main(int argc,char**argv) { printf(\"hello world\\\n\"); return 0; }" > hello.c && clang hello.c -o hello && ./hello

If you see hello world after running the 2nd command, pat yourself on the back, as you've successfully setup a working llvm / Clang development environment to start your hacking.

Next Up

Part 2 and debugging Clang.

Twitter

Follow me on twitter, @stuartcarnie.

4 comments:

Martins Mozeiko said...

llvm & clang has official git repositories, no need to use unofficial mirrors.
git clone http://llvm.org/git/llvm.git
git clone http://llvm.org/git/clang.git
git clone http://llvm.org/git/compiler-rt.git

Stuart said...

Thanks Martins; I should have remembered those repos!

Cheers

Unknown said...

The cmake for generating Xcode project for clang is incorrect. There is no declaration for "Xcode" generator.

Stuart said...

@Unknown, indeed there is an Xcode generator. See official Cmake docs here