The Runtime Stack


The previous program calls a function using global variables instead of arguments. The runtime stack can be used for function calls using arguments.

The picture shows how a typical operating system arranges memory when a program starts. There are four gigabytes of (virtual) memory available in total. The section of memory from 0x10000000 to 0x7FFFFFFF is available for the data segment and the stack segment. This is 1.8 Gigabytes of space. When the program is started the stack pointer ($sp) is initialized to 0x7FFFEFFC (the address of the last fullword below the top of user memory). As the program runs, the stack grows downward into the available space. The data segment grows upward as the program runs. Of course, in a dynamic program, the segments grow and shrink.

To push an item onto the stack, first subtract 4 from the stack pointer, then store the item at the address in the stack pointer. Assume that the value to push on the stack is in register $t0:
  subu  $sp, $sp, 4 # Point to the place for the new item.
  sw    $t0, ($sp)  # Store the contents of $t0 as the new top.
To pop the top item from a stack, copy the item pointed at by the stack pointer, then add 4 to the stack pointer. Assume that we want the value to be popped into $t0:
  lw    $t0,($sp)   # Copy top the item to $t0.
  addu  $sp, $sp, 4 # Point to the item beneath the old top.



      “Don’t only practice your art,    
      but force your way into its secrets,    
      for it and knowledge can raise men to the divine.”    
      ― Ludwig van Beethoven