ps6: task 1

This commit is contained in:
2026-04-28 22:10:46 +02:00
parent 9dfc2c6fc2
commit 5bc4780a7d
2 changed files with 29 additions and 0 deletions
+1
View File
@@ -65,6 +65,7 @@
EMIT("movzbq %s, %s", (byte_reg), (full_reg)) // full_reg <- byte_reg
#define JNE(label) EMIT("jne %s", (label)) // Conditional jump (not equal)
#define JE(label) EMIT("je %s", (label)) // Conditional jump (equal)
#define JMP(label) EMIT("jmp %s", (label)) // Unconditional jump
// Bitwise and
+28
View File
@@ -445,6 +445,8 @@ static void generate_return_statement(node_t* statement)
EMIT("jmp .%s.epilogue", current_function->name);
}
int if_counter = 0;
static void generate_if_statement(node_t* statement)
{
// TODO (Task 1):
@@ -453,6 +455,32 @@ static void generate_if_statement(node_t* statement)
// You will need to define your own unique labels for this if statement,
// so consider using a global variable as a counter to give each label a suffix unique to this if.
int arity = statement->n_children;
assert(arity == 2 || arity == 3);
bool do_else = arity == 3;
node_t *condition = statement->children[0];
node_t *then_body = statement->children[1];
char endif_label[8];
snprintf(endif_label, 8, "ENDIF%d", if_counter);
char else_label[8];
snprintf(else_label, 8, "ELSE%d", if_counter);
if_counter++;
generate_expression(condition);
CMPQ("$0", RAX);
JE(else_label);
generate_statement(then_body);
JMP(endif_label);
LABEL("%s", else_label);
if (do_else) {
node_t *else_body = statement->children[2];
generate_statement(else_body);
}
LABEL("%s", endif_label);
}
static void generate_while_statement(node_t* statement)