The following MIPS function processes an array and returns two values in $v0 and
ID: 3545053 • Letter: T
Question
The following MIPS function processes an array and returns two values in $v0 and
$v1. Assuming that the array consists of 5000 words indexed 0 through 4999, and its base address is stored in $a0 and its size (5000) in $a1, comment all lines and describe in a sentence or two what this code does. Specifically, what will be returned in $v0 and $v1?
add $a1, $a1, $a1
add $a1, $a1, $a1
add $v0, $zero, $zero
add $t0, $zero, $zero
outer: add $t4, $a0, $t0
lw $t4, 0($t4)
add $t5, $zero, $zero
add $t1, $zero, $zero
inner: add $t3, $a0, $t1
lw $t3, 0($t3)
bne $t3, $t4, skip
addi $t5, $t5, 1
skip: addi $t1, $t1, 4
bne $t1, $a1, inner
slt $t2, $t5, $v0
bne $t2, $zero, next
add $v0, $t5, $zero
add $v1, $t4, $zero
next: addi $t0, $t0, 4
bne $t0, $a1, outer
Explanation / Answer
add $a1, $a1, $a1 # $a1 = 5000 * 2
add $a1, $a1, $a1 # $a1 = 5000 * 4
add $v0, $zero, $zero # $v0 = 0
add $t0, $zero, $zero # $t0 = 0
outer: add $t4, $a0, $t0 # $t4 = address A[i]
lw $t4, 0($t4) # $t4 = A[i]
add $t5, $zero, $zero # $t5 = count = 0
add $t1, $zero, $zero # $t1 = 0
inner: add $t3, $a0, $t1 # $t3 = address A[j]
lw $t3, 0($t3) # $t3 = A[j]
bne $t3, $t4, skip # if (A[i]!=A[j]) skip
addi $t5, $t5, 1 # count++
skip: addi $t1, $t1, 4 # j = j+4
bne $t1, $a1, inner # inner loop = 5000
slt $t2, $t5, $v0 # if (count < $v0)
bne $t2, $zero, next # then goto next
add $v0, $t5, $zero # $v0 = count
add $v1, $t4, $zero # $v1 = A[i]
next: addi $t0, $t0, 4 # i = i+4
bne $t0, $a1, outer # outer loop = 5000
This code compares every element in the array against all elements for identical
matches. It counts the frequency of occurrence of each value in the array. The
count of the most frequently used value is returned in $v0 and the value itself is
returned in $v1.