Search code examples
compiler-constructionllvmclang++llvm-c++-apillc

How to generate LLVM api code via IR code, in current versions?


I am trying to generate LLVM API code that can regenerate IR code that is fed into it. As i discovered via various questions such as this question it was at some point possible to do the following to achieve this goal:

clang++ -S -O0 -emit-llvm MyFile.cpp -o MyIR.ll
llc -march=cpp MyIR.ll -o MyIR_Maker.cpp

However i get the following error: llc: error: invalid target 'cpp'. Further research tells me that the same issue occurred in earlier versions of LLVM when the c backend was removed in version 3.1. I am however using cpp, this leads me to believe that for some reason the cpp backend does not exist in my version of llvm.

So really what i want to know from here is: if my analysis so far is correct, how do i enable the cpp backend or otherwise get my llc to a state where i can use it in the way i desire? Of course if i am wrong or if there is another way, i will be open to it.

The version we've chosen to work with is LLVM 3.6, this was installed via brew on OS X. Thank you in advance.

Edit: This question has been pointed to as a possibly similar question. However that question was asked in the specific context of LLVM 3.2, where as mine concerns the current situation in version 3.6, as there may possibly be a real solution at this time. The only answer to that question points to a general outside resource and doesn't explain very thoroughly what the actual solution is.


Solution

  • It appears the correct way to enable the cpp backend is to download the LLVM source and build it yourself, here is how that process worked for me:

    • Go to this page and find the version you would like to use, download the respective link titled "LLVM source code"
    • Extract the file
    • Open the command line
    • cd to the folder you've just extracted, it should be of the format "llvm-x.x.x.src", where x.x.x is your version number
    • mkdir build
    • cd build
    • brew install cmake (if you don't already have cmake)
    • cmake -G Xcode .. (This generates an Xcode project that can build LLVM)
    • open LLVM.xcodeproj
    • If prompted when Xcode opens, click "automatically create schemes"
    • Wait for Xcode to finish indexing, this will take a while.
    • Run the Xcode project to compile LLVM, this will also take a while.
    • Once this is done all of the generated llvm CLI tools will be in a in your "build" folder, in a directory called Debug/bin
    • Place this folder wherever you want, and export it to your path.

    Now you should be able to following commands should work as expected, assuming you're using an appropriate version of clang, and your path doesn't include a different set of the llvm binaries:

    clang++ -S -O0 -emit-llvm MyFile.cpp -o MyIR.ll
    llc -march=cpp MyIR.ll -o MyIR_Maker.cpp