Compiler Translation

September 24, 2013

I often wish I could easily port a C compiler to my new target.

When I build a substantial CPU, I often use my universal assembler hack to get a quick cross assembler going so I can write code. However, I often wish I could easily port a C compiler to my new target. The obvious answer, of course, is to retarget gcc. That sounds good in theory, but if you’ve ever tried porting gcc’s backend to a new architecture, it is a daunting task.

Another common alternative to gcc is CLANG/LLVM. The gcc compiler compiles to an “intermediate language” (IL) that the machine code generator then converts to a specific assembly language. LLVM is similar to IL and there are a variety of frontends that compile languages to LLVM (CLANG is the one for the C language). The LLVM software can translate into different machine languages as a compiler or just in time, in some cases. There is also a gcc retarget that emits LLVM intermediate code.

Either way you go, you don’t have to worry about all the compiler-specific details. You only need to figure out how to bridge from the compiler’s intermediate representation to your machine code (usually, the backend emits assembly language as text, which is further compiled by something like gas, the GNU Assembler).

There are a few other options, too. The lcc compiler started out as a book in 1995. It uses iburg to do code generation, and that tool might be useful with some other retargeting projects, as well. The Lance compiler is available for limited use without a license. Although the vbcc compiler hasn’t been updated since 2011, the documentation of its backend looked very good and it appeared to be one of the easier compilers to port.

Whatever tool you use, it looks like a big project and one I haven’t attempted yet. There are a few tutorials floating around, although none seem complete or, at least, current. For LLVM, there is a tutorial that targets a special CPU and the official documentation. For gcc there are several choices, including a Master’s thesis and the official documentation.

Since the CPUs I typically want to target are embedded, I may revisit SDCC, which has matured quite a bit. It appears to be retargetable (read Chapter 9 of the documentation) and has a reasonably small set of iCode primitives (which has nothing to do with Apple, by the way).

There are doubtlessly other retargetable CPUs out there, and I suppose I’ll eventually bite the bullet and retarget one for One-Der or one of my other CPUs.