Another Loop Example in MIPS


Another Loop Example: Reading from and Writing to an Array

        /* Double every value in A */
        int i;
        for ( i = 0; i < numVals; i++ )
        {
            A[i] *= 2;      /* which means A[i] = A[i] * 2 */
        }


CMIPS Equivalent
/* Double every value in A */
{ /* A[i] = A[i] * 2 */ int x = A[i]; x *= 2; A[i] = x;
        # $s6 = A, $s7 = numVals
        # $t0 = i, $t4 = x
        addi $t0, $zero, 0
LOOP:   slt $t1, $t0, $s7
        beq $t1, $zero, ENDLP

        # Calculate address of A[i]
        sll $t1, $t0, 2
        add $t1, $s6, $t1
        # Read value at A[i] into x; etc
        lw  $t4, 0($t1)
        sll $t4, $t4, 1
        sw  $t4, 0($t1)

        addi $t0, $t0, 1
        j LOOP
ENDLP:
        ⋮ 


# $t0 = i = 0
# $t1 = 1 if i < numVals
# Leave loop if i >= numVals


# $t1 = 4 * i (shift left 2)
# t1 = A + 4i, i.e., &A[i]

# Read A[i] into $t4 (x)
# x *= 2 (shift left 1)
# Store $t4 out to A[i]

# Increment i
# Jump to top of loop

More Complex Loop Pattern — Less Intuitive, More Efficient


Alyce Brady, Kalamazoo College