From 21622321994b96dac81ca19936cd8213b117aa12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Autin?= Date: Mon, 27 Mar 2023 15:37:30 +0200 Subject: [PATCH] :recycle: Simplified branch_instruction --- src/simulator/machine.rs | 47 +++++++++++----------------------------- 1 file changed, 13 insertions(+), 34 deletions(-) diff --git a/src/simulator/machine.rs b/src/simulator/machine.rs index 99c70ba..b9aa48e 100644 --- a/src/simulator/machine.rs +++ b/src/simulator/machine.rs @@ -308,40 +308,19 @@ impl Machine { /// Treatement for Branch instructions fn branch_instruction(&mut self, inst: Instruction) -> Result<(), MachineError> { - match inst.funct3 { - RISCV_BR_BEQ => { - if self.int_reg.get_reg(inst.rs1) == self.int_reg.get_reg(inst.rs2) { - self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; - } - }, - RISCV_BR_BNE => { - if self.int_reg.get_reg(inst.rs1) != self.int_reg.get_reg(inst.rs2) { - self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; - } - }, - RISCV_BR_BLT => { - if self.int_reg.get_reg(inst.rs1) < self.int_reg.get_reg(inst.rs2) { - self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; - } - }, - RISCV_BR_BGE => { - if self.int_reg.get_reg(inst.rs1) >= self.int_reg.get_reg(inst.rs2) { - self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; - } - }, - RISCV_BR_BLTU => { - if self.int_reg.get_reg(inst.rs1) < self.int_reg.get_reg(inst.rs2) { - self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; - } - }, - RISCV_BR_BGEU => { - if self.int_reg.get_reg(inst.rs1) >= self.int_reg.get_reg(inst.rs2) { - self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; - } - }, - _ => { - panic!("In BR switch case, this should never happen... Instr was {}", inst.value); - } + let op = match inst.funct3 { + RISCV_BR_BEQ => |a, b| a == b, + RISCV_BR_BNE => |a, b| a != b, + RISCV_BR_BLT => |a, b| a < b, + RISCV_BR_BGE => |a, b| a >= b, + RISCV_BR_BLTU => |a, b| a < b, + RISCV_BR_BGEU => |a, b| a >= b, + _ => unreachable!() + }; + let rs1 = self.int_reg.get_reg(inst.rs1); + let rs2 = self.int_reg.get_reg(inst.rs2); + if op(rs1, rs2) { + self.pc = (self.pc as i64 + inst.imm13_signed as i64 - 4) as u64; } Ok(()) }