How to write your own code generator backend for gcc?

c, compiler-construction, gcc

Solution

It is hard work.

For example I also design my own "architecture" with my own byte code and wanted to generate C/C++ code with GCC for it. This is the way how I make it:

- At first you should read everything about porting in the manual of GCC.

- Also not forget too read GCC Internals.

- Read many things about Compilers.

- Also look at this question and the answers here.

- Google for more information.

- Ask yourself if you are really ready.

- Be sure to have a very good cafe machine... you will need it.

- Start to add machine dependet files to gcc.

- Compile gcc in a cross host-target way.

- Check the code results in the Hex-Editor.

- Do more tests.

- Now have fun with your own architecture :D

When you are finished you can use c or c++ only without os-dependet libraries (you have currently no running OS on your architecture) and you should now (if you need it) compile many other libraries with your cross compiler to have a good framework.

PS: LLVM (Clang) is easier to port... maybe you want to start there?

Problem

I have created my very own (very simple) byte code language, and a virtual machine to execute it. It works fine, but now I'd like to use gcc (or any other freely available compiler) to generate byte code for this machine from a normal c program. So the question is, how do I modify or extend gcc so that it can output my own byte code? Note that I do NOT want to compile my byte code to machine code, I want to "compile" c-code to (my own) byte code. I realize that this is a potentially large question, and it is possible that the best answer is "go look at the gcc source code". I just need some help with how to get started with this. I figure that there must be some articles or books on this subject that could describe the process to add a custom generator to gcc, but I haven't found anything by googling.

Original source