CS计算机代考程序代写 prolog assembly Lifetime of Local Variables and Arguments

Lifetime of Local Variables and Arguments
Allocation: allocate space for them when procedure is called Deallocation: free them when procedures ends (return)
A function’s activation frame includes
 Local variables
 Return address
 Arguments
Why isn’t the Heap the best choice for activation frame?
 Requires more complicated and costly process to avoid fragmentation
 The stack on the other hand just needs to add or subtract from a pointer, since each activation frame only exists when a function is being run
Structure of Activation Frames/Accessing Variables/Arguments
Static data
Stack
Heap
Stack
Activation Frame Details for SIM 213
Stack Pointer: r5 – stores base address of current frame
Never return a pointer to the address of a local variable
Memory leaks occur when local variables that store a reference to a block of memory are not properly handled. In this case the l should have been returned
Some Implications
Return address: r6 – instruction where procedure jumps to when it completes
Returnvalue: r0-singlevaluereturnedbyprocedure
Stack Management and Division of Labor
Before call
caller prologue: info caller needs to send to callee, this is typically the arguments needed for the function to run. The caller will allocate space on the stack and store the argument values on the stack
Function call
callee prologue: info to execute procedure and return. Allocate space for the return address and the local variables (if applicable) and storing the return address on the stack
Run procedure
callee epilogue: deallocate of the memory it allocated (i.e., mem for return address and local variables). This is done by incrementing the stack pointe. The callee epilogue also prepares to return by loading the return address from the stack into r6
Return
caller epilogue: deallocates the memory that it allocated (i.e., the memory for the arguments) by increasing the stack pointer
ld 12(r5), r0 str0,(r5) #l0=a0 ld 16(r5), r0 str0,4(r5) #l1=a1
Always initialize local variables

Exercises
Write out the assembly code for the caller & callee prologues and caller & callee epilogues for
loo(10,15)
ld $8, r1
add r1, r5
deca r5,
st r6, (r5)
ld $-12, r1
add r1, r5
The Runtime Stack
What does the runtime stack look like for the code given?
x
c
y
ra
a 10 b 15
Caller
Prologue
Callee
deca r5
ld $15, r1
st r1, (r5)
deca r5
ld $10, r1
st r1, (r5)
Caller
Epilogue
Callee
ld 12(r5), r6
ld $16, r1
add r1, r5
How big is the activation frame for boo()?
16 bytes on a 32-bit system
Write out the assembly code for goo?
ra i
j k
deca r5
st r6, (r5)
deca r5
ld 16(r5), r1
st r1, (r5)
deca r5
ld 12(r5), r1
st r1, (r5)
gpc $6, r6
j loo j (r6)
ld (r5), r6
inca r5
For more practice write out all the other functions epilogues, prologues and function body