A minimal C compiler for my custom 16-bit RISC architecture, capable of compiling itself.
Currently does two passes:
- Parse to AST (also analyzes variable lifetime)
- Generate Code from AST (no IR,
fprintfstraight to output file)
| Source | Assembly |
|---|---|
structcoord
{
intx;
inty;
};
intfoo (intn, structcoord*coords)
{
intsum=0;
for (inti=0; i<n; i++)
sum+=coords[i].x*coords[i].y;
returnsum;
} | _foo:mov r0,0mov r1,0for_loop0:sub rz, r1,[sp-2]jmp_ns for_break0mul r2, r1,2add r2,[sp-3]mul r3, r1,2add r3,[sp-3]add r3,1mov r5,[r3]mul r4,[r2], r5add r0, r4for_continue0:add r1,1jmp for_loop0for_break0:mov[sp-2], r0subsp,1movip,[sp] |
This is not a conformant C compiler (at all!). Here are the most important things that are missing or different
- Type conversion behaviour is different
- Parsing is not quite the same as in standard C
- Preprocessor only supports #include, #define, #ifdef, and #pragma once
- Primitives are:
int(aliasint16,int16_t)uint(aliasuint16,uint16_t,size_t,char)int32(aliasint32_t)uint32(aliasuint32_t)fixed(8.8 fixed point)
These are just off the top of my head, there surely are many others!
Just a CMake project, so
> mkdir bin
> cd bin
> cmake ..
followed by
> cmake --build .
There are no command-line switches as of now, so just
> ./comp [SOURCE FILES..]
This will generate assembly in out.s and data in data.bin.