owned this note
owned this note
Published
Linked with GitHub
# Lab1: R32I Simulator
**Introduce:**
https://en.wikipedia.org/wiki/Tower_of_Hanoi
**C code**
```cpp=
#include <stdio.h>
const int ans=0;
void hanoi(int n, char A, char B, char C) {
if(n == 1)
ans++;
else {
hanoi(n-1, A, C, B);
hanoi(1, A, B, C);
hanoi(n-1, B, A, C);
}
}
int main() {
int n=7;
hanoi(n, 'A', 'B', 'C');
return 0;
}
```
**Assembly code**
```cpp=
main:
addi a2, zero, 7
addi a0, zero, 0
jal honoi
j end
honoi:
addi sp, sp, -8
sw ra, 4(sp)
sw a2, 0(sp)
addi t0, zero, 1
beq a2, t0, re
addi a2, a2, -1
jal honoi
addi a0, a0, 1
jal honoi
lw ra, 4(sp)
lw a2, 0(sp)
addi sp, sp, 8
jr ra
re:
addi sp, sp, 8
addi a0, a0, 1
jr ra
end:
```
**Explanation for assembly code**
my code has three part:
main:
1.define number of tower
2.reset the number of moving tower
3.call recursive
4.end
honoi:
1.call recursive
2.calculate the number of moving tower
re:
1.return recursive
2.calculater the number of moving tower
recursive part:
Store the address & n in the stack

Check the end of recursive (n=0)
YES->return
NO ->call recursive


End of recursive

**Ripes analysis**
Ripe has five stage:
1.Instruction fetch(IF):
The instruction will be fetched depending on the Program Counter, which points
the address of the instruction.
2.Instruction decode and register fetch(ID):
Decoder Instruction. It has six types of instructioin.
(1)R-Format
(2)I-Format
(3)S-Format
(4)SB-Format
(5)U-Format
(6)UJ-Format

3.Execute(EX):
This stage will execute the operation
4.Memory access(MEM):
Store the result which executed into memory,get data from memory or go to next
stage, according to opcode.
5.Register write back(WB):
Write the result into register file.
**Hazard in pipeline**
Hazards are problems in pipeline when the next instruction can't execute in the following clock cycle, and can potentially lead to incorrect computation results.
Three common types of hazards are data hazards.
1.Structural hazards:
Hardware resource is not enough
2.Data hazards:
Data hazards occur when instructions that exhibit data dependence modify data
in different stages of a pipeline.
There are three situations in which a data hazard can occur:
read after write (RAW), true dependency
write after read (WAR)
write after write (WAW)
3.Control hazards (branch hazards):
Control hazard occurs when the pipeline makes wrong decisions on branch
prediction and therefore brings instructions into the pipeline that must
subsequently be discarded.
In my code, only control hazard happended

Ripe adds two nops to solve the hazard