33
Dr. Muhammed Al-Mulhem ICS535-101 1 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 1

Chapter 7

Scope, Functions, and Storage Management

Page 2: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 2

Block-Structured Languages

Nested blocks, local variables• Example { int x = 2;

{ int y = 3; x = y+2;

} }

• Storage management– Enter block: allocate space for variables– Exits block: some or all space may be

deallocated

new variables declared in nested blocks

inner block

outer block

local variable

global variable

Page 3: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 3

Block-Structured Languages

Characteristics• New variables can be declared at various

points.• Each declaration is visible within a certain

region of the program (scope).• Memory is allocated to the variables in a block

at entry and deallocated at exit time.• Variables may live longer than the life of block

variables.• Variables that are not declared in the current

block are global variables.

Page 4: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 4

Block-Structured Languages

Blocks in common languages• C { … }• Algol begin … end• ML let … in … end

Two forms of blocks• In-line blocks • Blocks associated with functions or procedures

Page 5: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 5

Simplified Machine Model

Registers

Environment Pointer

Program Counter

DataCode

Heap

Stack

Page 6: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 6

Memory Management

The machine model separates code memory from data memory.

Code Segment • Program counter points to the current program instruction.• Registers used for short term storage of addresses and data.

Data Segment• Stack contains data related to block entry/exit• Heap contains data of varying lifetime• Environment pointer points to current stack position

– Block entry: add new activation record to stack– Block exit: remove most recent activation record from the stack

Page 7: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 7

Some basic concepts

Scope• Region of program text where declaration is visible

Lifetime• Period of time when location is allocated to program

• Inner declaration of x hides outer one.• Inner block is called “hole in scope”• Lifetime of outer x includes time when

inner block is executed• Lifetime scope• Lines indicate “contour model” of

scope.

{ int x = … ;

{ int y = … ;

{ int x = … ;

….

};

};

};

Page 8: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 8

In-line Blocks It is a block that is not the body of a function or procedure. Activation record is allocated when a block is entered.

• Data structure stored on run-time stack• Contains space for local variables

Example

May need space for variables and intermediate results like (x+y), (x-y)

{ int x=0;

int y=x+1;

{ int z=(x+y)*(x-y);

};

};

Push record with space for x, y Set values of x, y Push record for inner block Set value of z Pop record for inner blockPop record for outer block

Page 9: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 9

Activation Record for in-line Blocks

Control (dynamic) link • pointer to previous

record on stack

Push record on stack:• Set new control link to

point to old env ptr• Set env ptr to new

record

Pop record off stack• Follow control link of

current record to reset environment pointer

Control link

Local variables

Intermediate results

Control link

Local variables

Intermediate results

Environment Pointer

Page 10: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 10

Example

{ int x=0;

int y=x+1;

{ int z=(x+y)*(x-y);

};

};

Push record with space for x, y Set values of x, y Push record for inner block Set value of z Pop record for inner blockPop record for outer block

Control link

x

y

0

1

x+y

x-y

Environment Pointer

1

-1

Control link

z -1

Page 11: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 11

Scoping Rules

Global and local variables{ int x=0;

int y=x+1;

{ int z=(x+y)*(x-y);

};

};

• x, y are local to outer block • z is local to inner bock• x, y are global to inner block

Static scope• global refers to declaration in closest enclosing

block

Dynamic scope• global refers to most recent activation record

These are same until we consider function calls.

Page 12: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 12

Functions and Procedures

Syntax of procedures (Algol) and functions (C)procedure P (<pars>) <type> function f(<pars>) begin { <local vars> <local vars> <proc body> <function body> end; };

Activation record must include space for

• parameters• return address• return value (intermediate result)

• location to put return value on function exit

Page 13: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 13

Activation Record for Function

Return address• Location of code to

execute on function return

Return-result address• Address in activation

record of calling block to receive return address

Parameters• Locations to contain

data from calling block

Control link

Local variables

Intermediate results

Environment Pointer

Parameters

Return address

Return-result addr

Page 14: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 14

Example

Functionfact(n) = if n<= 1 then 1 else n * fact(n-

1)

Return result address• location to put fact(n)

Parameter• set to value of n by

calling sequence

Intermediate result• locations to contain

value of fact(n-1)

Control link

Local variables

Intermediate results

Environment Pointer

Parameters

Return address

Return result addr

Page 15: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 15

Control link

fact(n-1)

n

Return-result addr

3

fact(3)

Function call

Suppose some block contains the expression fac(3) + 1

Control link

fact(n-1)

n

Return-result addr

2

fact(2)

fact(n) = if n<= 1 then 1 else n * fact(n-1)

Control link

fact(n-1)

n

Return-result addr

k

fact(k)

Environment Pointer

Control link

fact(n-1)

n

Return-result addr

1

fact(1)

Function return next slide

Page 16: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 16

Function return

Control link

fact(n-1)

n

Return result addr

3

fact(3)

Control link

fact(n-1)

n

Return result addr

1

2

fact(2)

Control link

fact(n-1)

n

Return result addr

1

fact(1)

fact(n) = if n<= 1 then 1 else n * fact(n-1)

Control link

fact(n-1)

n

Return result addr

2

3

fact(3)

Control link

fact(n-1)

n

Return result addr

1

2

fact(2)

Page 17: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 17

Parameter Passing

Formal parameters- names in a function declaration

Actual parameters- names in a function call Example:

Proc p (int x, int y) {…}

p (z, 4*z+1);

• x, y are formal• z and 4*z+1 are actual

Page 18: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 18

Topics for functions

Parameter passing• pass-by-value, pass-by-reference

