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,7 +136,7 @@ void eval(uint8_t* memory, size_t memory_size) {
}
break;
}
case 0x63: { // B-type (BEQ, BNE)
case 0x63: { // B-type (branches)
imm = ((instr >> 7) & 0x1E) | ((instr >> 20) & 0x7E0) |
((instr >> 19) & 0x800) | ((instr >> 31) << 12);
imm = sign_extend(imm, 13); // Sign-extend 13-bit immediate
@ -148,6 +148,20 @@ void eval(uint8_t* memory, size_t memory_size) {
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");
}