Search code examples
compiler-constructionosx-yosemitexcode6.1llvm-clang

Clang Launch Sequence?


What LLVM/Clang code is executed in what order upon passing source code to Clang for compilation?


Solution

  • What exactly do you mean? Are you interested in compilation phases, or do you want to see a stack trace for a particular method or class?


    Compilation phases:

    Let's say you pass some source file to clang by typing clang main.c into Terminal.

    The clang command by itself is just a driver which consumes parameters and invokes the actual compiler (you can invoke it directly by passing clang the -cc1 argument).

    Then, the compiler itself does the following jobs:

    • Invoking the preprocessor to handle all macro definitions (#define, #ifdef, etc.)
    • Breaks all source code into tokens (if keyword, while keyword, your_var identifier, etc.)
    • Passes tokens to the parser, which constructs an Abstract Syntax Tree and applies semantic analysis, but only in place (e.g.: check if assignment expression has correct types for lvalue and rvalue)
    • When the AST is done being generated, then the 'CodeGen' phase comes into play: it translates the AST passed to it by the parser into LLVM Intermediate Representation
    • Here, front-end phase ends and LLVM finally appears: it takes LLVM IR, applies optimizations and generates assembly code or object files for the end-user platform (e.g.: x86_64, arm64)

    Stacktrace:

    If you want to take a look at a stack trace or debugging report, then it makes sense to build Clang on your own.

    Here are instructions for compiling LLVM/Clang on OS X using Xcode after cloning the LLVM repository to your hard drive via Git:

    First, download LLVM's source files:

    mkdir ~/Projects/clang-dev
    cd ~/Projects/clang-dev
    git clone http://llvm.org/git/llvm.git
    git clone http://llvm.org/git/clang.git llvm/tools/clang
    git clone http://llvm.org/git/clang-tools-extra.git llvm/tools/clang/tools/extra
    git clone http://llvm.org/git/compiler-rt.git llvm/projects/compiler-rt
    

    You can also specify exact version by passing branch name to each clone command, e.g.: git clone http://llvm.org/git/llvm.git -b release_34

    Next, create and open an Xcode project:

    cd ~/Projects/clang-dev
    mkdir build
    cd build
    cmake -G Xcode CMAKE_BUILD_TYPE="Debug" ../llvm
    open LLVM.xcodeproj
    

    Set clang as your project's current target/scheme, click 'Edit scheme,' and add a source file to be passed to Clang as an argument when it runs:

    Edit scheme

    That's pretty much it; just set a breakpoint (in the main method or whenever you want) and hit the Run button (or press Cmd + R).

    UPD

    Here is more detailed guide: Getting started with LLVM/Clang on OS X


    Useful Links:

    Architecture of Open-Source Applications: LLVM by Chris Lattner

    objc.io: The Compiler by Chris Eidhof