Implement branches

This commit is contained in:
Konstantin Nazarov 2024-12-06 21:39:01 +00:00
parent c65c14bfdf
commit 2e47ad73ae
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22

View file

@ -136,22 +136,36 @@ void eval(uint8_t* memory, size_t memory_size) {
} }
break; break;
} }
case 0x63: { // B-type (BEQ, BNE) case 0x63: { // B-type (branches)
imm = ((instr >> 7) & 0x1E) | ((instr >> 20) & 0x7E0) | imm = ((instr >> 7) & 0x1E) | ((instr >> 20) & 0x7E0) |
((instr >> 19) & 0x800) | ((instr >> 31) << 12); ((instr >> 19) & 0x800) | ((instr >> 31) << 12);
imm = sign_extend(imm, 13); // Sign-extend 13-bit immediate imm = sign_extend(imm, 13); // Sign-extend 13-bit immediate
if (funct3 == 0x0) { // BEQ if (funct3 == 0x0) { // BEQ
if (registers[rs1] == registers[rs2]) { if (registers[rs1] == registers[rs2]) {
pc += imm - 4; // Offset PC (adjust for pre-increment) pc += imm - 4; // Offset PC (adjust for pre-increment)
}
} else if (funct3 == 0x1) { // BNE
if (registers[rs1] != registers[rs2]) {
pc += imm - 4; // Offset PC
}
} else {
throw std::runtime_error("Unknown B-type instruction");
} }
break; } else if (funct3 == 0x1) { // BNE
if (registers[rs1] != registers[rs2]) {
pc += imm - 4; // Offset PC
}
} else if (funct3 == 0x4) { // BLT
if (static_cast<int32_t>(registers[rs1]) <
static_cast<int32_t>(registers[rs2])) {
pc += imm - 4;
}
} else if (funct3 == 0x5) { // BGE
if (static_cast<int32_t>(registers[rs1]) >=
static_cast<int32_t>(registers[rs2])) {
pc += imm - 4;
}
} else if (funct3 == 0x6) { // BLTU
if (registers[rs1] < registers[rs2]) pc += imm - 4;
} else if (funct3 == 0x7) { // BGEU
if (registers[rs1] >= registers[rs2]) pc += imm - 4;
} else {
throw std::runtime_error("Unknown B-type instruction");
}
break;
} }
case 0x03: { // I-type (loads) case 0x03: { // I-type (loads)
imm = sign_extend(instr >> 20, 12); // Extract 12-bit immediate imm = sign_extend(instr >> 20, 12); // Extract 12-bit immediate