## Week-7 Questions
### Topic : Superscalar
#### Question : The example shows RAW dependency. Explain the software and hardware techniques to solve the problem.

**RAW (Read After Write):**
* A type of data hazard that occurs when an instruction needs to read a register or memory location before a previous instruction has finished writing to it.
* During pipeline execution, if the previous instruction has not yet completed the write operation, the subsequent instruction will read incorrect or incomplete data, leading to a hazard.
**Solving this issue:**
1. Software techniques: **Reordering the code sequence by inserting nop**
2. Hardware techniques: **Data forwarding**
---
#### Question : Identify the load-to-use harzards? And reorder the instruction to eliminate it.

1. Load-use hazard
* r1: `add r3, r1, r2` after `lw r1, b`
* r2: `add r3, r1, r2` after `lw r2, e`
* r4: `add r5, r1, r4` after `lw r4, f`
2. Reorder the instructions
Assume with hazard detection units and forwarding units. Previous `load` instructions can forward from `MEM` stage to the `EX` stage in the later instructions.
```RISCV=
lw r1, b
lw r2, e
lw r4, f
add r3, r1, r2
add r5, r1, r4
sw r3, a
sw r5, c
```
---
#### Question : Identify RAW, WAW, WAR dependency. Use Register renaming to eliminate WAW, WAR dependency

1. Data dependencies
* RAW
* r1: `sub r3, r2, r1` after `add r1, r2, r3`
* r1: `div r2, r1, r3` after `add r1, r2, r3`
* r1: `div r2, r1, r3` after `mul r1, r2, r3`
* r3: `mul r1, r2, r3` after `sub r3, r2, r1`
* r3: `div r2, r1, r3` after `sub r3, r2, r1`
* WAW
* r1: `mul r1, r2, r3` after `add r1, r2, r3`
* WAR
* r3: `sub r3, r2, r1` after `add r1, r2, r3`
* r1: `mul r1, r2, r3` after `sub r3, r2, r1`
* r2: `div r2, r1, r3` after `mul r1, r2, r3`
2. Register renaming
| Instruction | Original | Renamed Instruction | Register Renaming |
| ----------- | ------------------ | ------------------- | -------------------------------- |
| 1 | `add r1, r2, r3` | `add r14, r2, r3` | r1 → 14 |
| 2 | `sub r3, r2, r1` | `sub r15, r2, r14` | r3 → 15, r1 → 14 (read) |
| 3 | `mul r1, r2, r3` | `mul r16, r2, r15` | r1 → 16, r3 → 15 (read) |
| 4 | `div r2, r1, r3` | `div r17, r16, r15` | r2 → 17, r1 → 16, r3 → 15 (read) |
| Instruction | r1 | r2 | r3 |
| ---------------- | -- | -- | -- |
| Initial Mapping | 11 | 12 | 13 |
| `add r1, r2, r3` | 14 | 12 | 13 |
| `sub r3, r2, r1` | 14 | 12 | 15 |
| `mul r1, r2, r3` | 16 | 12 | 15 |
| `div r2, r1, r3` | 16 | 17 | 15 |