Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this MIPS assembly code correspond to?

I am learning MIPS assembly language. This is an exercise I am trying to understand. The question is:

What does the following code correspond to?

Name:   move    $t0,    $zero
Loop:   add     $t1,    $t0,    $t0
        add     $t1,    $t1,    $t1
        add     $t2,    $a0,    $t1
        sw      $zero,  0($t2)
        addi    $t0,    $t0,    1
        slt     $t3,    $t0,    $a1
        bne     $t3,    $zero,  Loop
        jr      $ra

I already know the meaning of each instruction, how the directives work and what a for loop is. When I try to run the code in MIPS Mars Simulator it ends with error, probably because values contained in the registers $a0 and $a1 are needed to begin with.

I don't get the bigger picture. What happens during each loop iteration? Is it just a part of a bigger algorithm? What is it supposed to do?

like image 797
firstName lastName Avatar asked Jul 16 '26 15:07

firstName lastName


1 Answers

Reading the comments I guess the answer is somehow clearer. At the beginning of the code, $a0 and $a1 should already have some value, let's suppose x and y respectively.

The first line move $t0, $zero would be int i = 0; in high level programming language, or the initial value of a do-while (condition) loop.

The following:

Loop: add $t1, $t0, $t0
      add $t1, $t1, $t1

is when the loop begins and would be like:

int j = 2 * i;
    j = 2 * j;

which shortly means int j = 4 * i; , the iterator is multiplied by 4 because MIPS registers are made of 32 bits, which means 4 bytes.

Then add $t2, $a0, $t1 corresponds to int k = x + j; or in other words to int k = x + 4 * i.

The next instruction sw $zero, 0($t2) stores 0 into the memory whose address is offset by 0 from the address of the value contained in $t2.

addi $t0, $t0, 1 increments i++; and

slt  $t3,  $t0,   $a1
bne  $t3,  $zero, Loop
jr   $ra

checks if i < y is satisfied, which is the condition of the do - while (i < y) loop. In case it is still true, the loop goes on setting to 0 the next element in memory, otherwise the loop ends returning to $ra.

like image 168
firstName lastName Avatar answered Jul 19 '26 08:07

firstName lastName