Procedures. 2 Procedure Definition A procedure is a mechanism for abstracting a group of related...

Preview:

Citation preview

Procedures

2

Procedure Definition• A procedure is a mechanism for abstracting a

group of related operations into a single operation that can be used repeatedly without repeating the code

• The group of operations is called the body of the procedure

• A procedure is defined by providing a specification or interface and a body

• The specification gives the procedure name, a list of types and names of parameters, and the type of its returned value

3

An Example

void intswap (int &x, int &y) // specification{ // body begins int t = x; x = y; y = t;} // body ends

void intswap (int &, int &); // specification only

4

Procedure Activation

• A procedure is called or activated by stating its name, together with arguments to the call, which correspond to its parameters

• A call to a procedure transfers control to the beginning of the body of the called procedure (the callee)

• When execution reaches the end of the body, control is returned to the caller

• Control can also be returned to the caller before reaching the end of the body by using return-statements

5

Environments

• A procedure communicates with the rest of the program through its parameters and also through nonlocal references

• The defining (or static) environment is the environment defining the meaning of nonlocal references

• The calling (or dynamic) environment is the environment defining the meaning of the caller

6

Environments

int a, b;

int q(int d){ int e; … }

int p(int c){ int a; … q(a); }

main(){ int b; p(a); }

a, b global

b main

a, c p

d, e q

calling environment

defining environment

7

Environments

• In static scoping, a procedure can communicate with its defining environment through nonlocal references or parameters

• In static scoping, a procedure can communicate with its calling environment through only parameters

• In dynamic scoping, the defining environment is the same as the calling environment

8

Parameter Passing

• Pass by value

• Pass by reference

• Pass by value-result

• Pass by name

9

Pass by Value

• Arguments are expressions that are evaluated at the time of the call, and their values become the values of the parameters during the execution of the procedure

• Parameters are viewed as constant values given by the values of the arguments, or

• Parameters are viewed as local variables with initial value given by the values of the arguments

10

An Examplevoid init_p(int *p){ *p = 0; }

void init_ptr(int *p){ p = (int *) malloc(sizeof(int)); }

void init_p_0(int p[ ]){ p[0] = 0; }

void append_1(Vector v){ v.addElement(new Integer(1)); }

void make_new(Vector v){ v = new Vector(): }

error!

error!

11

Pass by Reference

• An argument must in principle be a variable with an allocated address. Instead of the value, the location of the variable is passed to the parameter

• The parameter becomes an alias of the argument. Any changes made to the parameter occur to the argument as well

12

An Example

int a;

void inc(int &x){ x++; }… inc(a);

void inc(int *x){ (*x)++; }… inc(&a);

void yuck(int &x, int &y){ x = 2; y = 3; a = 4;}… yuck(a, a);

void inc(int &x){ x++; }… inc(2);

an error in C++!

ok in Fortran!

13

Pass by Value-Result

• The value of the argument is copied and used in the procedure, and then the final value of the parameter is copied back out to the location of the argument when the procedure exits

• This method is also known as copy-in, copy-out, or copy-restore

• A language may offer a pass by result method, in which there is no incoming value, but only an outgoing value

14

An Example

void p(int x, int y){ x++; y++; } main( ){ int a = 1; p(a, a); …}

a = 3 for pass by reference

a = 2 for pass by value-result

15

Pass by Name

• The semantics of procedures is described by a form of textual replacement

• An argument is not evaluated until its actual use in the called procedure. The name (or textual representation) of the argument replaces the name of the corresponding parameter at the point of call

• It turns out that pass by name is essentially equivalent to the normal order evaluation

16

An Example

int i;int a[10];

void p(int x){ i++; x++; } main( ){ i = 1; a[1] = 1; a[2] = 2; p(a[i]); return 0;}

/* i = 1, a[2] = 2 */i++; /* i = 2 */ a[i]++; /* a[2] = 3 */

17

Pass by Name

• The text of an argument at the point of call is viewed as a function in its own right, which is evaluated every time the corresponding parameter name is reached in the called procedure

• The argument will always be evaluated in the calling environment, while the called procedure will be executed in its defining environment

18

An Example

int i;

int p(int y){ int j = y; i++; return j + y; }

int q(void){ int j = 2; i = 1; printf(“%d\n”, p(i + j)); }

main(){ q( ); return 0;}

i + j 3 i + j 4

19

An Example

int i, j;

int i_plus_j(void){ return i + j; }

int p(int (*y) (void)){ int j = y(); i++; return j + y(); }

int q(void){ j = 2; i = 1; printf(“%d\n”, p(i_plus_j)); }

main(){ q( ); return 0;}

thunk

20

An Example

void intswap(int x, int y){ int t = x; x = y; y = t; }

intswap(i, a[i]);

t = i; i = a[i]; a[i] = t;

21

Fully Static Environments

• In Fortran 77, function and procedure definitions cannot be nested

• Recursion is not allowed

• The locations of all variables are fixed for the duration of program execution

22

Fully Static Environments

COMMON area

Activation record of main

Activation record of S1

Activation record of S2

space for local variables

space for passed parameters

return address

temporary space for

expression evaluation

23

