I was trying to do an assignment translating from C to MIPS but I get a instruction reference error in jal main. Here is what I have to translate:
void swap (int a, int b)
{
int temp=a;
a=b;
b=temp;
}
int distance (int a, int b)
{
if (b > a)
swap (a,b);
return (a-b)
}
And here is what I wrote:
.data #declare the variables
var1: .word 4, 7, 12, 5
var2: .word 15, 3, 6, 14
result: .space 4
.text
main:
la $t0, var1 #load address 'var1' into $t0
la $t1, var2 #load address 'var2' into $t1
la $t2, result #load address 'result' into $t2
li $t3, 0 # load imm (i=0)
for_loop:
bgt $t3, 4, for_done #when i>4 do not meet condition, exit
lw $t4, 0($t4) #result[i] = tmp
jal distance
addi $t3, $t3, 1 #i++
j for_loop
for_done:
la $t2, distance
ori $v0, $0, 4
syscall
distance:
blt $t0, $t1, exit
jal swap
sub $t5, $t0, $t1
jr $t5
swap:
lw $t6, 0($t0)
lw $t7, 0($t1)
sw $t6, 0($t1)
sw $t7, 0($t0)
exit:
I actually don't know what am I doing, just the basics of Assembly. I hope some of you could help me. :)
I'm sorry but your asm code had [at least] 15 bugs.
I've created two versions: one with the bugs annotated and a second with the bugs fixed and a working program
Note that due to the vagueness of the C code, I had to guess the true intent of the program and take [considerable] poetic license.
Here's the unchanged version with the bugs annotated [please pardon the gratuitous style cleanup]:
.data # declare the variables
var1: .word 4, 7, 12, 5
var2: .word 15, 3, 6, 14
# NOTE/BUG: this only reserves 4 bytes instead of the 16 we need to hold all
# four values
result: .space 4
.text
main:
la $t0,var1 # load address 'var1' into $t0
la $t1,var2 # load address 'var2' into $t1
la $t2,result # load address 'result' into $t2
li $t3,0 # load imm (i=0)
for_loop:
# NOTE/BUG: this goes one too far (i.e. we want i>=4)
bgt $t3,4,for_done # when i>4 do not meet condition, exit
# NOTE/BUG: $t4 is never intialized to anything, so this instruction will fault
# (e.g. equivalent to dererencing a null pointer in C)
lw $t4,0($t4) # result[i] = tmp
jal distance
# NOTE/BUG: the index variable 'i' is incremented, but distance does _not_ use
# (i.e.) distance will always use var1[0] and var2[0] on each iteration
addi $t3,$t3,1 # i++
j for_loop
# NOTE/BUG: what do we want to do here? -- print the result vector presumably
# NOTE/BUG: syscall 4 is to print a string -- it would require setting up $a0
# and _not_ $t2 but, even then, using 'distance' is wrong as distance is the
# function name and _not_ a string so we'd get garbage
# NOTE/BUG: we probably wouldn't even get that far because QtSpim would
# probably fault because distance is in the .text segment and not the .data
# segment
for_done:
la $t2,distance
ori $v0,$0,4
syscall
distance:
# NOTE/BUG: this is comparing _addresses_ instead of _values_ (i.e.) this
# compares (&var1[i] > &var2[i]) instead of var1[i] > var2[i])
# NOTE/BUG: this test is _reversed_, because this guarantees negative numbers
blt $t0,$t1,exit
# NOTE/BUG: jal is calling swap as a function, but swap is merely a label here
jal swap
# NOTE/BUG: based on the mips ABI, return values go into $v0
sub $t5,$t0,$t1
# NOTE/BUG: when 'jal distance' is called, the return address goes into $ra
# and to return to the place in main that called us, we want to do 'jr $ra'
# NOTE/BUG: this 'jr' should be at exit:
jr $t5
# NOTE/BUG: this actually swaps var1[i] and var2[i] -- would this be correct to
# modify the original arrays???
swap:
lw $t6,0($t0)
lw $t7,0($t1)
sw $t6,0($t1)
sw $t7,0($t0)
# NOTE/BUG: this is where the 'jr' should go
exit:
Here's the cleaned up and working version. I decided that it should store the distance in the result vector and then show all three vectors:
.data
# NOTE: lw/sw must be four byte aligned so keep these first
var1: .word 4, 7, 12, 5
var2: .word 15, 3, 6, 14
result: .space 16
msg_var1: .asciiz "var1:"
msg_var2: .asciiz "var2:"
msg_result: .asciiz "dist:"
msg_space: .asciiz " "
msg_nl: .asciiz "\n"
.text
main:
la $s0,var1 # load address of 'var1'
la $s1,var2 # load address of 'var2'
la $s2,result # load address of 'result'
li $s3,4 # number of elements in a given vector
li $s4,0 # load imm (i=0)
for_loop:
bge $s4,$s3,for_done # i <= count? if no, fly
jal distance
addi $s4,$s4,1 # i++
j for_loop
for_done:
la $a0,msg_var1
la $a1,var1
jal show
la $a0,msg_var2
la $a1,var2
jal show
la $a0,msg_result
la $a1,result
jal show
# exit program
li $v0,10
syscall
# distance -- calculate distance between two numbers in two vectors
#
# RETURNS:
# stores into 'result' vector
#
# global registers:
# s0 -- pointer to var1
# s1 -- pointer to var2
# s2 -- pointer to result
# s4 -- array index
#
# registers:
# t0 -- address and value of var1[i]
# t1 -- address and value of var2[i]
# t2 -- temp value
# t7 -- byte offset corresponding to index 'i'
distance:
sll $t7,$s4,2 # convert index to byte offset
addu $t0,$s0,$t7 # get &var1[i]
lw $t0,0($t0) # fetch var1[i]
addu $t1,$s1,$t7 # get &var2[i]
lw $t1,0($t1) # fetch var2[i]
bge $t0,$t1,distance_done # swap a/b to get abs val? if no, fly
# swap a/b
move $t2,$t0 # temp = a
move $t0,$t1 # a = b
move $t1,$t2 # b = temp
distance_done:
sub $v0,$t0,$t1 # get distance (i.e.) abs(a-b)
addu $t2,$s2,$t7 # get &result[i]
sw $v0,0($t2) # result[i] = distance
jr $ra # return
# show -- show vector
#
# arguments:
# a0 -- vector name
# a1 -- pointer to vector
#
# registers:
# t3 -- array remaining count
#
# clobbers:
# v0
show:
li $v0,4 # syscall to print string
syscall
move $t3,$s3 # get number of elements in vector
show_loop:
blez $t3,show_done # more to do? if no, fly
li $v0,4
la $a0,msg_space # output a space
syscall
# output vector[i]
li $v0,1 # syscall to output value
lw $a0,0($a1) # get vector value
syscall
addiu $a1,$a1,4 # advance pointer to next array element
addi $t3,$t3,-1 # bump down count
j show_loop
show_done:
# output newline
la $v0,4
la $a0,msg_nl
syscall
jr $ra # return
Related
.org 0x10000000
# Initializations
# NOTE: You may add initializations after line 10, but please do not
# remove or change the initializations to $sp, $s0, $s1, or $s2
li $sp, 0x10fffffc # Starting address of empty stack
li $s0, 0xf0000000 # UART base address
li $s1, array_ptr # Array head pointer
li $s2, array_ptr # Array tail pointer
li $t8 0x00000000
####################################################################
# Do not make changes to the jump to main, the allocation of
# memory for the array, or the main loop
####################################################################
j main
nop
array_ptr: # Label pointing to 100 word array
.space 100
main:
jal poll_UART
nop
jal period_check
nop
jal space_check
nop
jal case_check
nop
jal array_push
nop
j main
nop
####################################################################
# ******************************************************************
####################################################################
# The "poll_UART" function should poll the status register of the UART.
# If the 2^1 bit position (ready bit) is set to 1 then it
# should copy the receive buffer's value into $v0 and send
# a clear status command (2^1) to the command register before
# returning (a return statement is already included). In order to
# receive full credit, $s0 must contain the base address of the UART
# and must be used with the appropriate offsets to access UART
# registers and buffers
poll_UART:
lw $t1, 4($s0)
li $t2, 0b10
and $t3, $t1, $t2
beq $t3, $0, main
nop
lw $v0, 8($s0)
sw $t2, 0($s0)
jr $ra
nop
# The "period_check" function should check if the current character ($v0)
# is a period ("."). If it is a period then the function should go to the
# label, "palindrome_check". If the character is not a period then it
# should use the included return.
period_check:
li $t0, 0x2E
beq $v0, $t0, palindrome_check
nop
jr $ra
nop
# The "space_check" function should check if the current character ($v0)
# is a space (" "). If it is then it should jump to "main" so
# that it skips saving the space character. If not it should
# use the included return.
space_check:
li $t4, 0x20
beq $t4, $v0, main
nop
jr $ra
nop
# The "case_check" function should perform a single inequality check.
# If the current character ($v0) is greater than the ASCII value of 'Z',
# which indicates the current character is lowercase, then it should convert
# the value of $v0 to the uppercase equivalent and then return. If the
# current character ($v0) is already uppercase (meaning the inequality
# mentioned before was not true) then the function should return without
# performing a conversion.
case_check:
li $t5, 0x5A
slt $t6, $v0, $t5
li $t7, 1
beq $t6, $t7, change_uppercase
change_uppercase:
addiu $v0, $v0, -32
jr $ra
nop
# The "array_push" function should save the current character ($v0) to the
# current location of the tail pointer, $s2. Then it should increment the
# tail pointer so that it points to the next element of the array. Last
# it should use the included return statement.
array_push:
sw $v0, 0($s2)
addiu $s2, $s2, 4
jr $ra
nop
# The "palindrome_check" subroutine should be jumped to by the period
# check function if a period is encountered. This subroutine should contain
# a loop that traverses the array from the front towards the back (using the
# head pointer, $s1) and from the back towards the front(using the tail
# pointer, $s2). If the string is a palindrome then as the array is traversed
# the characters pointed to should be equal. If the characters are not equal
# then the string is not a palindrome and the print function should be used
# to print "No". If the pointers cross (i.e. the head pointer's address is
# greater than or equal to the tail pointer's address) and the compared
# characters are equal then the string is a palindrome and "Yes" should be
# printed.
#
# Remember to restore the head and tail pointers to the first element
# of the array before the subroutine jumps back to main to begin processing the
# next string. Also, keep in mind that because the tail pointer is updated at
# the end of "array_push" it technically points one element past the last
# character in the array. You will need to compensate for this by either
# decrementing the pointer once at the start of the array or using an offset
# from this pointer's address.
palindrome_check:
addiu $s2, $s2, -8
move $s3, $s1
subu $s4, $s2, $s3
beq $s4, $0, palindrome
nop
check_loop:
lw $s5, 0($s3)
lw $s6, 0($s2)
bne $s6, $t5, not_palindrome
nop
adjust_pointers:
addiu $s2, $s2, -4
addiu $s3, $s3, 4
slt $t8, $s3, $s2
bne $t8, $0, check_loop
nop
j palindrome
nop
palindrome:
li $a0, 1
call project3_print
move $s2, $s1
j main
nop
not_palindrome:
li $a0, 0
call project3_print
move $s2, $s1
j main
nop
I have tried working on debugging the Palindrome check and everything under that but it all appears fine. Im not sure if the problem remains in the poll_uart or not. this is the template I was given.
When I type in racecar it says no. when I type in gn. it says yes. when I type in night. it says no. So I am just confused.
I am working on a project which checks if a word is a palindrome and sends back "yes" or "no". For example the input "abba. data. abcd. reviver." should read "yes" "no" "no" "yes". Instead what I get is all "no". I have done some debugging and from what I can tell I am missing something in the palindrome_loop that is saying everything is not a palindrome. I am very new to all this so I am sorry if I sound uneducated in all this and kind of lost, but I am unsure of what else to do next any guidance or feedback is appreciated.
I am using PLPtool
Below is my code:
.org 0x10000000
# Initializations
# NOTE: You may add initializations after line 10, but please do not
# remove or change the initializations to $sp, $s0, $s1, or $s2
li $sp, 0x10fffffc # Starting address of empty stack
li $s0, 0xf0000000 # UART base address
li $s1, array_ptr # Array head pointer
li $s2, array_ptr # Array tail pointer
####################################################################
# Do not make changes to the jump to main, the allocation of
# memory for the array, or the main loop
####################################################################
j main
nop
array_ptr: # Label pointing to 100 word array
.space 100
main:
jal poll_UART
nop
jal period_check
nop
jal space_check
nop
jal case_check
nop
jal array_push
nop
j main
nop
####################################################################
# ******************************************************************
####################################################################
# The "poll_UART" function should poll the status register of the UART.
# If the 2^1 bit position (ready bit) is set to 1 then it
# should copy the receive buffer's value into $v0 and send
# a clear status command (2^1) to the command register before
# returning (a return statement is already included). In order to
# receive full credit, $s0 must contain the base address of the UART
# and must be used with the appropriate offsets to access UART
# registers and buffers
poll_UART:
lw $t1, 4($s0)
li $t2, 0b10
and $t3, $t2, $t1
beq $t3, $zero, main
nop
lw $v0, 8($s0)
sw $t2, 0($s0)
jr $ra
nop
# The "period_check" function should check if the current character ($v0)
# is a period ("."). If it is a period then the function should go to the
# label, "palindrome_check". If the character is not a period then it
# should use the included return.
period_check:
li $t0, 0x2E
beq $v0, $t0, palindrome_check
nop
jr $ra
nop
# The "space_check" function should check if the current character ($v0)
# is a space (" "). If it is then it should jump to "main" so
# that it skips saving the space character. If not it should
# use the included return.
space_check:
li $t4, 0x20
beq $t4, $v0, main
jr $ra
nop
# The "case_check" function should perform a single inequality check.
# If the current character ($v0) is greater than the ASCII value of 'Z',
# which indicates the current character is lowercase, then it should convert
# the value of $v0 to the uppercase equivalent and then return. If the
# current character ($v0) is already uppercase (meaning the inequality
# mentioned before was not true) then the function should return without
# performing a conversion.
case_check:
li $t5, 0x5A
slt $t6, $v0, $t5
li $t7, 1
beq $t6, $t7, convert_lowercase
nop
convert_lowercase:
addiu $v0, $v0, -32
jr $ra
nop
# The "array_push" function should save the current character ($v0) to the
# current location of the tail pointer, $s2. Then it should increment the
# tail pointer so that it points to the next element of the array. Last
# it should use the included return statement.
array_push:
sw $v0, 0($s2)
addiu $s2, $s2, 4
jr $ra
nop
# The "palindrome_check" subroutine should be jumped to by the period
# check function if a period is encountered. This subroutine should contain
# a loop that traverses the array from the front towards the back (using the
# head pointer, $s1) and from the back towards the front(using the tail
# pointer, $s2). If the string is a palindrome then as the array is traversed
# the characters pointed to should be equal. If the characters are not equal
# then the string is not a palindrome and the print function should be used
# to print "No". If the pointers cross (i.e. the head pointer's address is
# greater than or equal to the tail pointer's address) and the compared
# characters are equal then the string is a palindrome and "Yes" should be
# printed.
#
# Remember to restore the head and tail pointers to the first element
# of the array before the subroutine jumps back to main to begin processing the
# next string. Also, keep in mind that because the tail pointer is updated at
# the end of "array_push" it technically points one element past the last
# character in the array. You will need to compensate for this by either
# decrementing the pointer once at the start of the array or using an offset
# from this pointer's address.
palindrome_check:
addiu $s2, $s2, -8
move $s3, $s1
subu $s6, $s2, $s3
beq $s6, $zero, palindrome
nop
palindrome_loop:
lw $s4, 0($s3)
lw $s5, 0($s2)
bne $s5, $t0, not_a_palindrome
nop
pointer_adjust:
addiu $s2, $s2, -4
addiu $s3, $s3, 4
slt $t8, $s3, $s2
bne $t8, $t0, palindrome_loop
nop
j palindrome
nop
palindrome:
li $a0, 1
call project3_print
move $s2, $s1
j main
nop
not_a_palindrome:
li $a0, 0
call project3_print
move $s2, $s1
j main
nop
My question is about procedures in MIPS and using arguments.
I'm trying to translate this small C Function to MIPS and I wasn't sure if I was in the right track. This is the C function:
0 int countNegatives(int table[] , int n) {
1 int count = 0;
2 int i;
3
4 for (i=0; i<n; i++) {
5 if (table[i] <0) {
6 count++;
7 }
8 }
9
10 return count;
11 }
And this what I have on MIPS
main:
jal countNegatives
countNegatives:
li $t0, 0 #count = 0
li $t1, 0 #i = 0
loop:
bge $t1, $a1, endloop
sll $t2, $t1, 2 #$t2 = 4*i
add $t2, $a0, $t2 #$t2 = &table[i]
lw $t3, 0($t2) #temp = table[i]
bge $t3, $zero, endif
addi $t0, $t0, 1 #counter++
endif:
addi $t1, $t1, 1 #i++
endloop:
jr $ra
My code doesn't really run on QTSpim, and so I'm also trying to know if I'm missing any MIPS convention, and if I'm using the arguments in the procedure in a correct manner.
Thanks in advance if anyone can check the code out and see if something is wrong.
Except for some missing boilerplate, you were very close. Here's a version annotated with the bugs:
main:
# NOTE/BUG: a0/a1 are _not_ set up for the call
jal countNegatives
# NOTE/BUG: we just fall through into countNegatives again [which is bad]
countNegatives:
li $t0,0 # count = 0
li $t1,0 # i = 0
loop:
bge $t1,$a1,endloop
sll $t2,$t1,2 # $t2 = 4*i
add $t2,$a0,$t2 # $t2 = &table[i]
lw $t3,0($t2) # temp = table[i]
bge $t3,$zero,endif
addi $t0,$t0,1 # counter++
endif:
addi $t1,$t1,1 # i++
# NOTE/BUG: we need to loop here
endloop:
jr $ra
Here's a working version [with the added boilerplate]:
.data
arr: .word 10 20 -5 7 -6 0 1 -1 37
.text
.globl main
main:
la $a0,arr # point to array
li $a1,9 # array count
jal countNegatives
move $a0,$v0
li $v0,1
syscall
li $v0,10
syscall
# countNegatives -- count number of negatives
#
# RETURNS:
# v0 -- number of negative numbers found
#
# arguments:
# a0 -- pointer to array
# a1 -- array count
#
# temporaries:
# t1 -- index variable "i"
# t2 -- array offset / &table[i]
# t3 -- temp (value of table[i])
countNegatives:
li $v0,0 # count = 0
li $t1,0 # i = 0
loop:
bge $t1,$a1,endloop # i >= count? if yes, fly
sll $t2,$t1,2 # $t2 = 4*i
addu $t2,$a0,$t2 # $t2 = &table[i]
lw $t3,0($t2) # temp = table[i]
bge $t3,$zero,endif
addi $v0,$v0,1 # counter++
endif:
addi $t1,$t1,1 # i++
j loop
endloop:
jr $ra
Here's a just for fun version that uses slt instead of a conditional branch [and eliminates an extra jump inside the loop]:
.data
arr: .word 10 20 -5 7 -6 0 1 -1 37
.text
.globl main
main:
la $a0,arr # point to array
li $a1,9 # array count
jal countNegatives
move $a0,$v0
li $v0,1
syscall
li $v0,10
syscall
# countNegatives -- count number of negatives
#
# RETURNS:
# v0 -- number of negative numbers found
#
# arguments:
# a0 -- pointer to array
# a1 -- array count
#
# temporaries:
# t1 -- index variable "i"
# t2 -- array offset / &table[i]
# t3 -- temp (value of table[i])
countNegatives:
li $v0,0 # count = 0
li $t1,0 # i = 0
j loop_start # start the loop
loop:
sll $t2,$t1,2 # $t2 = 4*i
addu $t2,$a0,$t2 # $t2 = &table[i]
lw $t3,0($t2) # temp = table[i]
slt $t3,$t3,$zero # temp = (temp < 0)
add $v0,$v0,$t3 # counter += temp
addi $t1,$t1,1 # i++
loop_start:
blt $t1,$a1,loop # i < count? if yes, fly
jr $ra
Here's another version that uses pointer arithmetic instead of index variables.
Note that under the mips ABI, only the s* regs must be preserved by callee, so a0 and a1 are used as temporaries.
Also note that when adding addresses/pointers, as good practice, we want to use the unsigned versions of the add instructions (i.e. addu and addiu) to prevent [the unlikely possibility of] an overflow exception.
.data
arr: .word 10 20 -5 7 -6 0 1 -1 37
.text
.globl main
main:
la $a0,arr # point to array
li $a1,9 # array count
jal countNegatives
move $a0,$v0
li $v0,1
syscall
li $v0,10
syscall
# countNegatives -- count number of negatives
#
# RETURNS:
# v0 -- number of negative numbers found
#
# arguments:
# a0 -- pointer to array (ptr)
# a1 -- array count
#
# temporaries:
# a1 -- array limit (endp)
# t3 -- temp (value of table[i])
countNegatives:
li $v0,0 # count = 0
sll $a1,$a1,2 # get byte offset
addu $a1,$a0,$a1 # endp = &arr[count]
j loop_start # start the loop
loop:
lw $t3,0($a0) # temp = *ptr
slt $t3,$t3,$zero # temp = (temp < 0)
add $v0,$v0,$t3 # counter += temp
addiu $a0,$a0,4 # ptr += 4
loop_start:
bne $a0,$a1,loop # ptr != endp? if yes, fly
jr $ra
So, the final asm version, translated back into C would look something like this:
int
countNegatives(int *table, int n)
{
int *endp;
int count = 0;
endp = &table[n];
for (; table != endp; ++table)
count += (*table < 0);
return count;
}
It is not too difficult I think to see what decent compiler does:
https://godbolt.org/g/PiR8Ds
And you will have all the call conventions and another stuff toking by themselves.
#include <stdio.h>
int __attribute__((noinline)) countNegatives(int table[] , int n) {
int count = 0;
int i;
for (i=0; i<n; i++) {
if (table[i] <0) {
count++;
}
}
return count;
}
volatile int x[] = {454,-3,-5343,-3434,4534};
int main(void)
{
printf("%d\n",countNegatives((int *)x, sizeof(x)/sizeof(x[0])));
}
countNegatives:
blez $5,$L6
sll $5,$5,2
addu $5,$4,$5
move $2,$0
$L5:
lw $3,0($4)
addiu $4,$4,4
slt $3,$3,0
bne $4,$5,$L5
addu $2,$2,$3
j $31
nop
$L6:
j $31
move $2,$0
$LC0:
.ascii "%d\012\000"
main:
lui $4,%hi(x)
addiu $sp,$sp,-32
li $5,5 # 0x5
sw $31,28($sp)
jal countNegatives
addiu $4,$4,%lo(x)
lui $4,%hi($LC0)
move $5,$2
jal printf
addiu $4,$4,%lo($LC0)
lw $31,28($sp)
move $2,$0
j $31
addiu $sp,$sp,32
x:
.word 454
.word -3
.word -5343
.word -3434
.word 4534
I'm currently learning MIPS Assembly and I am attempting to convert the following C function into MIPS Assembly:
int count (int a[], int n, int x)
{
int res = 0;
int i = 0;
int j = 0;
int loc[];
for(i = 0; i != n; i++)
if(a[i] == x)
{
res = res + 1;
loc [j] = i;
j = j + 1;
}
return res, loc;
}
I've succeeded in converting most of it, and I believe I have successfully returned res (a value of 1), though I'm uncertain about returning loc (I also get a value of 1, and I don't think that's correct). However, I am having difficulty with this program and I am unsure as to how I can ensure that loc is returning the correct value or how to even code it to do so.
Here is my Assembly code:
.data
a: .word 5,6,7,8,9,10
n: .word
x: .word
res: .word 0
i: .word 0
jj: .word 0
loc: .space 40
.text
main:
la $s0, a
lw $s1, res
lw $s2, x
lw $t0, i
lw $t1, jj
lw $t2, n
la $s3, loc
li $t4, 6
start:
sll $t3, $t0, 2
add $t5, $t3, $s0
lw $t4, 0($t5)
beq $t0, $t4, start
addi $t0, $t0, 1
beq $t0, $t2, exit
addi $s1, $s1, 1
sll $t7, $t1, 2
add $t6, $s3, $t7
sw $t0, 0($t6)
addi $t1, $t1, 1
exit:
li $v0, 1
add $a0, $s1, $zero
syscall
li $v0, 1
add $a1, $s3, $zero
syscall
Any help, pointers, or suggestions would be very much appreciated.
EDIT: I've revised my code and now receive 0 for the res return and "268501028" for loc. Not sure where this number is coming from.
.data
a: .word 5,6,7,8,9,10
n: .word #n
x: .word #x
res: .word 0
i: .word 0
jj: .word 0
loc: .space 40
.text
main:
la $s0, a
lw $s1, res
lw $s2, x
lw $t0, i
lw $t1, jj
lw $t2, n
la $s3, loc
li $t4, 6
start:
beq $t0, $t2, exit #for(i = 0; i != n; i++)
bne $s0, $s2, else #if(a[i] == x)
j start
else:
addi $s1, $s1, 1 #res = res + 1;
sw $t0, ($t1) #loc [j] = i;
addi $t1, $t1, 1 #j = j+1
addi $t0, $t0, 1 #Increment i
addi $s3, $s3, 4 #Setting next element for loc
addi $s0, $s0, 4 #Setting next element for a
j start
exit:
li $v0, 1
move $a0, $s1
syscall
li $v0, 1
move $a0, $s3
syscall
Okay, there were a few bugs. I've annotated the source and added "BUG:" to hightlight them. I then created a cleaned up and corrected version
Here's your original code--no bug fixes, just annotations [please pardon the gratuitous style cleanup]:
# int
# count(int a[], int n, int x)
# {
# int res = 0;
# int i = 0;
# int j = 0;
# int loc[n];
#
# for (i = 0; i != n; i++) {
# if (a[i] == x) {
# res = res + 1;
# loc[j] = i;
# j = j + 1;
# }
# }
#
# return res, loc;
# }
.data
a: .word 5,6,7,8,9,10
n: .word
x: .word
res: .word 0
i: .word 0
jj: .word 0
loc: .space 40
nl: .asciiz "\n"
.text
.globl main
main:
la $s0,a
lw $s1,res
lw $s2,x
lw $t0,i
lw $t1,jj
lw $t2,n
la $s3,loc
li $t4,6 # BUG: extraneous (gets trashed below)
start:
sll $t3,$t0,2 # get i << 2
add $t5,$t3,$s0 # get &a[i]
lw $t4,0($t5) # fetch it
# BUG: we're comparing a[i] against i but we want to compare against x
# _and_ we want to flip the sense of the branch
beq $t0,$t4,start # is it a match? if yes, loop
addi $t0,$t0,1 # increment i
beq $t0,$t2,exit # i == n? if no, loop. if yes, exit
# BUG: the indexing here is wrong
addi $s1,$s1,1 # j += 1
sll $t7,$t1,2 # get jj << j
add $t6,$s3,$t7 # &loc[jj << j] (BUG: we want &loc[j])
sw $t0,0($t6) # set it to i
addi $t1,$t1,1 # jj += 1
# BUG: we should loop here and _not_ fall through
exit:
# print j (with newline)
li $v0,1
add $a0,$s1,$zero
syscall
li $v0,4
la $a0,nl
syscall
# print _address_ of loc[0]
# BUG: if we care to print anything, we should print the _values_ of the
# whole array
li $v0,1
# BUG: this should be a0 and _not_ a1
###add $a1,$s3,$zero
add $a0,$s3,$zero
syscall
li $v0,4
la $a0,nl
syscall
li $v0,10 # exit program
syscall
Here's the cleaned up and corrected version. I had to do a bit of restructuring and simplification to make it work, so it may seem a bit "alien" at first. However, I tried to retain your register usage where possible.
I also increased the size of the a array and added a user prompt for the x value:
# int
# count(int a[], int n, int x)
# {
# int i = 0;
# int j = 0;
# int loc[n];
#
# for (i = 0; i != n; i++) {
# if (a[i] == x) {
# loc[j] = i;
# j += 1;
# }
# }
#
# return j, loc;
# }
.data
a: .word 5,6,7,8,9,10
.word 5,6,7,8,9,10
.word 5,6,7,8,9,10
.word 5,6,7,8,9,10
.word 5,6,7,8,9,10
ae:
loc: .space 1000
prompt: .asciiz "Enter x value: "
msgnl: .asciiz "\n"
msgj: .asciiz "j: "
msgloc: .asciiz "loc: "
.text
# main -- main program
#
# RETURNS [sort of as this is a main program]:
# s1 -- j value (count of elements in "loc")
# loc -- filled in indexes into "a" array of matches to x
#
# registers:
# s0 -- a (base address of "a" array)
# t2 -- n (number of elements in "a" array)
#
# s2 -- x (value to match)
# t0 -- i (current index into "a" array)
# s3 -- loc (base address of "loc" array)
# s1 -- j (current index into "loc" array)
#
# t6 -- quick temporary [reusable]
# t7 -- used in array offset/index calculations [reusable]
.globl main
main:
# prompt for x value
li $v0,4 # syscall: print string
la $a0,prompt
syscall
# read in x value
li $v0,5 # syscall: read integer
syscall
move $s2,$v0
# get address of "a" array and compute length
la $s0,a # get &a[0]
la $t2,ae # get address of &a[n]
sub $t2,$t2,$s0 # get number of bytes in a
srl $t2,$t2,2 # get number of words in a (i.e. n)
li $t0,0 # i = 0
li $s1,0 # j = 0
la $s3,loc # base address of loc array
# main matching loop
loop:
sll $t7,$t0,2 # get i << 2
add $t7,$t7,$s0 # get &a[i]
lw $t6,0($t7) # fetch from it
bne $t6,$s2,next # a[i] == x? if no, advance to next element
# add new "i" value to loc array
sll $t7,$s1,2 # get j << 2
add $t7,$s3,$t7 # &loc[j << 2]
sw $t0,0($t7) # store i into loc
addi $s1,$s1,1 # j += 1
next:
addi $t0,$t0,1 # i += 1
blt $t0,$t2,loop # i < n? if yes, loop (or, we're done)
# done with calculation/fill loop
done:
la $s6,msgj # get prefix string
move $s7,$s1 # get j
jal prtnum # pretty print the number
blez $s1,exit # bug out if _no_ values in loc
# prepare to print all values of loc
la $t6,loc # base address of "loc"
li $t7,0 # initial index
# loop and print all values of loc
prtlocloop:
la $s6,msgloc # prefix string
lw $s7,($t6) # get loc[...]
jal prtnum # pretty print the number
add $t6,$t6,4 # increment address
add $t7,$t7,1 # increment index
blt $t7,$s1,prtlocloop # done? if no, loop
exit:
li $v0,10 # exit program
syscall
# prtnum -- print a number with a prefix string on a single line
#
# arguments:
# s6 -- prefix string
# s7 -- value to print
#
# registers:
# v0 -- syscall number [trashed]
# a0 -- syscall argument [trashed]
prtnum:
li $v0,4 # syscall: print string
move $a0,$s6 # string to print
syscall
li $v0,1 # syscall: print integer
move $a0,$s7 # value to print
syscall
li $v0,4 # syscall: print string
la $a0,msgnl
syscall
jr $ra # return
UPDATE:
What exactly is the difference between print and prtnum?
print is the label for the top of the loop that prints the values in loc. prtnum is subroutine/function that does the printing of a single number.
I added prtnum to demonstrate the use of a function and to avoid needless replication of some code.
Can they not be properly merged?
Sure, with some caveats. I did a slight/cosmetic edit to try to make things clearer. In particular, I renamed print: to prtlocloop: to try and make its role clearer.
The syscall(1) for "print integer" just prints the integer but does not add any whitespace or newline to separate them (i.e. it's exactly like printf("%d",a0)). So, we need something.
Originally, I just had the syscall(print_integer). With that, we get one "very long" number. Then, I added syscall(4) to print a newline. This was fine except the output was a bit confusing as to which value was j and which were the loc values.
(1) So, I added the "prefix" string. So, that became three syscalls for each number.
(2) This was used in two places: To print j and to print the loc values.
Same code in two or more places. That's the standard criterion for "split out code to function" in any language. It's a design/style choice [so there is no absolute answer].
So, with (1) and (2), I moved it to the prtnum function. Actually, I wrote the prtnum function first because I already knew the structure, and added the prefix argument after the output "looked ugly" [to me].
When I first coded it, I used "j: " for j and used a " " prefix for loc. It still looked a little funky. So, I changed the prefix to "loc: " to be consistent.
Could it be inlined? Sure. But, in addition to printing the number itself, we still have to add a separater. So, we need two syscalls per number to do it.
The separater could be a space if we want to put all numbers on the same output line. Fine for short vectors. This would require a slight change to the code as it exists now and we'd have to add a final output of newline to close the line. For longer arrays [that might not fit on a single line], one per line is [probably] tidier.
We only had to print j and loc. If the problem stated that we had to print a, then j, and then loc, I would have gone the other way.
I would have changed prtlocloop into another function (e.g. prtarray), that would loop on the given array and call prtnum for each element.
The first step was getting the calculation loop correct. The second was the printing. But, sometimes, they have to be done together. (i.e.) How can you debug something that you can't see?
So, with calculation correct, you are free to recode the output printing in any way you choose. The prtnum was just my way. But, it is by no means the only way.
Beyond the basic mechanics of working with the asm instructions, the choices are just like in any other language [notably C]. Comment well, choose the simplest and most effective way to architect/split the code, use descriptive variable names, etc. Comments should show "intent", the "what/why". The asm instructions are the "how".
Side note: Some OPs have had serious difficulty understanding how sll [which you already understand] works. They just didn't "get" the fact that a left shift by 2 was like a multiply by 4 and converts an index value into byte/address offset. So, you may already be ahead of the game ...
Yesterday, I gave an answer for a mips question where I went the other way and recommended inlining two functions. The problem was to calculate sin(x) using a Taylor series expansion [summation of terms] of the form: x**(2n)/factorial(2n-1).
With inlining, it was possible to reuse partial results from the previous term in the series without having to recalculate each term from scratch. This would not have been [conveniently] possible with multiple functions.
I didn't write the mips code, but I wrote the C/pseudo-code: mips program to calculate sin(x) The resulting mips code would [probably] have been simpler and would definitely run faster.
Given:
.data
arr: .word 2,5,1,3,4
len: .word 5
sum: .word 0
How would I access each word in "arr" such as 2, 3 and 4?
Eventually, what I would like to do is find a sum of all of the values in "arr", but I'm having difficulty iterating through "arr".
Thank you for your time!
Additional Info:
I'm using eduMIPS64
First load the address of the array into a register, then you can access the items with a constant offset. (Your assembler might support constructs such as lw $t0, arr+12 as convenience shorthand for this. See your manual.) For iteration, either increment the address register, or add another register containing the offset. Be sure to account for item sizes. Folling example is for 32 bit mips, adjust as necessary for 64 bit:
.data
arr: .word 2,5,1,3,4
len: .word 5
sum: .word 0
.text
.globl main
main:
la $t0, arr
lw $t1, 12($t0) # load arr[3] using byte offset
li $t1, 3 # index
sll $t1, $t1, 2 # multiply by item size
addu $t1, $t1, $t0 # add base address
lw $t1, ($t1) # load arr[3]
# iteration type 1
# for(i=len, ptr=arr; i != 0; i -= 1, ptr += 1)
# ... use *ptr ...
la $t0, arr
lw $t1, len # load length
loop1:
lw $t2, ($t0) # load item
# process item here
addi $t0, $t0, 4 # add item size to pointer
addi $t1, $t1, -1 # decrement counter
bne $t1, $0, loop1 # if counter != 0, repeat
# iteration type 2
# for(i=0, i != len; i += 1)
# ... use arr[i] ...
la $t0, arr
lw $t1, len # load length
li $t2, 0 # index
loop2:
sll $t3, $t2, 2 # multiply by item size
addu $t3, $t3, $t0 # add base address
lw $t3, ($t3) # load item
# process item here
addi $t2, $t2, 1 # increment index
bne $t2, $t1, loop2 # if index != len, repeat
(note these sample loops do not handle zero length array, add check if necessary)