Add static global variables

This commit is contained in:
Rui Ueyama 2019-08-24 11:22:02 +09:00
parent 3eaf84bf16
commit ac88c3b38a
4 changed files with 15 additions and 6 deletions

View File

@ -73,6 +73,7 @@ struct Var {
int offset; // Offset from RBP
// Global variable
bool is_static;
Initializer *initializer;
};

View File

@ -524,6 +524,10 @@ static void gen(Node *node) {
}
static void emit_data(Program *prog) {
for (VarList *vl = prog->globals; vl; vl = vl->next)
if (!vl->var->is_static)
printf(".global %s\n", vl->var->name);
printf(".bss\n");
for (VarList *vl = prog->globals; vl; vl = vl->next) {

13
parse.c
View File

@ -136,8 +136,9 @@ static Var *new_lvar(char *name, Type *ty) {
return var;
}
static Var *new_gvar(char *name, Type *ty, bool emit) {
static Var *new_gvar(char *name, Type *ty, bool is_static, bool emit) {
Var *var = new_var(name, ty, false);
var->is_static = is_static;
push_scope(name)->var = var;
if (emit) {
@ -641,7 +642,7 @@ static Function *function(void) {
ty = declarator(ty, &name);
// Add a function type to the scope
new_gvar(name, func_type(ty), false);
new_gvar(name, func_type(ty), false, false);
// Construct a function object
Function *fn = calloc(1, sizeof(Function));
@ -861,7 +862,7 @@ static void global_var(void) {
return;
}
Var *var = new_gvar(name, ty, sclass != EXTERN);
Var *var = new_gvar(name, ty, sclass == STATIC, sclass != EXTERN);
if (sclass == EXTERN) {
expect(";");
@ -1077,7 +1078,7 @@ static Node *declaration(void) {
if (sclass == STATIC) {
// static local variable
Var *var = new_gvar(new_label(), ty, true);
Var *var = new_gvar(new_label(), ty, true, true);
push_scope(name)->var = var;
if (consume("="))
@ -1706,7 +1707,7 @@ static Node *compound_literal(void) {
}
if (scope_depth == 0) {
Var *var = new_gvar(new_label(), ty, true);
Var *var = new_gvar(new_label(), ty, true, true);
var->initializer = gvar_initializer(ty);
return new_var_node(var, tok);
}
@ -1836,7 +1837,7 @@ static Node *primary(void) {
token = token->next;
Type *ty = array_of(char_type, tok->cont_len);
Var *var = new_gvar(new_label(), ty, true);
Var *var = new_gvar(new_label(), ty, true, true);
var->initializer = gvar_init_string(tok->contents, tok->cont_len);
return new_var_node(var, tok);
}

3
tests
View File

@ -60,6 +60,7 @@ Tree *tree = &(Tree){
extern int ext1;
extern int *ext2;
static int ext3 = 3;
int;
struct {char a; int b;};
@ -684,6 +685,8 @@ int main() {
ret_none();
assert(3, ext3, "ext3");
printf("OK\n");
return 0;
}