Move registers and pc counter to the VM class
This commit is contained in:
parent
78a2a460e8
commit
fd67be0d89
2 changed files with 15 additions and 11 deletions
20
src/vm.cpp
20
src/vm.cpp
|
@ -7,7 +7,6 @@
|
|||
#include <vector>
|
||||
#include <fstream>
|
||||
|
||||
const int NUM_REGISTERS = 32; // Standard RISC-V has 32 registers
|
||||
|
||||
inline int32_t sign_extend(int32_t value, int bits) {
|
||||
int32_t mask = 1 << (bits - 1);
|
||||
|
@ -53,22 +52,21 @@ std::vector<uint8_t> VM::read_memory(size_t start, size_t size) {
|
|||
memory_.begin() + start + size);
|
||||
}
|
||||
|
||||
uint32_t VM::read_register(size_t regnum) {
|
||||
if (regnum >= NUM_REGISTERS) {
|
||||
throw std::runtime_error("Register out of range");
|
||||
}
|
||||
|
||||
return registers[regnum];
|
||||
}
|
||||
|
||||
void VM::eval() {
|
||||
size_t memory_size = memory_.size();
|
||||
uint8_t *memory = &memory_[0];
|
||||
|
||||
uint32_t registers[NUM_REGISTERS] = {0};
|
||||
uint32_t pc = 0;
|
||||
|
||||
auto fetch_instruction = [&memory, &pc]() -> uint32_t {
|
||||
uint32_t instruction = 0;
|
||||
std::memcpy(&instruction, memory + pc, sizeof(uint32_t)); // Load 4 bytes (little-endian)
|
||||
return instruction;
|
||||
};
|
||||
|
||||
bool running = true;
|
||||
while (pc < memory_size && running) {
|
||||
uint32_t instr = fetch_instruction();
|
||||
uint32_t instr = *(uint32_t*)&memory[pc];
|
||||
if (instr == 0) break;
|
||||
//std::cout << "pc: " << std::hex << pc << std::dec << "\n";
|
||||
// std::cout << "instr: " << std::hex << instr << "\n";
|
||||
|
|
|
@ -5,6 +5,8 @@
|
|||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
const int NUM_REGISTERS = 32; // Standard RISC-V has 32 registers
|
||||
|
||||
std::vector<uint8_t> load_program(const std::string& filename, size_t memory_size);
|
||||
|
||||
class VM {
|
||||
|
@ -14,7 +16,11 @@ public:
|
|||
void eval();
|
||||
|
||||
std::vector<uint8_t> read_memory(size_t start, size_t size);
|
||||
uint32_t read_register(size_t regnum);
|
||||
|
||||
private:
|
||||
std::vector<uint8_t> memory_;
|
||||
|
||||
uint32_t registers[NUM_REGISTERS] = {0};
|
||||
uint32_t pc = 0;
|
||||
};
|
||||
|
|
Loading…
Reference in a new issue