forked from jserv/jit-construct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler-arm.c
84 lines (81 loc) · 1.94 KB
/
compiler-arm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdio.h>
#include <stdlib.h>
#include "util.h"
#include "stack.h"
void compile(const char * const file_contents)
{
int num_brackets = 0;
int matching_bracket = 0;
struct stack stack = { .size = 0, .items = { 0 } };
const char * const prologue =
".globl main\n"
"main:\n"
"LDR R4 ,= _array\n"
"push {lr}\n";
puts(prologue);
for (unsigned long i = 0; file_contents[i] != '\0'; ++i) {
switch (file_contents[i]) {
case '>':
puts(" ADD R4, R4, #1");
break;
case '<':
puts(" SUB R4, R4, #1");
break;
case '+':
puts(" LDRB R5, [R4]");
puts(" ADD R5, R5, #1");
puts(" STRB R5, [R4]");
break;
case '-':
puts(" LDRB R5, [R4]");
puts(" SUB R5, R5, #1");
puts(" STRB R5, [R4]");
break;
case '.':
puts(" LDR R0 ,= _char ");
puts(" LDRB R1, [R4]");
puts(" BL printf");
break;
case ',':
puts(" BL getchar");
puts(" STRB R0, [R4]");
break;
case '[':
if (stack_push(&stack, num_brackets) == 0) {
printf("_in_%d:\n", num_brackets);
puts (" LDRB R5, [R4]");
puts (" CMP R5, #0");
printf(" BEQ _out_%d\n", num_brackets);
num_brackets++;
} else {
err("out of stack space, too much nesting");
}
break;
case ']':
if (stack_pop(&stack, &matching_bracket) == 0) {
printf("_out_%d:\n", matching_bracket);
puts (" LDRB R5, [R4]");
puts (" CMP R5, #0");
printf(" BNE _in_%d\n", matching_bracket);
} else {
err("stack underflow, unmatched brackets");
}
break;
}
}
const char *const epilogue =
" pop {pc}\n"
".data\n"
".align 4\n"
"_char: .asciz \"%c\"\n"
"_array: .space 30000\n";
puts(epilogue);
}
int main(int argc, char *argv[])
{
if (argc != 2) err("Usage: compiler-arm <inputfile>");
char *file_contents = read_file(argv[1]);
if (file_contents == NULL) err("Unable to read file");
compile(file_contents);
free(file_contents);
}