Valhalla Legends Archive

Programming => General Programming => Assembly Language (any cpu) => Topic started by: iago on November 05, 2003, 08:01 PM

Title: Does this make any sense?
Post by: iago on November 05, 2003, 08:01 PM
This is MIPS, a toy assembly language.
beq = branch-if-equal
lw = load word
Most instructions are: op dest, src, src
Registers are anything beginnning with $ (usually there are specific ones, but this isn't real code).

The question is, optimize this code to use the delayed branch slot..  What that means is, because of pipelining, the instruction after the instruction immediately after the branch will be executed before it, but can be dangerous if the instruction changes the data used in the branch, so you have to be careful (most people will put a nop there for safety).  Anyway, here's the code:
Loop:
lw $2, 100($3)
addi $3, $3, 4
beq $3, $4, Loop


What I did was:
Loop:
addi $3, $3, 4
beq $3, $4, Loop
lw $2, 96($3) <-- delay slot, executed before the loop


Does this seem silly to anybody else?  It seems like the lw doesn't even have to be PART of the loop, right?
Title: Re:Does this make any sense?
Post by: Yoni on November 06, 2003, 10:17 AM
Wrong.

In the first snippet, $2 receives the value of $3 before 4 is added to it for the last time, meaning it gets the value ($3 - 4).
In the second snippet, $2 gets the value of $3 after 4 is added to it, meaning it gets the value ($3).

Dunno anything about MIPS so I can't give optimization tips. But, I observe that this (first) code is equivalent to (pseudo):

$2 = $4 - 4
$3 = $4

So, why is a loop required at all?

I might be misreading the lw instruction though...
Title: Re:Does this make any sense?
Post by: iago on November 06, 2003, 11:51 AM
The first is actually closer to thie:
Loop:
lw $2, 100($3)
addi $3, $3, 4
beq $3, $4, Loop
=
do
*$2 = $3[100];
$3 += 4
while $3 != $4

Hopefully, I guess, $4 is a multiple of $3.  
Your code will work, *except* it won't cause an infinite loop 3/4 of the time :P
Title: Re:Does this make any sense?
Post by: Adron on November 07, 2003, 04:26 AM
It could be a "ProbeForRead"-like function?