Compiling a String Copy Procedure, Showing How to Use C Strings
The procedure strcpy copies string y to string x using the null byte termination convention of C:
void strcpy (char x[ ], char y[ ]) { int i; } |
What is the MIPS assembly code?
Below is the basic MIPS assembly code segment. Assume that base addresses for arrays x and y are found in $a0 and $a1, while i is in $s0. strcpy adjusts the stack pointer and then saves the saved register $s0 on the stack:
strcpy:
addi $sp, $sp,–4 # adjust stack for 1 more item |
strcpy:
addi $sp,$sp,–4 # adjust stack for 1 more item
sw $s0, 0($sp) # save $s0
To initialize i to 0, the next instruction sets $s0 to 0 by adding 0 to 0 and placing that sum in $s0:
add $s0, $zero, $zero # i = 0 + 0 |
Th is is the beginning of the loop. Th e address of y[i] is fi rst formed by adding i to y[ ]:
L1: add $t1, $s0, $a1 # address of y[i] in $t1 |
Note that we don’t have to multiply i by 4 since y is an array of bytes and not of words, as in prior examples.
To load the character in y[i], we use load byte unsigned, which puts the character into $t2:
lbu $t2, 0($t1) # $t2 = y[i] |
A similar address calculation puts the address of x[i] in $t3, and then the character in $t2 is stored at that address.
add $t3, $s0, $a0 # address of x[i] in $t3 sb $t2, 0($t3) # x[i] = y[i] |
Next, we exit the loop if the character was 0. Th at is, we exit if it is the last character of the string:
beq $t2, $zero, L2 # if y[i] == 0, go to L2 |
If not, we increment i and loop back:
addi $s0, $s0, 1 # i = i + 1 j L1 # go to L1 |
If we don’t loop back, it was the last character of the string; we restore $s0 and the stack pointer, and then return.
L2: lw $s0, 0($sp) # y[i] == 0: end of string.
# Restore old $s0 |
String copies usually use pointers instead of arrays in C to avoid the operations on i in the code above. See Section 2.14 for an explanation of arrays versus pointers.