Thoroughly Rusty ARM64 C Compiler
This is my approach to writing a C compiler, using norasandler's stages
It outputs ARM64 code to be compiled with the gcc-aarch64-linux toolchain.
If you have an x86_64 host (like I do), use qemu-static
, compiling the code with gcc -static
and gcc from aarch64-none-linux-gnu
(available download is here)
The compiler currently expects an only function, with no parameters, with a list of the following:
- Variable declarations (only
int
s for the moment) - Assignments (with their optional binary operators)
- if statements (with else-if chaining)
- blocks inside blocks for scoped variables
- While loops
- The not supported operators are:
- Pre and post increment
- Comma operator
- Array accessing operator (compiler does not support pointers/arrays)
Input file:
int foo() {
int a = 1;
int b = 2;
if (a > b) {
return a -b;
} else {
return a + b;
}
}
Output assembly:
.arch armv8-a
.global foo
.type foo, %function
foo:
sub sp, sp, #16
mov w1, #1
str w1, [sp]
mov w2, #2
str w2, [sp, #4]
ldr w0, [sp]
ldr w1, [sp, #4]
cmp w0, w1
ble .LBB2
ldr w0, [sp]
ldr w1, [sp, #4]
sub w0, w0, w1
b .epilogue
.LBB2:
ldr w0, [sp]
ldr w1, [sp, #4]
add w0, w0, w1
.epilogue:
add sp, sp, #16
ret