lw and sw hazards example MIPS

The below example confused me:

lw $r0, 4($r0)
sw $r0, 4($r0)
add $r0,$r0, $r0  Using MIPS 5 stage execution what are the hazards we have 1) without forwarding 2) with forwarding only in the stage of execution (exe or alu) 3) with forwarding. Add nops to eliminate hazards. • Happy to help, let know where you've got confused. – Isu Jun 21 '17 at 15:34 • What did you try? Where did you get stuck? We're happy to help you understand the concepts but just solving homework-style exercises for you is unlikely to really do that. Perhaps try to think about why you can't solve this yourself, and ask a question about that. – David Richerby Jun 21 '17 at 15:42 • @Isu i know that the result of lw wont be available until the end of 4 stage and sw needs it in the end of 2nd stage so i think we need to add two nops between lw and sw. Then the register that add needs to decode needs also results that wont get till sw ends after 3rd stage so one nop between sw and add. So there are two data hazards. In 2 same thing with lw and sw but no need for nop for sw and add since we can forward results for exe stage. And 3 one nop for lw and sw and then we can forward results. Is that right ? – alexbako Jun 21 '17 at 16:33 • @DavidRicherby here my understanding ^ – alexbako Jun 21 '17 at 16:35 • This question seems off-topic, since it's about a specific CPU. – Yuval Filmus Jun 21 '17 at 18:46 2 Answers The hazard stems from the fact that the lw instruction updates register \$r0 at the 5th stage of the pipe (write-back) while the sw and the add instructions require the updated data at the 2nd stage of the pipe (decode/read).

Putting everything on a single time line (assuming the lw execution begins at time $t=1$), the correct value of \$r0 will be available not before$t=4$and the other instructions must be stalled (at the decoding phase) until this data is available. After$t=4$a forwarding unit can be used to forward the data to the correct place, e.g., to the execution stage for the sw or to the decoding stage for the add (if needed). Look at data dependecies: lw$r0, 4($r0) sw$r0, 4($r0) add$r0, $r0,$r0


At line 1, $r0 is being written to. At line 2, $r0 is being read. Therefore we have a RAW hazard, read after write.

There is also a WAR hazard between line 2 and 3 because the register is being written after reading it.