Supporting Functions (procedures) What is needed? Functions: - - PowerPoint PPT Presentation

supporting functions procedures what is needed
SMART_READER_LITE
LIVE PREVIEW

Supporting Functions (procedures) What is needed? Functions: - - PowerPoint PPT Presentation

Supporting Functions (procedures) What is needed? Functions: Analogy of a spy secret plan, acquire resources, perform task, cover tracks, return with result Program has to place params for functions access transfer


slide-1
SLIDE 1

Supporting Functions (procedures)

slide-2
SLIDE 2

What is needed?

  • Functions: Analogy of a spy
  • secret plan, acquire resources, perform task, cover tracks, return with result
  • Program has to
  • place params for function’s access
  • transfer control to procedure
  • acquire storage resources for the function
  • perform function’s instructions
  • place result for calling program’s access
  • return control to point of origin
slide-3
SLIDE 3

Using registers

  • Registers are fast!
  • $a0 – $a3: argument registers
  • $v0-$v1: value registers
  • $ra: return address register
slide-4
SLIDE 4

Jump-Link and Program Counter

  • Jump-and-link instruction
  • jumps to addr, store next instruction’s addr in $ra: the return address
  • jal ProcedureAddress
  • Program Counter (PC)
  • address of current instruction
  • , jal stores PC + 4 in $ra to setup procedure return
  • , another instruction: jr $ra
  • jumps to address in $ra
slide-5
SLIDE 5

Setup for Executing Functions

  • Caller puts params in $a0 – $a3
  • Uses jal X to jump to callee procedure X
  • stores PC + 4 in $ra as well
  • Callee performs its instructions
  • Places results in $v0 – $v1
  • Returns to caller by $jr $ra
slide-6
SLIDE 6

32

To summarize:

slide-7
SLIDE 7

Procedure needs more registers. Overwrite?

  • More than $a0 – $a4 & $v0,$v1 may be needed
  • $t0 – $t9, $s0 – $s7
  • Those needed by caller must be restored to their original value
  • Use Stack for storing/restoring these registers

Stack

Last-In First-Out

Stack Pointer

$sp

slide-8
SLIDE 8

Push and Pop operations

Stack

(in memory)

HIGH LOW Push

SP SP

(subtract) (grow)

Push

SP

(add) (shrink)

MIPS provides $sp

slide-9
SLIDE 9

Compiling a C “leaf” procedure

int leaf_example (int g, int h, int i, int j) { int f; f = (g + h) - (i + j); return f; }

slide-10
SLIDE 10

The Stack Pointer

s0 t0 t1 $sp $sp $sp

Before During After

slide-11
SLIDE 11

Temporary registers

  • $t0 - $t9 are not preserved by callee
  • $s0 - $s7 are preserved by callee
  • So only 8 registers need to be saved
slide-12
SLIDE 12

Nested procedures

  • A procedure may call another
  • Also, recursive procedure
  • May over-write arg. or return-address registers
  • Solution: push them on the stack as well