Skip to content

Latest commit

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Compiler

A minimal C compiler for my custom 16-bit RISC architecture, capable of compiling itself.

Currently does two passes:

  1. Parse to AST (also analyzes variable lifetime)
  2. Generate Code from AST (no IR, fprintf straight to output file)

Example

SourceAssembly
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]

Limitations

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 (alias int16, int16_t)
    • uint (alias uint16, uint16_t, size_t, char)
    • int32 (alias int32_t)
    • uint32 (alias uint32_t)
    • fixed (8.8 fixed point)

These are just off the top of my head, there surely are many others!

Building

Just a CMake project, so

> mkdir bin
> cd bin
> cmake ..

followed by

> cmake --build .

Usage

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.

About

From-scratch C compiler for my custom 16-bit CPU

Topics

Resources

Stars

75 stars

Watchers

2 watching

Forks

Releases

Packages

Contributors

Languages