Lecture 21

Add to the prologue

.import init
.import new
.import delete

Function init

Takes a parameter in $2.

New and Delete

Functions in alloc.merl

new: $1 = number of words needed.

code(new int [expr]) =  code(expr) ($3=expr)
                        add $1, $3, $0
                        call new
                        bne $3, $0, $1
                        add $3, $11, 0

delete: $1 = pointer to memory to be deallocated.

code(delete [] expr) =  code(expr)
                        beq $3, $11, skipY
                        add $1, $3, $0
                        call delete
                        skipY:

Procedures

Big Picture

int f() {}
int g() {}
...
int wain() {}
lis $5
.word $5
jr $5
f:
g:
wain:

Main prologue/Epilogue

Procedure-specific prologues

Saving and Restoring

Two approaches to saving and restoring -- caller-save and calle-save. Suppose \(f\) calls \(g\):

Our approach has been:

Who saves $29? caller or callee?

If callee-save

Or let the caller ($f) save $29 before calling \(g\)

f: ...
push($29)
push($31)
lis $5
.word g
jalr $5
pop($31)
pop($29)

Procedure names match the names of existing labels. It won't assemble.

Use a naming scheme for labels that prevents duplication.

Parameters

Could not use registers -- may not be enough

factor -> ID(expr1, ..., exprn)
code (factor) = push($29)
                push($30)
                code(expr1)
                push($3)
                ...
                code(exprn)
                push($3)
                lis $5
                .word ____
                jalr $5
                ; pop all args
                pop($31)
                pop($29)
code(procedure) =   sub $29, $30, $4
                    push(registers)
                    code(dcls)
                    code(statements)
                    code(expr)
                    pop(registers)
                    add $30, $30, $4
                    jr $31

What does the stack look like?

|__________|
|local regs|-$30
|__________|
|saved regs|-$29
|__________|____
|args for g|f's frame
|__________|
|   $31    |
|__________|
|   $29    |
|__________|____

Suppose \(g\) is

int g(int a, int b, int c) {
int d = 0; int e = 0; int f = 0;
//...
}

g's symbol table:

Name Type Offset
a int 0
b int -4
c int -8
d int -12
e int -16
f int -20

Parameters below $29, local variables above $29.

In between are saved registers, so symbol table offsets are wrong.

Fix symbol table:

|__________|
|saved regs|-$30
|__________|
|local regs|-$29
|__________|____
|args for g|f's frame
|__________|
|   $31    |
|__________|
|   $29    |
|__________|____
Name Type Offset
a int 12
b int 8
c int 4
d int 0
e int -4
f int -8