-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.c
More file actions
114 lines (96 loc) · 2.08 KB
/
codegen.c
File metadata and controls
114 lines (96 loc) · 2.08 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "9cc.h"
static int depth;
static void push(void) {
printf(" push %%rax\n");
depth++;
}
static void pop(char *arg) {
printf(" pop %s\n", arg);
depth--;
}
static void gen_addr(Node *node) {
if (node->kind == ND_LVAR) {
int offset = (node->name - 'a' + 1) * 8;
printf("\tlea %d(%%rbp), %%rax\n", -offset);
return;
}
error("not an lvalue");
}
static void gen_expr(Node *node) {
switch (node->kind) {
case ND_NUM:
printf(" mov $%d, %%rax\n", node->val);
return;
case ND_NEG:
gen_expr(node->lhs);
printf(" neg %%rax\n");
return;
case ND_LVAR:
gen_addr(node);
printf("\tmov (%%rax), %%rax\n");
return;
case ND_ASSIGN:
gen_addr(node->lhs);
push();
gen_expr(node->rhs);
pop("%rdi");
printf("\tmov %%rax, (%%rdi)\n");
return;
}
gen_expr(node->rhs);
push();
gen_expr(node->lhs);
pop("%rdi");
switch (node->kind) {
case ND_ADD:
printf(" add %%rdi, %%rax\n");
return;
case ND_SUB:
printf(" sub %%rdi, %%rax\n");
return;
case ND_MUL:
printf(" imul %%rdi, %%rax\n");
return;
case ND_DIV:
printf(" cqo\n");
printf(" idiv %%rdi\n");
return;
case ND_EQ:
case ND_NE:
case ND_LT:
case ND_LE:
printf(" cmp %%rdi, %%rax\n");
if (node->kind == ND_EQ)
printf(" sete %%al\n");
else if (node->kind == ND_NE)
printf(" setne %%al\n");
else if (node->kind == ND_LT)
printf(" setl %%al\n");
else if (node->kind == ND_LE)
printf(" setle %%al\n");
printf(" movzb %%al, %%rax\n");
return;
}
error("invalid expression");
}
static void gen_stmt(Node *node) {
if (node->kind == ND_EXPR_STMT) {
gen_expr(node->lhs);
return;
}
error("invalid statement");
}
void codegen(Node *node) {
printf(" .globl main\n");
printf("main:\n");
printf("\tpush %%rbp\n");
printf("\tmov %%rsp, %%rbp\n");
printf("\tsub $208, %%rsp\n");
for (Node *n = node; n; n = n->next) {
gen_stmt(n);
assert(depth == 0);
}
printf("\tmov %%rbp, %%rsp\n");
printf("\tpop %%rbp\n");
printf(" ret\n");
}