Compiling LLVM to LLVM IR

Hello everyone,

I'm trying to compile LLVM and Clang into LLVM IR with debug info. I know that clang++ -g2 -S -emit-llvm <filename> does this, but I'm unfamiliar with CMake.

I tried changing CMAKE_CXX_FLAGS in CMakeCache.txt to "clang++ -g2 -S -emit-llvm," "-g2 -S -emit-llvm," and "-emit-llvm," but everything I tried resulted in a failed build, and/or .o files that didn't look like LLVM IR files when I opened them up. Where is the right place to pass these flags in?

Thanks,
Mackenzie

Hi Mackenzie,

The trick is to use LTO.
Here is a set of commands you need to run in order to prepare build system:

$ mkdir build
$ cd build
$ export CFLAGS="-flto -g "
$ export CXXFLAGS="-flto -g "
$ export CPPFLAGS="-flto -g "
$ cmake ../llvm

Now you can build any target you want, for instance:

$ make LLVMSupport -j8

When it's done you will have bunch of .o files, which are actually LLVM bitcode files:

$ find ./ -name "*.o" | xargs file
.//CMakeFiles/test.o: LLVM bitcode, wrapper x86_64
.//lib/Support/CMakeFiles/LLVMSupport.dir/Allocator.cpp.o: LLVM bitcode, wrapper x86_64
.//lib/Support/CMakeFiles/LLVMSupport.dir/APFloat.cpp.o: LLVM bitcode, wrapper x86_64
.//lib/Support/CMakeFiles/LLVMSupport.dir/APInt.cpp.o: LLVM bitcode, wrapper x86_64
.//lib/Support/CMakeFiles/LLVMSupport.dir/APSInt.cpp.o: LLVM bitcode, wrapper x86_64
.//lib/Support/CMakeFiles/LLVMSupport.dir/ARMAttributeParser.cpp.o: LLVM bitcode, wrapper x86_64
....

If you need a human readable IR, then you can convert them into .ll using llvm-dis:

$ llvm-dis .//lib/Support/CMakeFiles/LLVMSupport.dir/Allocator.cpp.o
$ file .//lib/Support/CMakeFiles/LLVMSupport.dir/Allocator.cpp.o.ll
.//lib/Support/CMakeFiles/LLVMSupport.dir/Allocator.cpp.o.ll: ASCII text, with very long lines

I hope that helps.

Cheers,
Alex.

Shorter:

```cmake ../llvm -DLLVM_ENABLE_LTO=YES```

Note that LTO implies a different optimization pipeline. If you just want
IR without changing anything else, the exact command line flag is
`-emit-llvm` I believe.

Best,