Possible to convert a LLVM IR back to C code?

Hi All, Is there any way we get readable c/cpp code from the LLVM IR generated in TVM? @jinchenglee


I don’t think it is possible/easy. There used to be a LLVM C backend a long time ago, which people at JuliaComputing took up, but it’s questionable how readable that is. If you wanted something like this, you probably would want to generate C code in the backend (similar to the CUDA backend).

This is as far as I know. If you know more, I’d be most interested to hear about it.

Best regards


This is a general question to compilers. AFAIK, there’s no production quality tool that compiles LLVM IR code to structed C code. Although LLVM has a backend to generate C code as @t-vi mentioned, it is not for human to read.

The most important reason behind that is the abstraction level and information preservation. Once a C program is compiled to LLVM IR, the loop information is basically transformed to basic blocks with data/control flow. It means that if you want to compile the LLVM IR back to readable C code, you need to analyze the code and recover all those structures by yourself. Given that two functional equivalent but structural different C programs may result in very similar LLVM IR, this becomes an open problem.

In short, as @t-vi suggested, if you want to get C code, you should directly generate C code from TVM IR.

LLVM used to have a cpp backend, but it was generating C++ code which would recreate the LLVM IR via C++ API calls. There is nothing in LLVM right now that would generate C or C++ code that is equivalent to a given LLVM IR.

While it is hard to convert llvm back. We will be gaining a serializable text format for the TIR that is readable.

So we can print out the tir before the llvm codegen stage which will be quite close to what you want TQ

@tqchen, could you please guide me with a sample usage of the same?

The tir printer is still WIP, will update the thread later once it lands