Regarding the MIPS assembly language which is thought in the pattersson's book, I have a question with inserting NOP between instructions to avoid pipeline stalls.
Consider the following code
lw $s5, -16($s5)
sw $s5, -16($s5)
add $s5, $s5, $s5
We see there is a RAW hazard for $s5 between lw
and sw
. There is also a WAW hazard for $s5 betwween sw
and add
. So we have to insert two NOPs to avoid stalls. In other words, the pipeline diagram is
lw IF ID EX MEM WB
sw IF ID --- EX MEM WB
add IF ID EX MEM -- WB
When sw
is going to be executed, it has be wait for lw
to put the data in a register. Therefore, there is one bubble. Also, when add
wants to write the final result, it has to wait for the completion of the previous instruction (sw
). That is another bubble.
So the modified code is
lw
NOP
sw
NOP
add
But the solution propose the following code
lw
NOP
NOP
sw
add
Which one is correct? I think mine!