How to make clang compile to llvm IR

pythonic picture pythonic · Feb 5, 2012 · Viewed 97.5k times · Source

I want clang to compile my C/C++ code to LLVM bytecode rather than binary executable. How can I achieve that? And if I get the LLVM bytecode, how can I take it to further compile it to binary executable.

Basically I want to add some of my own code to the LLVM bytecode before compiling to binary executable.

Answer

Eli Bendersky picture Eli Bendersky · Feb 5, 2012

Given some C/C++ file foo.c:

> clang -S -emit-llvm foo.c

Produces foo.ll which is an LLVM IR file.

The -emit-llvm option can also be passed to the compiler front-end directly, and not the driver by means of -cc1:

> clang -cc1 foo.c -emit-llvm

Produces foo.ll with the IR. -cc1 adds some cool options like -ast-print. Check out -cc1 --help for more details.


To compile LLVM IR further to assembly, use the llc tool:

> llc foo.ll

Produces foo.s with assembly (defaulting to the machine architecture you run it on). llc is one of the LLVM tools - here is its documentation.