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

Slides:



Advertisements
Similar presentations
The University of Adelaide, School of Computer Science
Advertisements

Programming Languages and Paradigms
CSI 3120, Implementing subprograms, page 1 Implementing subprograms The environment in block-structured languages The structure of the activation stack.
CPS3340 COMPUTER ARCHITECTURE Fall Semester, /17/2013 Lecture 12: Procedures Instructor: Ashraf Yaseen DEPARTMENT OF MATH & COMPUTER SCIENCE CENTRAL.
Implementing Subprograms
(1) ICS 313: Programming Language Theory Chapter 10: Implementing Subprograms.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
1 Storage Registers vs. memory Access to registers is much faster than access to memory Goal: store as much data as possible in registers Limitations/considerations:
Cse321, Programming Languages and Compilers 1 6/12/2015 Lecture #17, March 12, 2007 Procedure Abstraction, Name Spaces, Scoping Rules, Activation Records,
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
ISBN Chapter 10 Implementing Subprograms.
Runtime Environments Source language issues Storage organization
Honors Compilers Addressing of Local Variables Mar 19 th, 2002.
Run-Time Storage Organization
Run time vs. Compile time
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
Scope, Function Calls and Storage Management John Mitchell CS
Chapter 9: Subprogram Control
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Scope, Function Calls and Storage Management John Mitchell CS
Slide 1 Vitaly Shmatikov CS 345 Scope and Activation Records.
1 Chapter 5: Names, Bindings and Scopes Lionel Williams Jr. and Victoria Yan CSci 210, Advanced Software Paradigms September 26, 2010.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
Runtime Environments What is in the memory? Runtime Environment2 Outline Memory organization during program execution Static runtime environments.
CS3012: Formal Languages and Compilers The Runtime Environment After the analysis phases are complete, the compiler must generate executable code. The.
CS 2104 Prog. Lang. Concepts Subprograms
Runtime Environments Compiler Construction Chapter 7.
Compiler Construction
Chapter 10 Implementing Subprograms. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 10 Topics The General Semantics of Calls and Returns.
Chapter 7 Runtime Environments. Relationships between names and data objects As execution proceeds, the same name can denote different data objects Procedures,
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
Slide 1 Vitaly Shmatikov CS 345 Imperative Programming.
Basic Semantics Associating meaning with language entities.
Midterm Review John Mitchell CS 242. Midterm uThurs Nov 7, 7-9PM Terman Aud Closed book uClass schedule Thurs Oct 31, Tues Nov 5 – topics not on midterm.
ISBN Chapter 10 Implementing Subprograms.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
BİL 744 Derleyici Gerçekleştirimi (Compiler Design)1 Run-Time Environments How do we allocate the space for the generated target code and the data object.
Run-Time Storage Organization Compiler Design Lecture (03/23/98) Computer Science Rensselaer Polytechnic.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Slide 1 Dr. Mohammad El-Ramly Fall 2010 Set 7- II - Functions Slides by Vitaly Shmatikov Cairo University Faculty of Computers and Information CS317 Concepts.
CSC 8505 Compiler Construction Runtime Environments.
Slide 1 WEEK 8 Imperative Programming Original by Vitaly Shmatikov.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
7. Runtime Environments Zhang Zhizheng
RUNTIME ENVIRONMENT AND VARIABLE BINDINGS How to manage local variables.
ISBN Chapter 10 Implementing Subprograms.
ISBN Chapter 10 Implementing Subprograms.
Scope, Function Calls and Storage Management John Mitchell CS Reading: Chapter 7, Concepts in Programming Languages.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
Run-Time Environments Presented By: Seema Gupta 09MCA102.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Chapter 14 Functions.
Run-Time Environments Chapter 7
Implementing Subprograms Chapter 10
Functions.
Implementing Subprograms
Memory Locations For Variables
Run-Time Storage Organization
Run-Time Storage Organization
Chapter 10: Implementing Subprograms Sangho Ha
Implementing Subprograms
The University of Adelaide, School of Computer Science
Implementing Subprograms
UNIT V Run Time Environments.
Runtime Environments What is in the memory?.
Scope, Function Calls and Storage Management
Where is all the knowledge we lost with information? T. S. Eliot
Chapter 10 Def: The subprogram call and return operations of
Presentation transcript:

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

Dr. Muhammed Al-Mulhem ICS Block-Structured Languages uNested 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

Dr. Muhammed Al-Mulhem ICS Block-Structured Languages uCharacteristics 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.

Dr. Muhammed Al-Mulhem ICS Block-Structured Languages uBlocks in common languages C { … } Algol begin … end ML let … in … end uTwo forms of blocks In-line blocks Blocks associated with functions or procedures

Dr. Muhammed Al-Mulhem ICS Simplified Machine Model Registers Environment Pointer Program Counter DataCode Heap Stack

Dr. Muhammed Al-Mulhem ICS Memory Management uThe machine model separates code memory from data memory. uCode Segment Program counter points to the current program instruction. Registers used for short term storage of addresses and data. uData 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

Dr. Muhammed Al-Mulhem ICS Some basic concepts uScope Region of program text where declaration is visible uLifetime 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 = … ; …. };

Dr. Muhammed Al-Mulhem ICS In-line Blocks uIt is a block that is not the body of a function or procedure. uActivation record is allocated when a block is entered. Data structure stored on run-time stack Contains space for local variables uExample 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 block Pop record for outer block

Dr. Muhammed Al-Mulhem ICS Activation Record for in-line Blocks uControl (dynamic) link pointer to previous record on stack uPush record on stack: Set new control link to point to old env ptr Set env ptr to new record uPop 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

