It may happen that there are multiple answers to a question. Here is just my answers to the questions.
decl $5 # register $5 = $5 - 1could be
addi $5, $5, -1Note that there is no such thing as subi in MIPS instruction set.
However, if you have not learnt the immediate form of add, one might consider
lw $1, AddressofOne($0) sub $5, $5, $1assuming that the
AddressofOne
contains the address at which 1 is
stored. Of course, this is not as elegant as using addi.
clrl $5 # register $5 = 0can be implemented in MIPS as
add $5, $0, $0Any other possibilities?
clrl 1000 # memory[1000] = 0can be
sw $0, 1000($0)with MIPS. You see that $0 = 0 permanently is handy in the above two examples.
aoblss $6, $5, L1 # $5 = $5 + 1; if ($5 < $6) goto L1can be synthesized in MIPS as
addi $5, $5, 1 # $5 = $5 + 1 slt $1, $5, $6 # $1 = 1 if $5 < $6 bne $1, $0, L1 # goto L1 if $1 == 1
loop: lw $3, 0($4) # Read next word from source addi $2, $2, 1 # Increment count words copied sw $3, 0($5) # Write to destination addi $4, $4, 1 # Advance pointer to next source addi $5, $5, 1 # Advance pointer to next dest bne $3, $0, loop # Loop if word copied is not zero
Here is the bugfree version:
addi $2, $0, -1 # * THE COUNT IS INITIALIZED TO -1 loop: lw $3, 0($4) # Read next word from source addi $2, $2, 1 # Increment count words copied sw $3, 0($5) # Write to destination addi $4, $4, 4 # * ADVANCE 4 BYTES SOURCE addi $5, $5, 4 # * ADVANCE 4 BYTES DESTINATION bne $3, $0, loop # Loop if word copied is not zero
Starting from -1 for $2 is a trick to copy but not count the last word (of value 0). One word occupies 4 bytes.
loop: lw $3, 0($4) addi $2, $2, 1 sw $3, 0($5) addi $4, $4, 1 addi $5, $5, 1 bne $3, $0, loopis (after consulting Figure 3.16 of the textbook, page 132, You are not expected to memorized the op code).
Name Format op rs rt immediate or address | symbolic form lw I 35 4 3 0 | lw $3,0($4) addi I 8 2 2 1 | addi $2,$2,1 sw I 43 5 3 0 | sw $3,0($5) addi I 8 4 4 1 | addi $4,$4,1 addi I 8 5 5 1 | addi $5,$5,1 bne I 5 3 0 -20 | bne $3,$0,loop
Note that they are all immediate format (I-type) instructions. The loop label is translated into -20 (by xspim), meaning, jump back by 20 bytes, counting from the current instruction bne,
count = -1; do { ++count; dest[count] = src[count]; } while (src[count] != 0);assuming $2 coresponds count, $4 to src[], and $5 to dest[]. Of course, there are other ways of writing the same program.
C Code MIPS Instruction if (i == j) goto L1; beq $19, $20, L1 if (i != j) goto L1; bne $19, $20, L1 if (i < j) goto L1; slt $1, $19, $20 bne $1, $0, L1 if (i <= j) goto L1; slt $1, $20, $19 beq $1, $0, L1 if (i > j) goto L1; slt $1, $20, $19 bne $1, $0, L1 if (i >= j) goto L1; slt $1, $19, $20 beq $1, $0, L1
Note that if it is not i<j, then i>=j. This fact is used in the last example.