MIPS Assembly Language Programming

Examples of Converting C to Assembly

Suppose we have the following at the start of our assembly language file:

.data
array:   .space 200
x:       .word  5

.text
__start:

Global (non-array) variable access

What assembly language could we write to add the integer 3 to the global variable x (i.e. the location labelled x)?

First load the value of the variable x into a register. Remember that global variables are accessed using the global pointer register.

         lw      $t0, x($gp)

Do the addition:

         addi    $t0, $t0, 3

Store the value back. We can leave this step until we need to use $t0 for something else.

         sw      $t0, x($gp)

Array access

What assembly language could we write to store the integer 2 at the array index given by the variable x?

We know what the start address of the array is. We need to add a value to obtain the address of array as indexed by the variable x. The value we actually need depends on the size of each element of the array. Let us assume they are words. The value we need to add is thus the value stored in x * 4 bytes.

First we need to get the start address of the array.

         addi    $t0, $gp, array

Load the value of x into a register, multiply it by 4 and add it to the start address of the array:

         lw      $t1, x($gp)
         addi    $t1, $t1, $t1  # Double $t1
         addi    $t1, $t1, $t1  # Double $t1 again
         addi    $t0, $t0, $t1

Put the value 2 into a register. Remember register $zero always holds the value zero.

         addi    $t1, $zero, 2  # Put 2 into $t1

Finally store 2 into the array element:

         sw      $t1, 0($t0)

Note that in binary, multiplying by four is the same as shifting left by two bits. Thus we could have replaced this code:

         lw      $t1, x($gp)
         addi    $t1, $t1, $t1  # Double $t1
         addi    $t1, $t1, $t1  # Double $t1 again
         addi    $t0, $t0, $t1

with:

         lw      $t1, x($gp)
         sll     $t1, $t1, 2    # Multiply $t1 by 4
         addi    $t0, $t0, $t1


CSE 378 Spring 2002 - Section 3
First Previous Page 2 Next Last