Procedures Procedure Definition A procedure is a mechanism

  • Slides: 44
Download presentation
Procedures

Procedures

Procedure Definition • A procedure is a mechanism for abstracting a group of related

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 2

An Example void intswap (int &x, int &y) { int t = x; x

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

Procedure Activation • A procedure is called or activated by stating its name, together

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 4 statements

Environments • A procedure communicates with the rest of the program through its parameters

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 5

Environments int a, b; int q(int d) { int e; … } int p(int

Environments int a, b; int q(int d) { int e; … } int p(int c) { int a; … q(a); } defining environment a, b global b main a, c p d, e q main() { int b; p(a); } calling environment 6

Environments • In static scoping, a procedure can communicate with its defining environment through

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 7

Parameter Passing • Pass by value • Pass by reference • Pass by value-result

Parameter Passing • Pass by value • Pass by reference • Pass by value-result • Pass by name 8

Pass by Value • Arguments are expressions that are evaluated at the time of

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 9

An Example void init_p(int *p) { *p = 0; } void init_ptr(int *p) {

An Example void init_p(int *p) { *p = 0; } void init_ptr(int *p) { p = (int *) malloc(sizeof(int)); } error! void init_p_0(int p[ ]) { p[0] = 0; } void append_1(Vector v) { v. add. Element(new Integer(1)); } void make_new(Vector v) { v = new Vector(): } error! 10

Pass by Reference • An argument must in principle be a variable with an

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 11

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

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! 12

Pass by Value-Result • The value of the argument is copied and used in

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 13

An Example void p(int x, int y) { x++; y++; } main( ) {

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 14

Pass by Name • The semantics of procedures is described by a form of

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 15

An Example int i; int a[10]; void p(int x) { i++; x++; } i++;

An Example int i; int a[10]; void p(int x) { i++; x++; } i++; a[i]++; main( ) { i = 1; a[1] = 1; a[2] = 2; p(a[i]); return 0; } /* i = 1, a[2] = 2 */ /* i = 2 */ /* a[2] = 3 */ 16

Pass by Name • The text of an argument at the point of call

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 17

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

An Example int i; int p(int y) { int j = y; i++; return j + y; } i+j 3 i+j 4 int q(void) { int j = 2; i = 1; printf(“%dn”, p(i + j)); } main() { q( ); return 0; } 18

An Example int i, j; int i_plus_j(void) { return i + j; } thunk

An Example int i, j; int i_plus_j(void) { return i + j; } thunk int p(int (*y) (void)) { int j = y(); i++; return j + y(); } int q(void) { j = 2; i = 1; printf(“%dn”, p(i_plus_j)); } main() { q( ); return 0; } 19

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

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; 20

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

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 21

Fully Static Environments COMMON area space for local variables Activation record of main space

Fully Static Environments COMMON area space for local variables Activation record of main space for passed parameters Activation record of S 1 return address Activation record of S 2 temporary space for … expression evaluation 22

An Example REAL TABLE(10), MAXVAL READ *, TABLE(1), TABLE(2) CALL LRGST(TABLE, 2, MAXVAL) PRINT

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 23

Stack-Based Environment • In a block-structured language with recursion, activations of procedures can be

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 24

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

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 25

Stack-Based Environment control link access link local variables passed parameters return address temporaries 26

Stack-Based Environment control link access link local variables passed parameters return address temporaries 26

An Example int p(void) { …} int q(void) { … p( ); } ep

An Example int p(void) { …} int q(void) { … p( ); } ep main q q ep p main() { q( ); … } 27

An Example procedure q is x: integer; procedure p(y: integer) is i: integer :

An Example procedure q is x: integer; procedure p(y: integer) is i: integer : = x; begin … end p; q access link r control link p procedure r is x: float; begin p(1); … end r; begin r; end q; 28

Access Chaining procedure ex is x: …; procedure p is procedure q is begin

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 29

Closure procedure lastex is procedure p(n: integer) is procedure show is begin if n

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; <ep, ip> lastex p show begin show; end p; begin p(1); end lastex; 30

Procedure Parameters • For a procedure parameter, the corresponding argument will be a closure

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 31

Dynamically Created Procedures • When procedures can be created dynamically and be returned via

Dynamically Created Procedures • When procedures can be created dynamically 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 32

An Example type Withdraw. Proc is access function(x: integer) return integer; Insufficient. Funds: exception;

An Example type Withdraw. Proc is access function(x: integer) return integer; Insufficient. Funds: exception; function make. New. Balance(init. Balance: integer) return With. Draw. Proc is current. Balance: integer; function withdraw(amt: integer) return integer is begin if amt <= current. Balance then currentbalance : = current. Balance – amt; else raise Insufficient. Funds; end if; return current. Balance; end withdraw; begin curent. Balance : = init. Balance; return withdraw’access; end make. Newbalance; 33

An Example withdraw 1, withdraw 2: Withdraw. Proc; withdraw 1 : = make. New.

An Example withdraw 1, withdraw 2: Withdraw. Proc; withdraw 1 : = make. New. Balance(500); withdraw 2 : = make. New. Balance(100); /* similar to dangling reference */ new. Balance 1 : = withdraw 1(100); new. Balance 2 : = withdraw 2(50); 34

Fully Dynamic Environments • In fully dynamic environment, like scheme, an activation record can

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 35

An Example defining environment … Withdraw 1 Withdraw 2 Make. New. Balance: current. Balance:

An Example defining environment … Withdraw 1 Withdraw 2 Make. New. Balance: current. Balance: 500 Withdraw: … Make. New. Balance: current. Balance: 100 Withdraw: … The structure of the activations becomes treelike instead of stacklike 36

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

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 37

Drawbacks of Reference Counting • Need extra memory to keep the reference counts •

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 38

Maintaining Reference Counts void decrement(p) { p->refcount--; if (p->refcount == 0) { for all

Maintaining Reference Counts void 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++; } 39

Circular References p p is deallocated 40

Circular References p p is deallocated 40

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

Mark and Sweep • It (a lazy method) puts off reclaiming any storage 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 41

Drawbacks of Mark and Sweep • Need extra space to keep the marks •

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 42

Stop and Copy • Splitting memory into two halves and allocating storage only from

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 43

Generational Garbage Collection • A permanent storage area is added to the reclamation scheme

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 44