Dr. Muhammed Al-Mulhem ICS 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 block Pop record for outer block Control link x y 0 1 x+y x-y Environment Pointer 1 Control link z

Dr. Muhammed Al-Mulhem ICS Scoping Rules uGlobal 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 uStatic scope global refers to declaration in closest enclosing block uDynamic scope global refers to most recent activation record These are same until we consider function calls.

Dr. Muhammed Al-Mulhem ICS Functions and Procedures uSyntax of procedures (Algol) and functions (C) procedure P ( ) function f( ) begin { end; }; uActivation record must include space for parameters return address return value (intermediate result) location to put return value on function exit

Dr. Muhammed Al-Mulhem ICS Activation Record for Function uReturn address Location of code to execute on function return uReturn-result address Address in activation record of calling block to receive return address uParameters Locations to contain data from calling block Control link Local variables Intermediate results Environment Pointer Parameters Return address Return-result addr

Dr. Muhammed Al-Mulhem ICS Example uFunction fact(n) = if n<= 1 then 1 else n * fact(n-1) uReturn result address location to put fact(n) uParameter set to value of n by calling sequence uIntermediate result locations to contain value of fact(n-1) Control link Local variables Intermediate results Environment Pointer Parameters Return address Return result addr

Dr. Muhammed Al-Mulhem ICS 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 

Dr. Muhammed Al-Mulhem ICS 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)

Dr. Muhammed Al-Mulhem ICS Parameter Passing uFormal parameters- names in a function declaration uActual parameters- names in a function call uExample: Proc p (int x, int y) { … } p (z, 4*z+1); x, y are formal z and 4*z+1 are actual

Dr. Muhammed Al-Mulhem ICS Topics for functions uParameter passing pass-by-value, pass-by-reference uAccess to global variables global variables are contained in an activation record higher “up” the stack uTail recursion an optimization for certain recursive functions

Dr. Muhammed Al-Mulhem ICS Parameter passing uGeneral 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 uMost languages evaluate the actual parameters before executing the function body. uTwo 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.

Dr. Muhammed Al-Mulhem ICS Parameter passing uPass-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 uPass-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)

Dr. Muhammed Al-Mulhem ICS Parameter passing uThe 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.

Dr. Muhammed Al-Mulhem ICS Access to global variables uTwo possible scoping conventions Static scope: refer to closest enclosing block Dynamic scope: most recent activation record on stack uExample int x=1; function g(z) = x+z; function f(y) = { int x = y+1; return g(y*x) }; f(3); x1 x4 y3 z12 outer block f(3) g(12)

Dr. Muhammed Al-Mulhem ICS Access to global variables int x=1; function g(z) = x+z; function f(y) = { int x = y+1; return g(y*x) }; f(3); x1 x4 y3 z12 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

Dr. Muhammed Al-Mulhem ICS Access link to maintain static scope uControl link Link to activation record of previous (calling) block uAccess link Link to activation record of closest enclosing block in program text uDifference 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

Dr. Muhammed Al-Mulhem ICS Tail recursion (first-order case) uA useful compiler optimization is the tail recursion elimination. What is tail recursion? uFunction g makes a tail call to function f if Return value of function f is return value of g uExample fun g(x) = if x>0 then f(x) else f(x)*2 uOptimization 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

Dr. Muhammed Al-Mulhem ICS Example uConsider the tail recursive function to compute factorial fun tlfact(n, a) = if n <= 1 then a else tlfact(n-1, n*a); uUse the following call tlfact(3, 1); uThe activation records without optimization is as shown. control return val n3 a1 control return val n2 a3 control return val n1 a6 f(1,3)

Dr. Muhammed Al-Mulhem ICS Example uAdvantage of tail recursion: We can use the same activation record for all recursive calls. uAfter third call terminates, it passes its return result back to the second call, which passes to the first. uWe can simplify this process by letting the third call return its result to activation that make the original call. uNote 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. uTherefore, we can use one activation record for all three calls.

Dr. Muhammed Al-Mulhem ICS Tail recursion elimination fun tlfact(n, a) = if n <= 1 then a else tlfact(n-1, n*a); control return val n3 a1 tlfact(1,6) Optimization pop followed by push = reuse activation record in place Conclusion Tail recursive function equiv to iterative loop control return val n2 a3 tlfact(3,1) control return val n1 a6 tlfact(2,3)

Dr. Muhammed Al-Mulhem ICS Tail recursion and iteration fun f(x,y) = if x>y then x else f(2*x, y); control return val x1 y3 f(4,3), g(4,3) control return val x2 y3 f(1,3), g(1,3) control return val x4 y3 f(2,3), g(2,3) fun g(x,y) = { while not(x>y) do x := 2*x; return x; }; uTail recursion elimination compiles tail recursive function into iterative loops. uConsider the two functions, tail recursive and iterative.

Dr. Muhammed Al-Mulhem ICS Higher-Order Functions uFirst-Class functions uA 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

Dr. Muhammed Al-Mulhem ICS Example: Function with function parameters uA 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))

Dr. Muhammed Al-Mulhem ICS Example: Function returns function value uA scheme example (define (make-double f ) (define (doublefn x) (f x x)) doublefn) uThis function assumes that f is a function with two parameters and creates the function that repeats the parameter x in a call to f. uWe can use make-double as follows u(define square (make-double *)) u(define double (make-double +))

Dr. Muhammed Al-Mulhem ICS Closures uFunction value is pair closure =  env, code  env is a pointer to the activaltion record code is a pointer to function code.