Question
If the leaf function could use temporary registers ($t0, $t1, etc.), write the MIPS code for the code in the table above.
Write MIPS code for executable part of the code.
Assume that the stack and the static data segments are empty and that the stack and global pointers start at address 0x7fff fffc and 0x1000 8000, respectively. Assume the calling conventions as specified in Figure 2.11 and that function inputs are passed using registers $a0 and returned in register $v0. Assume that leaf functions may only use saved registers.
int X[8] = {100, 200, 300, 500, 0, -1, 20, -2};
int count1;
int count2;
int count_less_than(int*, int, int);
int main()
{
count1 = count_less_than(X, 8, 0);
count2 = count_less_than(X, 4, 320);
}
int count_less_than (int X[], int N, int threshold)
{
int count = 0, i;
for (i = 0; i < N; i++)
count += (X[i] < threshold);
return count;
}
Explanation / Answer
To understand what the program does to call function() we compile it with gcc using the -S switch to generate assembly code output: $ gcc -S -o example1.s example1.c By looking at the assembly language output we see that the call to function() is translated to: pushl $3 pushl $2 pushl $1 call function This pushes the 3 arguments to function backwards into the stack, and calls function(). The instruction 'call' will push the instruction pointer (IP) onto the stack. We'll call the saved IP the return address (RET). The first thing done in function is the procedure prolog: pushl %ebp movl %esp,%ebp subl $20,%esp This pushes EBP, the frame pointer, onto the stack. It then copies the current SP onto EBP, making it the new FP pointer. We'll call the saved FP pointer SFP. It then allocates space for the local variables by subtracting their size from SP. We must remember that memory can only be addressed in multiples of the word size. A word in our case is 4 bytes, or 32 bits. So our 5 byte buffer is really going to take 8 bytes (2 words) of memory, and our 10 byte buffer is going to take 12 bytes (3 words) of memory. That is why SP is being subtracted by 20. With that in mind our stack looks like this when function() is called (each space represents a byte): bottom of top of memory memory buffer2 buffer1 sfp ret a b c