Memory Access with $sp and $fp
Memory
Data memory “grows” from highest to lowest.
MIPS has a stack pointer $sp that points to the last memory allocated (used).
To store local memory (in the memory stack)
(1) Copy stack pointer to frame pointer
$fp is the frame pointer which we will use to reference all stack memory. That means all memory will be reference with reference to the frame pointer ($fp).
(2) Allocate memory for local variables
(3) Referce variables by substracting from frame pointer
First variable is -4($fp) and second is -8($fp) ... -4-4n($fp) n = 0, 1, 2 ...
Here is a short program from CSE1303’s Slide
C Code
The MIPS assembly
...
Data memory “grows” from highest to lowest.
MIPS has a stack pointer $sp that points to the last memory allocated (used).
To store local memory (in the memory stack)
(1) Copy stack pointer to frame pointer
move $fp, $sp$fp is the frame pointer which we will use to reference all stack memory. That means all memory will be reference with reference to the frame pointer ($fp).
(2) Allocate memory for local variables
subu $sp, $sp, 12 # Assuming 3 ints (4-byte each)(3) Referce variables by substracting from frame pointer
# a = -4($fp)
# b = -8($fp)
# c = -12($fp)First variable is -4($fp) and second is -8($fp) ... -4-4n($fp) n = 0, 1, 2 ...
Here is a short program from CSE1303’s Slide
C Code
#include <stdio.h>
#include <stdlib.h>
/* A global variable. */
int g = 123;
int main()
{
/* Three local variables. */
int a = -5;
int b;
int c = 0x12345678;
/* Do some arithmetic. */
b = g + a;
/* Do some more arithmetic. */
printf("%d", c - a);
exit(0);
}The MIPS assembly
# MIPSMemory.asm
# Test the memory access
# a = -12($fp)
# b = -8($fp)
# c = -4($fp)
.data
g: .word 123
.text
main:
# Copy $sp to $fp
move $fp, $sp
# Allocate 4 words (12 bytes)
subu $sp, $sp, 12
# int a = -5
li $t0, -5
sw $t0, -12($fp)
# int c = 0x12345678;
li $t0, 0x12345678
sw $t0, -4($fp)
# c - a
lw $t0, -12($fp) # $t0 = a
lw $t1, -4($fp) # $t1 = c
sub $t0, $t1, $t0
# display result
move $a0, $t0
li $v0, 1
syscall
exit:
li $v0, 10
syscall
...