Access to global variables• global variables are contained in an activation

record higher “up” the stack

Tail recursion• an optimization for certain recursive functions

Page 19: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 19

Parameter passing

General terminology: L-values and R-values• Assignment y := x+3

– Identifier on left refers to location, called its L-value– Identifier on right refers to contents, called R-value

Most languages evaluate the actual parameters before executing the function body.

Two mechanisms to pass parameters:• Call by reference: pass the L-value (address) of

the actual parameter.• Call by value: pass the R-value (contents of

address) of the actual parameter.

Page 20: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 20

Parameter passing

Pass-by-reference• Caller places L-value (address) of actual parameter

in activation record of the called function.• Function can assign to variable that is passed

Pass-by-value• Caller places R-value (contents) of actual

parameter in activation record of the called function.

• Function cannot change value of caller’s variable• Reduces aliasing (alias: two names refer to same

loc)

Page 21: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 21

Parameter passing

The difference between pass-by-value and pass-by-reference is important in several ways:• Side Effects: Function can change the value of a

parameter using call-by-reference• Aliasing: Aliasing can occurs when two parameters

are passed by reference.• Efficiency: Pass-by-value may be inefficient for large

structure if the value must be copied. Call-by-reference may be less efficient than call-by-value for small structure that would fit directly on the stack, because when parameters are passed by reference we must derefence a pointer to get their value.

Page 22: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 22

Access to global variables

Two possible scoping conventions• Static scope: refer to closest enclosing block• Dynamic scope: most recent activation record on stack

Example

int x=1;function g(z) = x+z;function f(y) = { int x = y+1; return g(y*x) };f(3);

x 1

x 4

y 3

z 12

outer block

f(3)

g(12)

Page 23: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 23

Access to global variablesint x=1;function g(z) = x+z;function f(y) = { int x = y+1; return g(y*x) };f(3);

x 1

x 4

y 3

z 12

outer block

f(3)

g(12)

•Two integers named x on the stack.

•Which x is used for expression x+z ?

•Under dynamic scope, x will be the one from the most recently created activation, namely x=4.

•Under static scope, x will refer to the one from the closest program block, namely x=1

Page 24: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 24

Access link to maintain static scope

Control link• Link to activation record of

previous (calling) block Access link

• Link to activation record of closest enclosing block in program text

Difference• Control link depends on

dynamic behavior of program

• Access link depends on static form of program text

Control link

Local variables

Intermediate results

Environment Pointer

Parameters

Return address

Return result addr

Access link

Page 25: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 25

Tail recursion (first-order

case)

A useful compiler optimization is the tail recursion elimination. What is tail recursion?

Function g makes a tail call to function f if• Return value of function f is return value of g

Example

fun g(x) = if x>0 then f(x) else f(x)*2

Optimization• For tail recursive functions, it is possible to reuse an

activation record for a recursive call to the function. – next activation record has exactly same form

tail call not a tail call

Page 26: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 26

Example

Consider the tail recursive function to compute factorial

fun tlfact(n, a) = if n <= 1 then a else tlfact(n-1, n*a);

Use the following calltlfact(3, 1);

The activation records without optimization is as shown.

control

return val

n 3

a 1

control

return val

n 2

a 3

control

return val

n 1

a 6

f(1,3)

Page 27: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 27

Example

Advantage of tail recursion:• We can use the same activation record for all

recursive calls. After third call terminates, it passes its return result

back to the second call, which passes to the first. We can simplify this process by letting the third call

return its result to activation that make the original call.

Note that, when the third call finishes, we can pop the activation record for the second call. Similarly for the activation record for the first call.

Therefore, we can use one activation record for all three calls.

Page 28: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 28

Tail recursion elimination

fun tlfact(n, a) = if n <= 1

then a else tlfact(n-1,

n*a);

control

return val

n 3

a 1

tlfact(1,6)

Optimization• pop followed by push =

reuse activation record in place

Conclusion• Tail recursive function equiv

to iterative loop

control

return val

n 2

a 3

tlfact(3,1)

control

return val

n 1

a 6

tlfact(2,3)

Page 29: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 29

Tail recursion and iteration

fun f(x,y) = if x>y then x else f(2*x, y);

control

return val

x 1

y 3

f(4,3), g(4,3)

control

return val

x 2

y 3

f(1,3), g(1,3)

control

return val

x 4

y 3

f(2,3), g(2,3)

fun g(x,y) = {while not(x>y) do

x := 2*x; return x; };

Tail recursion elimination compiles tail recursive function into iterative loops.

Consider the two functions, tail recursive and iterative.

Page 30: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 30

Higher-Order Functions

First-Class functions A language has first-class function if

• Functions declared within any scope• Functions passed as arguments to other

functions• Functions returned as a result of functions

Page 31: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 31

Example: Function with function parameters

A scheme example(define (map f L)

(if (null? L) ‘()(cons (f (car L)) (map f (cdr L)))))

(define (square x) (* x x))

(define (square-list L) (map square L))

Page 32: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 32

Example: Function returns function value

A scheme example(define (make-double f )

(define (doublefn x) (f x x))doublefn)

This function assumes that f is a function with two parameters and creates the function that repeats the parameter x in a call to f.

We can use make-double as follows (define square (make-double *)) (define double (make-double +))

Page 33: Dr. Muhammed Al-Mulhem ICS535-1011 Chapter 7 Scope, Functions, and Storage Management

Dr. Muhammed Al-Mulhem ICS535-101 33

Closures

Function value is pair closure = env, code • env is a pointer to the activaltion record• code is a pointer to function code.