CS 208 w20 lecture 11 outline

1 Stack Operations

mem-layout.png

  • pushq and popq push/pop quad words onto/off of the program stack

    • pushq has a source operand, popq has a destination
    • the stack is a region of memory used to facilitate local variables and procedure calls
    • top of the stack is the lowest memory address, and is conventionally drawn at the bottom
    • each of these instructions combine a data move (source to memory for push, memory to destination for pop) and modifying the stack pointer
      • %rsp, the stack pointer, always contains the address of the top of the stack
      • either decremented by 8 (push, stack grows down) or incremented by 8 (pop)

    stack.png

1.1 Poll

Top of the stack at 0x200, 8 bytes stored there contain 0x20. What changes about registers or memory as a result of popq %r8?

2 Procedures

2.1 Are Jumps Enough?

  • yoo calls who
yoo:
    ...
    jmp who
back:
    ...
done:


who:
    ...
    jmp back
done:
  • but what if yoo calls who twice?

2.2 Overview

  • mechanisms needed to facilitate procedures (e.g., procedure P calls procedure Q, then Q executes and returns back to P):
    • passing control: instruction pointer (%rip) must be set to the start of Q and then set to the instruction following the call to Q in P
    • passing data: P has to provide arguments to Q and Q has to return a value to P
    • allocating and deallocating memeory: Q needs to acquire space for local variables and then free that space
  • requires seperate storage per call (not just per procedure)

2.3 The Run-Time Stack

frame-general.png

  • stack data structure a natural fit for managing run-time procedure memory
    • only the most recent procedure call needs to allocate space for local variables or make a new procedure call
    • when a procedure returns, we want to free the memory used by this most recent call
    • hence pushing and popping procedure data from a stack
  • when a procedure allocates space on the stack it is called that procedure's stack frame
  • x86-64 only allocates what a procedure actually needs
    • if a procedure's local variables can all be held in registers and it calls no other procedures, no stack frame is needed

2.4 Control Transfer

  • processor needs to know where it should resume execution after a procedure call returns
    • the call instruction pushes the return address of the following instruction onto the stack (part of the calling procedure's stack frame) and sets the instruction pointer to the start of the new procedure
      • call operand can either be direct (a label) or indirect (* followed by one of the standard operand formats)
    • the ret instruction pops the return address off the stack and copies it to the PC