This is a sort of hash function of 32-bit values where you can add and remove values in any order and you get the same result. I.e.
let mut hash_0 = MemHash::default();
hash_0.add(4);
hash_0.add(9);
hash_0.remove(2);
hash_0.add(9);
hash_0.remove(1);
let mut hash_1 = MemHash::default();
hash_1.remove(2);
hash_1.add(9);
hash_1.add(9);
hash_1.remove(1);
hash_1.add(4);
assert_eq!(hash_0.value(), hash_1.value());The intended use case was for CPU lockstep verification. To verify a CPU we run the same program on a simulation of the CPU in a SystemVerilog simulator (Questa, VCS, Xcelium or Verilator) and also on a model (sail-riscv, Spike, Whisper, etc).
The robust way to verify stores is to record memory accesses for each instruction from the DUT and model and compare them.
A not-as-good but much easier to set up alternative is to compare the contents of all memory after each instruction. This isn't as good because you can't record things like PMAs for the accesses (which can be affected by PBMT), idempotent stores are ignored, etc. But it doesn't require instrumentation so it's easier to set up.
Another situation where it can be helpful is if an instruction is executed in very different ways on the DUT and model. For example on the model a vector instruction is probably executed in one go, but on the DUT it might be broken down into micro-ops.
However hashing all memory is going to be very slow if you do it naively. This hash function is supposed to make it faster, so you do:
fn write(&mut self, address: u32, data: u8) {
let old_value = (address << 8) | self.memory[address] as u32;
let new_value = (address << 8) | data as u32;
self.memory[address] = data;
this.memhash.remove(old_value);
this.memhash.add(new_value);
}
Almost certainly a terribly weak hash, but it shouldn't matter for the intended application which is to catch DUT bugs.
Only tested as far as an example main() which does the same set of operations in a bunch of different orders and prints out the hashes. If you cargo run you should see the same value printed a bunch of times.
No.