Trying to write a basic main program using a function

216 views Asked by At

I am trying to write a function to copy words from source memory to destination memory.

I have written the function but I am having difficulty executing the code. It is giving me execption 4 as an error

.data    
.text      
main:

.setnoreorder      
top: beq $a2,0,done 
lw $t1,($a0) 
sw $t1,($a1) 
add $a0,$a0,4 
add $a1,$a1,4 
j top     
sub $a2,$a2,1


done:   
jr  $ra     #return to the main program 
add $0, $0, $0  #nop 

I want to write a main program which calls this function to copy 800 words from address 0x50000 to 0x90000 in memory. But when I add the values in $a0-$a2 and run the code it doesnt work. Does anyone know how to fix it. (I am converting C code to MIPS which is why I have included a C tag

Cheers

3

There are 3 answers

0
56phil On BEST ANSWER
    .text                       # code starts here 
main:                           # required label
    la      $a0,dest            # point to destination
    la      $a1,srce            # point to source
    li      $a2,1000            # move this many words 
    jal     block_copy          # call the routine 
    nop
    li      $v0,10
    syscall

###############################################################################
#   block copy - moves $a3 words from $a1 to $a0
#
#   register usage:
#       $a0 address of destination 
#       $a1 address of source
#       $a2 block size (number of words to move)
#       $v0 return code (0 means no troubles)
#
block_copy:

    move        $v0,$a2         # counter/rc 
bc_loop:
    lw          $t0,0($a1)      # no DMA here
    sw          $t0,0($a0)      # we have to move a word at a time 
    addiu       $a0,$a0,4       # point to next word in destination
    addiu       $a1,$a1,4       # point to next word in source
    addiu       $v0,$v0,-1      # decrement counter 
    bgtz        $v0,bc_loop     # keep on moving if counter is positive 
    jr          $ra             # return to caller
###############################################################################

    .data 
dest:
    .word       9:1000          # destination 1000 words (all zeroes)
srce:
    .word       0:1000          # source 1000 words (all nines)
2
MRAB On

Shouldn't that be:

sub $a2,$a2,1
j top
0
amdn On

You show a delay slot in two places, here

j top     
sub $a2,$a2,1

and here

done:   
jr  $ra     #return to the main program 
add $0, $0, $0  #nop

But apparently not here:

top: beq $a2,0,done 
lw $t1,($a0) 

Maybe the problem is that the load following the beq is, in fact, a delay slot and is being executed even when $a2 is zero (and the branch is taken) - you are loading from memory at ($a0) even when the count is zero - perhaps accessing invalid memory and causing the exception.