-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.c
100 lines (89 loc) · 2.27 KB
/
codegen.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "codegen.h"
#include "symtab.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern FILE *output;
int free_reg_num = 0;
char invalid_value[] = "???";
// REGISTERS
int take_reg(void) {
if(free_reg_num > LAST_WORKING_REG) {
err("Compiler error! No free registers!");
exit(EXIT_FAILURE);
}
return free_reg_num++;
}
void free_reg(void) {
if(free_reg_num < 1) {
err("Compiler error! No more registers to free!");
exit(EXIT_FAILURE);
} else
set_type(--free_reg_num, NO_TYPE);
}
// Ako je u pitanju indeks registra, oslobodi registar NA VRHU STEKA!
void free_if_reg(int reg_index) {
if(reg_index >= 0 && reg_index <= LAST_WORKING_REG)
free_reg();
}
// SYMBOL
// Izmenjeno da vraca string umesto void
void gen_sym_name(int index) {
if(index > -1) {
if(get_kind(index) == VAR) { // -n*4(%14)
code("-%d(%%14)", get_atr1(index) * 4);
} else if(get_kind(index) == PAR) { // m*4(%14)
code("%d(%%14)", 4 + get_atr1(index) * 4);
} else if(get_kind(index) == LIT) {
code("$%s", get_name(index));
} else { //function, reg, gvar
code("%s", get_name(index));
}
}
}
// Dodato
char *print_sym_name(int index) {
if(index > -1) {
if(get_kind(index) == VAR) { // -n*4(%14)
//code("-%d(%%14)", get_atr1(index) * 4);
// Dodato : (Ali je nepotrebno)
static char ret[10];
strcpy(ret, "-");
char ind[4];
sprintf(ind, "%d", get_atr1(index) * 4);
strcat(ret, ind);
strcat(ret, "(%14)");
return ret;
} else if(get_kind(index) == PAR) { // m*4(%14)
//code("%d(%%14)", 4 + get_atr1(index) * 4);
// TODO:
} else if(get_kind(index) == LIT) {
//code("$%s", get_name(index));
// TODO:
} else { //function, reg, gvar
return get_name(index);
}
}
}
// OTHER
void gen_cmp(int op1_index, int op2_index) {
if(get_type(op1_index) == INT)
code("\n\t\tCMPS \t");
else
code("\n\t\tCMPU \t");
gen_sym_name(op1_index);
code(",");
gen_sym_name(op2_index);
free_if_reg(op2_index);
free_if_reg(op1_index);
}
void gen_mov(int input_index, int output_index) {
code("\n\t\tMOV \t");
gen_sym_name(input_index);
code(",");
gen_sym_name(output_index);
//ako se smešta u registar, treba preneti tip
if(output_index >= 0 && output_index <= LAST_WORKING_REG)
set_type(output_index, get_type(input_index));
free_if_reg(input_index);
}