An Example REAL TABLE(10), MAXVAL READ *, TABLE(1), TABLE(2) CALL LRGST(TABLE, 2, MAXVAL) PRINT *, MAXVAL END SUBROUTINE LRGST(A, SIZE, V) INTEGER SIZE REAL A(SIZE), V INTEGER K V = A(1) DO 10 K = 1, SIZE IF (A(K) .GT. V) V = A(K)10 CONTINUE RETURN END

TABLE (1)

TABLE (10)

MAXVAL

Temp: 2

K

A

SIZE

V

Return addr

24

Stack-Based Environment

• In a block-structured language with recursion, activations of procedures can be done in a stack manner, with a new activation record created on the stack every time a procedure is entered and released on exit

25

Stack-Based Environment

• Environment (or frame) pointer points to the current activation record

• Control (or dynamic) link points to the calling environment, i.e., the activation record of the caller

• Access (or static) link points to the defining environment, i.e., the activation record where nonlocal references are defined

26

Stack-Based Environment

control link

access link

local variables

passed parameters

return address

temporaries

27

An Example

int p(void){ … }

int q(void){ … p( ); }

main(){ q( ); … }

mainep

main

qep

main

q

pep

28

An Example

q

r

p

controllinkaccess

link

procedure q is x: integer;

procedure p(y: integer) is i: integer := x; begin … end p;

procedure r is x: float; begin p(1); … end r;

begin r; end q;

29

Access Chaining

procedure ex is x: …;

procedure p is

procedure q is begin … x …; end q;

begin … end p;

begin … end ex;

ex: x

p

q

nesting depth = 2

30

Closure

procedure lastex is

procedure p(n: integer) is

procedure show is begin if n > 0 then p(n - 1); end if; put(n); new_line; end show;

begin show; end p;

begin p(1); end lastex;

lastex

p

show

p

show

<ep, ip>

31

Procedure Parameters

• For a procedure parameter, the corresponding argument will be a closure <ep, ip>

• The ep is used to set the access link of the called procedure

• The ip points to the code of the called procedure

32

Dynamically Created Procedures• When procedures can be created dynamic

ally and be returned via returned values or reference parameters, they become first-class values

• Since the closure of a locally defined procedure will have an ep points to the current activation record. If that closure is available outside the activation of the procedure that created it, the ep will point to an activation record that no longer exits

33

An Exampletype WithdrawProc is access function(x: integer) return integer;InsufficientFunds: exception;function makeNewBalance(initBalance: integer) return WithDrawProc is currentBalance: integer; function withdraw(amt: integer) return integer is begin if amt <= currentBalance then currentbalance := currentBalance – amt; else raise InsufficientFunds; end if; return currentBalance; end withdraw;begin curentBalance := initBalance; return withdraw’access;end makeNewbalance;

34

An Example

withdraw1, withdraw2: WithdrawProc;

withdraw1 := makeNewBalance(500);withdraw2 := makeNewBalance(100);

/* similar to dangling reference */newBalance1 := withdraw1(100);newBalance2 := withdraw2(50);

35

Fully Dynamic Environments• In fully dynamic environment, like scheme,

an activation record can be removed only if they can no longer be reached from within the executing program

• Such an environment must perform some kind of automatic reclamation of unreachable storage called garbage collection

• Two standard methods of garbage collection are reference counting and mark and sweep

36

An Example

defining environment…

Withdraw1 Withdraw2

MakeNewBalance:currentBalance: 500Withdraw: …

MakeNewBalance:currentBalance: 100Withdraw: …

The structure of the activations becomestreelike instead of stacklike

37

Reference Counting• It (an eager method) reclaims a space as

soon as it is no longer referenced

• Each block of allocated storage contains an extra count field, which stores the number of references to the block from other blocks

• Each time a reference is changed, these reference counts must be updated

• When the reference count drops to zero, the block can be returned to the free list

38

Drawbacks of Reference Counting

• Need extra memory to keep the reference counts

• The effort to maintain the reference counts can be fairly large

• Circular references can cause unreferenced memory to never be deallocated

39

Maintaining Reference Countsvoid decrement(p){ p->refcount--; if (p->refcount == 0) { for all fields r of *p that are pointers do decrement(r); deallocate(*p); }}

void assign(p, q){ decrement(p); p = q; q->refcount++;}

40

Circular References

p

p is deallocated

41

Mark and Sweep• It (a lazy method) puts off reclaiming any sto

rage until the allocator runs out of space, at which point it looks for all storage that can be referenced and removes all unreferenced storage back to the free list

• The first pass follows all pointers recursively, starting with the symbol table, and marks each of block reached with an extra bit

• The second pass then sweeps linearly through memory, returning unmarked blocks to the free list

42

Drawbacks of Mark and Sweep

• Need extra space to keep the marks

• The double pass through memory causes a significant delay in processing, sometimes as much as a few seconds, each time the garbage collector is invoked, which can be every few minutes

• Two improvements: stop and copy, and generational garbage collection

43

Stop and Copy

• Splitting memory into two halves and allocating storage only from one half at a time

• During the marking pass, all reached blocks are copied to the other half

• No extra bit is required. Only one pass is required. Compaction is performed automatically

44

Generational Garbage Collection

• A permanent storage area is added to the reclamation scheme

• Allocated objects that survive long enough are simply copied into permanent space and are never deallocated during subsequent storage reclamations

• The garbage collector needs to search only a very small section of memory for newer storage allocations

Recommended