The document discusses run-time environments in compiler design. It provides details about storage organization and allocation strategies at run-time. Storage is allocated either statically at compile-time, dynamically from the heap, or from the stack. The stack is used to store procedure activations by pushing activation records when procedures are called and popping them on return. Activation records contain information for each procedure call like local variables, parameters, and return values.
Run-Time Environments: Storage organization, Stack Allocation of Space, Access to Nonlocal Data on the Stack, Heap Management, Introduction to Garbage Collection, Introduction to Trace-Based Collection. Code Generation: Issues in the Design of a Code Generator, The Target Language, Addresses in the Target Code, Basic Blocks and Flow Graphs, Optimization of Basic Blocks, A Simple Code Generator, Peephole Optimization, Register Allocation and Assignment, Dynamic Programming Code-Generation
The purpose of types:
To define what the program should do.
e.g. read an array of integers and return a double
To guarantee that the program is meaningful.
that it does not add a string to an integer
that variables are declared before they are used
To document the programmer's intentions.
better than comments, which are not checked by the compiler
To optimize the use of hardware.
reserve the minimal amount of memory, but not more
use the most appropriate machine instructions.
This produced by straight forward compiling algorithms made to run faster or less space or both. This improvement is achieved by program transformations that are traditionally called optimizations.compiler that apply-code improving transformation are called optimizing compilers.
Run-Time Environments: Storage organization, Stack Allocation of Space, Access to Nonlocal Data on the Stack, Heap Management, Introduction to Garbage Collection, Introduction to Trace-Based Collection. Code Generation: Issues in the Design of a Code Generator, The Target Language, Addresses in the Target Code, Basic Blocks and Flow Graphs, Optimization of Basic Blocks, A Simple Code Generator, Peephole Optimization, Register Allocation and Assignment, Dynamic Programming Code-Generation
The purpose of types:
To define what the program should do.
e.g. read an array of integers and return a double
To guarantee that the program is meaningful.
that it does not add a string to an integer
that variables are declared before they are used
To document the programmer's intentions.
better than comments, which are not checked by the compiler
To optimize the use of hardware.
reserve the minimal amount of memory, but not more
use the most appropriate machine instructions.
This produced by straight forward compiling algorithms made to run faster or less space or both. This improvement is achieved by program transformations that are traditionally called optimizations.compiler that apply-code improving transformation are called optimizing compilers.
Artificial Intelligence: Introduction, Typical Applications. State Space Search: Depth Bounded
DFS, Depth First Iterative Deepening. Heuristic Search: Heuristic Functions, Best First Search,
Hill Climbing, Variable Neighborhood Descent, Beam Search, Tabu Search. Optimal Search: A
*
algorithm, Iterative Deepening A*
, Recursive Best First Search, Pruning the CLOSED and OPEN
Lists
Distributed Mutual Exclusion and Distributed Deadlock DetectionSHIKHA GAUTAM
Distributed Mutual Exclusion: Classification of distributed mutual exclusion, requirement of mutual exclusion theorem, Token based and non token based algorithms. Distributed Deadlock Detection: system model, resource Vs communication deadlocks, deadlock prevention, avoidance, detection & resolution, centralized dead lock detection
Artificial Intelligence: Introduction, Typical Applications. State Space Search: Depth Bounded
DFS, Depth First Iterative Deepening. Heuristic Search: Heuristic Functions, Best First Search,
Hill Climbing, Variable Neighborhood Descent, Beam Search, Tabu Search. Optimal Search: A
*
algorithm, Iterative Deepening A*
, Recursive Best First Search, Pruning the CLOSED and OPEN
Lists
Distributed Mutual Exclusion and Distributed Deadlock DetectionSHIKHA GAUTAM
Distributed Mutual Exclusion: Classification of distributed mutual exclusion, requirement of mutual exclusion theorem, Token based and non token based algorithms. Distributed Deadlock Detection: system model, resource Vs communication deadlocks, deadlock prevention, avoidance, detection & resolution, centralized dead lock detection
Apache Apex: Stream Processing Architecture and Applications Comsysto Reply GmbH
• Architecture highlights: high throughput, low-latency, operability with stateful fault tolerance, strong processing guarantees, auto-scaling etc
• Application development model, unified approach for real-time and batch use cases
• Tools for ease of use, ease of operability and ease of management
• How customers use Apache Apex in production
Apache Apex: Stream Processing Architecture and ApplicationsThomas Weise
Slides from http://www.meetup.com/Hadoop-User-Group-Munich/events/230313355/
This is an overview of architecture with use cases for Apache Apex, a big data analytics platform. It comes with a powerful stream processing engine, rich set of functional building blocks and an easy to use API for the developer to build real-time and batch applications. Apex runs natively on YARN and HDFS and is used in production in various industries. You will learn more about two use cases: A leading Ad Tech company serves billions of advertising impressions and collects terabytes of data from several data centers across the world every day. Apex was used to implement rapid actionable insights, for real-time reporting and allocation, utilizing Kafka and files as source, dimensional computation and low latency visualization. A customer in the IoT space uses Apex for Time Series service, including efficient storage of time series data, data indexing for quick retrieval and queries at high scale and precision. The platform leverages the high availability, horizontal scalability and operability of Apex.
Apache Big Data EU 2016: Next Gen Big Data Analytics with Apache ApexApache Apex
Stream data processing is becoming increasingly important to support business needs for faster time to insight and action with growing volume of information from more sources. Apache Apex (http://apex.apache.org/) is a unified big data in motion processing platform for the Apache Hadoop ecosystem. Apex supports demanding use cases with:
* Architecture for high throughput, low latency and exactly-once processing semantics.
* Comprehensive library of building blocks including connectors for Kafka, Files, Cassandra, HBase and many more
* Java based with unobtrusive API to build real-time and batch applications and implement custom business logic.
* Advanced engine features for auto-scaling, dynamic changes, compute locality.
Apex was developed since 2012 and is used in production in various industries like online advertising, Internet of Things (IoT) and financial services.
Apache Big Data 2016: Next Gen Big Data Analytics with Apache ApexApache Apex
Apache Apex is a next gen big data analytics platform. Originally developed at DataTorrent it comes with a powerful stream processing engine, rich set of functional building blocks and an easy to use API for the developer to build real-time and batch applications. Apex runs natively on YARN and HDFS and is used in production in various industries. You will learn about the Apex architecture, including its unique features for scalability, fault tolerance and processing guarantees, programming model and use cases.
http://apachebigdata2016.sched.org/event/6M0L/next-gen-big-data-analytics-with-apache-apex-thomas-weise-datatorrent
Actionable Insights with Apache Apex at Apache Big Data 2017 by Devendra TagareApache Apex
The presentation covers how Apache Apex is used to deliver actionable insights in real-time for Ad-tech. It includes a reference architecture to provide dimensional aggregates on TB scale for billions of events per day. The reference architecture covers concepts around Apache Apex, with Kafka as source and dimensional compute. Slides from Devendra Tagare at Apache Big Data North America in Miami 2017.
The topic focuses on different aspects of processor organization and architecture such as architecture models, register organization, instruction formats, addressing modes etc.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Digital Tools and AI for Teaching Learning and Research
Run time storage
1. Automata and Compiler Design
R. Madana Mohana., M.E, MISTE (Ph.D)
1
Associate Professor
Department of Computer Science and Engineering
September 2014
www.rmmnaidu.com
3. Run-Time Environments
The compiler must implement various abstractions in the source
language definition such as
Names used in a program
Define the scope of variables
Data types
3
Data types
Operators
Procedures
Parameters and
Flow of control constructs.
The compiler must co-operate with operating system and other
systems software to support the implementation of these
abstractions on the target machine. This can be done by the
compiler by creating run-time environment.
4. Run-Time Environments
What is run-time environment in compiler design?
A run-time environment in compiler design deals variety of issues
such as:
1. Managing the processor stack.
2. Layout and allocation of memory for various variables used in
the source program.
4
the source program.
3. Instructions to copy the actual parameters on top of the stack
when a function is called.
4. Allocating and de-allocating the memory dynamically with the
help of operating system.
5. The mechanism used by the target program to access variables.
6. The mechanism to pass parameters.
7. The interfaces to the operating system, input/output devices and
other programs.
5. A lot has to happen at run time to get your program running.
At run time, we need a system to map NAMES (in the source
program) to STORAGE on the machine.
Allocation and deallocation of memory is handled by a RUN-
TIME SUPPORT SYSTEM typically linked and loaded along
Run-Time Environments
5
TIME SUPPORT SYSTEM typically linked and loaded along
with the compiled target code.
One of the primary responsibilities of the run-time system is to
manage ACTIVATIONS of procedures.
6. For allocating memory to data items, the following information
is required:
1. Size of data item
2. The type of data item
Dimensions of the data item
Run-Time Environments
6
3. Dimensions of the data item
4. Scope of the data item
7. The organization of data objects in memory depends on the
source language features:
1. Recursion
2. Parameter passing mechanism
Local names
Run-Time Environments
7
3. Local names
4. Non-local names
5. Dynamic data structures
9. Suppose that the compiler obtains memory from the OS so that
it can execute the compiled program
Program gets loaded on a newly created process
This runtime storage must hold
Generated target code
Storage Organization
9
Generated target code
Data objects
A counterpart of the control stack to keep track of procedure
activations
10. code for function 1
code for function 2
code for function n
. . .
Runtime Memory
PASCAL and C use extensions of the
control stack to manage activations of
procedures
Stack contains information about register
values, value of program counter and
data objects whose lifetimes are
10
global / static area
stack
heap
free space
data objects whose lifetimes are
contained in that of an activation
Heap holds all other information. For
example, activations that cannot be
represented as a tree.
By convention, stack grows down and the
top of the stack is drawn towards the
bottom of this slide (value of top is usually
kept in a register)
11. code for function 1
code for function 2
code for function n
. . .
code for function 1
code for function 2
code for function n
. . .
Runtime Memory
11
global / static area
stack
heap
free space
global / static area
stack
heap
free space
Stack grows
12. Activation Record
Information needed by a single
execution of a procedure is managed
using an activation record or frame
Not all compilers use all of the
fields
Pascal and C push activation record
returned value
actual parameters
optional control link
12
Pascal and C push activation record
on the runtime stack when procedure
is called and pop the activation
record off the stack when control
returns to the caller
optional control link
optional access link
saved machine status
local data
temporaries
Fig: A typical Activation Record
13. 1) Temporary values
Ex. those arising in the evaluation of
expressions
2) Local data
Data that is local to an execution of the
procedure
returned value
actual parameters
optional control link
optional access link
13
Activation Record
procedure
3) Saved machine status
State of the machine info before
procedure is called. Values of program
counter and machine registers that have
to be restored when control returns from
the procedure
optional access link
saved machine status
local data
temporaries
14. 4) Access Link
refer to non-local data held in other
activation records
5) Control link
points to the activation record of the caller
6) Actual parameters
returned value
actual parameters
optional control link
optional access link
14
Activation Record
6) Actual parameters
used by the calling procedure to supply
parameters to the called procedure
(in practice these are passed in registers)
7) Returned value
used by the called procedure to return a
value to the calling procedure
(in practice it is returned in a register)
optional access link
saved machine status
local data
temporaries
15. Local data
The field for local data is set when declarations in a procedure
are examined during compile time
Variable-length data is not stored here
Keep a count of the memory locations that have been
allocated so far
15
allocated so far
Determine a relative address (offset) of the storage for a
local with respect to some position (e.g. beginning of the
frame)
• Multibyte objects are stored in consecutive bytes and
given the address of the first byte
18. Run-time stack and heap
The STACK is used to store:
Procedure activations.
The status of the machine just before calling a procedure, so
that the status can be restored when the called procedure
returns.
18
returns.
The HEAP stores data allocated under program control
19. Storage Allocation Strategies
The various storage allocation strategies to allocate storage in
different data areas of memory are:
1. Static Allocation
• Storage is allocated for all data objects at compile time
Stack Allocation
19
2. Stack Allocation
• The storage is managed as a stack
3. Heap Allocation (It is one of Dynamic Storage Allocation)
• The storage is allocated and deallocated at runtime from a
data area known as heap
20. Static Allocation
In a static environment (Fortran 77) there are a number of
restrictions:
Size of data objects are known at compile time
No recursive procedures
No dynamic memory allocation
20
No dynamic memory allocation
Only one copy of each procedure activation record exists at
time t
We can allocate storage at compile time
• Bindings do not change at runtime
• Every time a procedure is called, the same bindings occur
21. Static Allocation
Statically allocated names are bound to relocatable storage
at compile time.
Storage bindings of statically allocated names never change.
The compiler uses the type of a name (retrieved from the
symbol table) to determine storage size required.
21
symbol table) to determine storage size required.
The required number of bytes (possibly aligned) is set aside
for the name.
The relocatable address of the storage is fixed at compile
time.
22. Static Allocation
int i = 10;
int f(int j)
{
int k;
int m;
…
code for function 1
code for function 2
code for function n
. . .
code main()
code f()
i (int)
22
…
}
main()
{
int k;
f(k);
}
global / static area
stack
heap
free space
i (int)
k (int)
k (int)
m (int)
main()
Activation
record
f()
Activation
record
23. Limitations:
The size required must be known at compile time.
Recursive procedures cannot be implemented statically.
No data structure can be created dynamically as all data is
static.
23
Static allocation
static.
24. Stack-based Allocation
In a stack-based allocation, the previous restrictions are lifted
(Pascal, C, etc)
procedures are allowed to be called recursively
o Need to hold multiple activation records for the same
procedure
24
o Created as required and placed on the stack
Each record will maintain a pointer to the record that
activated it
On completion, the current record will be deleted
from the stack and control is passed to the calling
record
Dynamic memory allocation is allowed
Pointers to data locations are allowed
25. Stack-dynamic allocation
Storage is organized as a stack.
Activation records are pushed and popped.
Locals and parameters are contained in the activation records
for the call.
This means locals are bound to fresh storage on every call.
25
This means locals are bound to fresh storage on every call.
We just need a stack_top pointer.
To allocate a new activation record, we just increase stack_top.
To deallocate an existing activation record, we just decrease
stack_top.
26. Stack-based Allocation
PROGRAM sort(input,output);
VAR a : array[0..10] of Integer;
PROCEDURE readarray;
VAR i : Integer;
BEGIN
for i:= 1 to 9 do read(a[i]);
END;
FUNCTION partition(y,z : Integer):
Integer;
VAR i,j,x,v : Integer;
Position in
Activation Tree
Activation Records
On Stack
s
s
a (array)
26
VAR i,j,x,v : Integer;
BEGIN
…
END;
PROCEDURE quicksort(m,n : Integer);
VAR i : Integer;
BEGIN
if (n > m) then BEGIN
i := partition(m,n);
quicksort(m, i-1);
quicksort(i+1,n)
END
END;
BEGIN /* of main */
a[0] := -9999; a[10] := 9999;
readarray;
quicksort(1,9)
END.
27. PROGRAM sort(input,output);
VAR a : array[0..10] of Integer;
PROCEDURE readarray;
VAR i : Integer;
BEGIN
for i:= 1 to 9 do read(a[i]);
END;
FUNCTION partition(y,z : Integer):
Integer;
VAR i,j,x,v : Integer;
Position in
Activation Tree
Activation Records
On Stack
s
a (array)
s
27
Stack-based Allocation
VAR i,j,x,v : Integer;
BEGIN
…
END;
PROCEDURE quicksort(m,n : Integer);
VAR i : Integer;
BEGIN
if (n > m) then BEGIN
i := partition(m,n);
quicksort(m, i-1);
quicksort(i+1,n)
END
END;
BEGIN /* of main */
a[0] := -9999; a[10] := 9999;
readarray;
quicksort(1,9)
END.
r r
i (integer)
28. PROGRAM sort(input,output);
VAR a : array[0..10] of Integer;
PROCEDURE readarray;
VAR i : Integer;
BEGIN
for i:= 1 to 9 do read(a[i]);
END;
FUNCTION partition(y,z : Integer):
Integer;
VAR i,j,x,v : Integer;
Position in
Activation Tree
Activation Records
On Stack
s
a (array)
s
28
Stack-based Allocation
VAR i,j,x,v : Integer;
BEGIN
…
END;
PROCEDURE quicksort(m,n : Integer);
VAR i : Integer;
BEGIN
if (n > m) then BEGIN
i := partition(m,n);
quicksort(m, i-1);
quicksort(i+1,n)
END
END;
BEGIN /* of main */
a[0] := -9999; a[10] := 9999;
readarray;
quicksort(1,9)
END.
r q(1,9)
i (integer)
q(1,9)
29. PROGRAM sort(input,output);
VAR a : array[0..10] of Integer;
PROCEDURE readarray;
VAR i : Integer;
BEGIN
for i:= 1 to 9 do read(a[i]);
END;
FUNCTION partition(y,z : Integer):
Integer;
VAR i,j,x,v : Integer;
Position in
Activation Tree
Activation Records
On Stack
s
a (array)
s
q(1,9)
29
Stack-based Allocation
VAR i,j,x,v : Integer;
BEGIN
…
END;
PROCEDURE quicksort(m,n : Integer);
VAR i : Integer;
BEGIN
if (n > m) then BEGIN
i := partition(m,n);
quicksort(m, i-1);
quicksort(i+1,n)
END
END;
BEGIN /* of main */
a[0] := -9999; a[10] := 9999;
readarray;
quicksort(1,9)
END.
r q(1,9)
i (integer)
q(1,9)
q(1,3)p(1,9)
q(1,3)
i (integer)
30. Position inPosition inPosition inPosition in
Activation TreeActivation TreeActivation TreeActivation Tree
Activation RecordsActivation RecordsActivation RecordsActivation Records
on the Stackon the Stackon the Stackon the Stack
30
31. Address generation in stack allocation
The position of the activation record on the stack cannot be
determined statically.
Therefore the compiler must generate addresses RELATIVE to
the activation record.
We generate addresses of the form
31
We generate addresses of the form
stack_top + offset
32. Calling Sequences
Procedure calls are implemented by
generating calling sequences in the target
code
Call sequence: allocates activation
record and enters information into fields
returned value
actual parameters
optional control link
32
record and enters information into fields
Return sequence: restores the state of
the machine so that the calling
procedure can continue execution
optional access link
saved machine status
local data
temporaries
33. Calling Sequences
Why placing returned value and
actual parameters next to the
activation record of the caller?
Caller can access these values
using offsets from its own
caller
returned value
actual parameters
optional control link
optional access link
saved machine status
local data
33
using offsets from its own
activation record
No need to know the middle part
of the callee’s activation record
callee
local data
temporaries
returned value
actual parameters
optional control link
optional access link
saved machine status
local data
temporaries
34. How do we calculate offset?
Maintain a register that
points to the end of the
machine status field in an
activation record
Top_sp is known to the caller,
caller
returned value
actual parameters
optional control link
optional access link
saved machine status
local data
34
Calling Sequences
Top_sp is known to the caller,
so it can be responsible for
setting it before control flows
to the called procedure
Callee can access its
temporaries and local data
using offsets from top_sp
callee
local data
temporaries
returned value
actual parameters
optional control link
optional access link
saved machine status
local data
temporaries
top_sp
35. Call Sequence
The caller evaluates actuals
The caller
stores a return address and the old value of top_sp into the
callee’s activation record
increments top_sp; that is moved past the caller’s local
35
increments top_sp; that is moved past the caller’s local
data and temporaries and the callee’s parameter and
status fields
The callee
saves register values and other status information
The callee
initializes its local data and begins execution
36. Return Sequence
The callee places a return value next to the activation record
of the caller
Using the information in the status field, the callee
restores top_sp and other registers
braches to a return address in the caller’s code
36
braches to a return address in the caller’s code
Although top_sp has been decremented, the caller can copy
the returned value into its own activation record and use it to
evaluate an expression
37.
38. Example of variable- length data
All variable-length data is
pointed to from the local data
area.
38
39. Dangling References
Whenever storage is deallocated, the problem of dangling
references arises
Occurs when there is a reference to storage that has been
deallocated
Logical error
39
Logical error
Mysterious bugs can appear
40. int *dangle()
{
int i = 23;
return &i;
What’s the problem?
40
Dangling References
return &i;
}
main()
{
int *p;
p = dangle();
}
41. int *dangle()
{
int i = 23;
return &i;
Local variable i only exists in
dangle()
When procedure completes
execution and control is transferred
41
Dangling References
}
main()
{
int *p;
p = dangle();
}
execution and control is transferred
to main(), the space for i does not
exist anymore (pop activation
record for dangle off the stack)
Pointer p is a dangling reference
42. Stack Allocation Advantages and Disadvantages
Advantages:
It supports recursion as memory is always allocated on block
entry.
It allows to create data structures dynamically.
It allows an array declaration like A(I, J), since actual
42
It allows an array declaration like A(I, J), since actual
allocation is made only at execution time. The dimension
bounds need not be known at compile time.
Disadvantages:
Memory addressing has to be effected through pointers and
index registers which may be store them, static allocation
especially in case of array reference.
43. Heap Allocation
Stack allocation cannot be used if:
The values of the local variables must be retained when an
activation ends
A called activation outlives the caller
In such a case de-allocation of activation record cannot occur
43
In such a case de-allocation of activation record cannot occur
in last-in first-out fashion
Heap allocation gives out pieces of contiguous storage for
activation records
44. Heap Allocation
There are two aspects of dynamic allocation :
Runtime allocation and de-allocation of data structures
Languages like Algol have dynamic data structures and it
reserves some part of memory for it.
44
If a procedure wants to put a value that is to be used after its
activation is over then we cannot use stack for that purpose. That is
language like Pascal allows data to be allocated under program
control. Also in certain language a called activation may outlive the
caller procedure. In such a case last-in-first-out queue will not work and
we will require a data structure like heap to store the activation. The
last case is not true for those languages whose activation trees correctly
depict the flow of control between procedures.
45. Heap Allocation
Some languages do not have tree-structured allocations.
In these cases, activations have to be allocated on the heap.
This allows strange situations, like callee activations that live
longer than their callers’ activations.
This is not common.
45
This is not common.
46. Heap Allocation
Pieces may be de-allocated in any order
Over time the heap will consist of alternate areas that are
free and in use
Heap manager is supposed to make use of the free space
For efficiency reasons it may be helpful to handle small
46
For efficiency reasons it may be helpful to handle small
activations as a special case
For each size of interest keep a linked list of free blocks of
that size
47. Heap Allocation
Fill a request of size s with block of size s ' where s ' is the
smallest size greater than or equal to s
For large blocks of storage use heap manager
For large amount of storage computation may take some time
to use up memory so that time taken by the manager may be
47
to use up memory so that time taken by the manager may be
negligible compared to the computation time
48. Heap Allocation
For efficiency reasons we can handle small activations and
activations of predictable size as a special case as follows:
1. For each size of interest, keep a linked list if free blocks of that
size
2. If possible, fill a request for size s with a block of size s', where
48
2. If possible, fill a request for size s with a block of size s', where
s' is the smallest size greater than or equal to s. When the block
is eventually de-allocated, it is returned to the linked list it came
from.
3. For large blocks of storage use the heap manger.
Heap manger will dynamically allocate memory. This will come with a
runtime overhead. As heap manager will have to take care of
defragmentation and garbage collection. But since heap manger saves
space otherwise we will have to fix size of activation at compile time,
runtime overhead is the price worth it.
49. Access to non-local names
Scope rules determine the treatment of non-local names
A common rule is lexical scoping or static scoping (most
languages use lexical scoping)
The scope rules of a language decide how to reference the
non-local variables. There are two methods that are commonly
49
non-local variables. There are two methods that are commonly
used:
1. Static or Lexical scoping: It determines the declaration that
applies to a name by examining the program text alone. E.g.,
Pascal, C and ADA.
2. Dynamic Scoping: It determines the declaration applicable to
a name at run time, by considering the current activations.
E.g., Lisp
50. Block
Blocks can be nested
The property is referred to as block structured
Scope of the declaration is given by most closely nested rule
• The scope of a declaration in block B includes B
50
• If a name X is not declared in B then an occurrence of X is in
the scope of declarator X in B ' such that
o B ' has a declaration of X
o B ' is most closely nested around B
53. Blocks
Blocks are simpler to handle than procedures
Blocks can be treated as parameter less procedures
Use stack for memory allocation
Allocate space for complete procedure body at one time
53
54. Blocks
There are two methods of implementing block structure:
1. Stack Allocation : This is based on the observation that scope of
a declaration does not extend outside the block in which it
appears, the space for declared name can be allocated when
the block is entered and de-allocated when controls leave the
54
the block is entered and de-allocated when controls leave the
block. The view treat block as a "parameter less procedure"
called only from the point just before the block and returning
only to the point just before the block.
2. Complete Allocation : Here you allocate the complete memory
at one time. If there are blocks within the procedure, then
allowance is made for the storage needed for declarations
within the books. If two variables are never alive at the same
time and are at same depth they can be assigned same storage.
55. Lexical scope without nested procedures
A procedure definition cannot occur within another
Therefore, all non local references are global and can be
allocated at compile time
Any name non-local to one procedure is non-local to all
procedures
55
procedures
In absence of nested procedures use stack allocation
Storage for non locals is allocated statically
A non local name must be local to the top of the stack
Stack allocation of non local has advantage:
• Non locals have static allocations
• Procedures can be passed/returned as parameters
56. Lexical scope without nested procedures
In languages like C nested procedures are not allowed. That is, you
cannot define a procedure inside another procedure. So, if there is a
non- local reference to a name in some function then that variable must
be a global variable. The scope of a global variable holds within all
the functions except those in which the variables have been re-
declared. Storage for all names declared globally can be allocated
56
declared. Storage for all names declared globally can be allocated
statically. Thus their positions will be known at compile time. In static
allocation, we use stack allocation. Any other name must be a local of
the activation at the top of the stack, accessible through the top pointer.
Nested procedures cause this scheme to fail because a non-local may
then refer to a local of parent variable which may be buried deep in
the stack and not at the top of stack. An important benefit of static
allocation for non- locals is that declared procedures can freely be
passed as parameters and returned as results (a function is passed in C
by passing a pointer to it).
58. Scope with nested procedures
58
The above example contains a program in Pascal with nested
procedure sort
1. Readarray
2. Exchange
Quicksort3. Quicksort
4. Partition
Here we apply the most closely nested rule for deciding
scoping of variables and procedure names. The procedure
exchange called by partition , is non-local to partition.
Applying the rule, we first check if exchange is defined within
quicksort ; since it is not, we look for it in the main program
sort.
59. Nesting Depth
59
Main procedure is at depth 1
Add 1 to depth as we go from enclosing to enclosed
procedure
Access to non-local names
Include a field 'access link' in the activation recordInclude a field 'access link' in the activation record
If p is nested in q then access link of p points to the access link
in most recent activation of q
60. Nesting Depth
60
Nesting Depth: The notion of nesting depth is used to
implement lexical scope. The main program is assumed to be
at nesting depth 1 and we add 1 to the nesting depth as we
go from an enclosing to an enclosed procedure.
Access Links: To implement the lexical scope for nestedAccess Links: To implement the lexical scope for nested
procedures we add a pointer called an access link to each
activation record. If a procedure p is nested immediately
within q in the source text, then the access link in an activation
record for p points to the access link in the record for most
recent activation of q .
62. Access to non local names
62
Suppose procedure p at depth np refers to a non- local a at
depth na, then storage for a can be found as
follow (np-na) access links from the record at the top of the
stack
after following (np-na) links we reach procedure for whichafter following (np-na) links we reach procedure for which
a is local
Therefore, address of a non local a in procedure p can be
stored in symbol table as
(np-na, offset of a in record of activation having a )
63. Access to non local names
63
Suppose procedure p at depth np refers to a non-local a with
nesting depth na = np. The storage for a can be found as follows:
When control is in p, an activation record for p is at the top
of the stack. Follow the (np - na) access links from the record
at the top of the stack.at the top of the stack.
After following (np - na) links, we reach an activation record
for the procedure that a is local to. As discussed earlier, its
storage is at a fixed offset relative to a position in the
record. In particular, the offset can be relative to the access
link.
The address of non-local a in procedure p is stored as following
in the symbol table:
(np - na, offset within the activation record containing a)
64. How to setup access links?
64
suppose procedure p at depth np calls procedure x at depth nx.
The code for setting up access links depends upon whether the
called procedure is nested within the caller.
np < nx
Called procedure is nested more deeply than p. Therefore, xCalled procedure is nested more deeply than p. Therefore, x
must be declared in p. The access link in the called procedure
must point to the access link of the activation just below it
np ≥ nx
From scoping rules enclosing procedure at the depth 1,2,. ,nx-1
must be same. Follow np-(nx-1) links from the caller, we reach the
most recent activation of the procedure that encloses both called
and calling procedure
65. Procedure Parameters
65
program param (input,output);
procedure b( function h(n:integer): integer);
begin
writeln (h(2))
end;
procedure c;
var m: integer;var m: integer;
function f(n: integer): integer;
begin
f := m + n
end;
begin
m :=0; b(f)
end;
begin
c
end.
66. Procedure Parameters
66
Scope of m does not include procedure b
within b, call h(2) activates f
it outputs f(2) which is 2
how is access link for activation of f is set up?
a nested procedure must take its access link along with it
when c passes f:
it determines access link for f as if it were calling f
this link is passed along with f to b
67. Procedure Parameters
67
Lexical scope rules apply even when a nested procedure is
passed as a parameter. In the program shown in the previous
slide, the scope of declaration of m does not include the body
of b. Within the body of b, the call h(2) activates f because
the formal h refers to f. Now how to set up the access link forthe formal h refers to f. Now how to set up the access link for
the activation of f? The answer is that a nested procedure that
is passed as a parameter must take its access link along with it,
as shown in the next slide. When procedure c passes f, it
determines an access link for f, just as it would if it were calling
f. This link is passed along with f to b. Subsequently, when f is
activated from within b, the link is used to set up the access link
in the activation record for f.
69. Displays
69
Faster access to non locals
Uses an array of pointers to activation records
Non locals at depth i is in the activation record pointed to by
d[i]
70. Dynamic Scope
70
Binding of non local names to storage do not change when
new activation is set up
A non local name a in the called activation refers to same
storage that it did in the calling activation
In dynamic scope , a new activation inherits the existing
bindings of non local names to storage. A non local name a
in the called activation refers to the same storage that it did
in the calling activation. New bindings are set up for the
local names of the called procedure, the names refer to
storage in the new activation record.
72. Dynamic Scoping: Example
72
Output under lexical scoping
0.250 0.250
0.250 0.250
Output under dynamic scoping
0.250 0.125
0.250 0.125
The outputs under the lexical and the dynamic scoping are as
shown. Under dynamic scoping, when show is called in the main
program, 0.250 is written because the variable r local to the
main program is used. However, when show is called from
within small, 0.125 is written because the variable r local to
small is used.
73. Implementing Dynamic Scope
73
Deep Access
Dispense with access links
use control links to search into the stack
term deep access comes from the fact that search may go
deep into the stackdeep into the stack
Shallow Access
hold current value of each name in static memory
when a new activation of p occurs a local name n in p takes
over the storage for n
previous value of n is saved in the activation record of p
74. Implementing Dynamic Scope
74
We will discuss two approaches to implement dynamic scope. They bear
resemblance to the use of access links and displays, respectively, in the
implementation of the lexical scope.
1. Deep Access : Dynamic scope results if access links point to the same
activation records that control links do. A simple implementation is to
dispense with access links and use control links to search into the stack,dispense with access links and use control links to search into the stack,
looking for the first activation record containing storage for the non-
local name. The term deep access comes from the fact that search may
go deep into the stack. The depth to which the search may go depends
on the input of the program and cannot be determined at compile time.
2. Shallow Access : Here the idea is to hold the current value of each name
in static memory. When a new activation of a procedure p occurs, a
local name n in p takes over the storage for n. The previous value of n is
saved in the activation record for p and is restored when the activation
of p ends.
75. Parameter Passing
75
Call by value
actual parameters are evaluated and their rvalues are passed
to the called procedure
used in Pascal and C
formal is treated just like a local nameformal is treated just like a local name
caller evaluates the actual parameters and places rvalue in the
storage for formals
call has no effect on the activation record of caller
This is, in a sense, the simplest possible method of passing
76. Parameter Passing
76
Call by value
This is, in a sense, the simplest possible method of passing
parameters. The actual parameters are evaluated and their r-
values are passed to the called procedure. Call-by-value is
used in C, and Pascal parameters are usually passed this way.used in C, and Pascal parameters are usually passed this way.
Call-by-Value can be implemented as follows:
1. A formal parameter is treated just like a local name, so the
storage for the formals is in the activation record of the
called procedure.
2. The caller evaluates the actual parameters and places their r-
values in the storage for the formals. A distinguishing feature
of call-by-value is that operations on the formal parameters
do not affect values in the activation record of the caller.
77. Parameter Passing
77
Call by reference (call by address)
the caller passes a pointer to each location of actual
parameters
if actual parameter is a name then lvalue is passed
if actual parameter is an expression then it is evaluated in aif actual parameter is an expression then it is evaluated in a
new location and the address of that location is passed
78. Parameter Passing
78
Call by reference (call by address)
When the parameters are passed by reference (also known as
call-by-address or call-by location), the caller passes to the
called procedure a pointer to the storage address of each
actual parameter.actual parameter.
1. If an actual parameter is a name or an expression having an
l-value, then that l-value itself is passed.
2. However, if the actual parameter is an expression, like a + b
or 2, that has no l-value, then the expression is evaluated in a
new location, and the address of that location is passed.
A reference to a formal parameter in the called procedure
becomes, in the target code, an indirect reference through the
pointer passed to the called procedure.
79. Parameter Passing
79
Copy restore (copy-in copy-out, call by value result)
actual parameters are evaluated, rvalues are passed by call
by value, lvalues are determined before the call
when control returns, the current rvalues of the formals are
copied into lvalues of the localscopied into lvalues of the locals
80. Parameter Passing
80
Copy restore (copy-in copy-out, call by value result)
This is a hybrid form between call-by-value and call-by-
reference (also known as copy-in copy-out or value-result).
1. Before control flows to the called procedure, the actual
parameters are evaluated. The r-values of the actuals areparameters are evaluated. The r-values of the actuals are
passed to the called procedure as in call-by-value. In
addition, however, the l-values of those actual parameters
having l-values are determined before the call.
2. When the control returns, the current r-values of the formal
parameters are copied back into the l-values of the actuals,
using the l-values computed before the call. Only the actuals
having l-values are copied.
81. Parameter Passing
81
Call by name (used in Algol)
names are copied
local names are different from names of calling procedure
swap(i,a[i])
temp = I
i = a[i]
a[i] = temp
82. Parameter Passing
82
Call by name (used in Algol)
This is defined by the copy-rule as used in Algol.
1. The procedure is treated as if it were a macro; that is, its
body is substituted for the call in the caller, with the actual
parameters literally substituted for the formals. Such a literalparameters literally substituted for the formals. Such a literal
substitution is called macro-expansion or inline expansion.
2. The local names of the called procedure are kept distinct
from the names of the calling procedure. We can think of
each local of the called procedure being systematically
renamed into a distinct new name before macro-expansion is
done.
3. The actual parameters are surrounded by parentheses if
necessary to preserve their integrity.
84. Dynamic Allocation
Returning the address of a local variable is defined to be a
logical error (e.g. in C)
In a dynamic environment there is no such restriction
All variables and activation records must be maintained for
as long as there are references to them
84
as long as there are references to them
Callee outlives the caller
It is also possible to return pointers to local functions
Must deallocate space when procedures and variables are
no longer needed (garbage collection)
85. Dynamic Allocation
Use a heap to maintain these records
Also called free store
Heap management is challenging
85
86. Language Facility for Dynamic Storage Allocation
Storage is usually taken from heap
Allocated data is retained until deallocated
Allocation can be either explicit or implicit
Pascal: explicit allocation and de-allocation by new() and
dispose()
86
dispose()
Lisp: implicit allocation when cons is used, and de- allocation
through garbage collection
87. Static storage allocation is usually done on the stack, as this is a
convenient way to take care of the normal scoping rules, where
the most recent values have to be considered, and when the
scope ends, their values have to be removed.
But for dynamic allocation, no such prior information regarding
87
Language Facility for Dynamic Storage Allocation
But for dynamic allocation, no such prior information regarding
the use of the variables is available. So we need the maximum
possible flexibility in this. For this a heap is used.
For the sake of a more efficient utilization of memory, the stack
grows downwards and the heap grows upwards, starting from
different ends of the available memory. This makes sure that all
available memory is utilized.
88. Pascal allows for explicit allocation and de-allocation of
memory. This can be done by using the new() and dispose()
functions.
However, in Lisp, continuous checking is done for free memory.
When less than 20 percent of the memory is free, then garbage
88
Language Facility for Dynamic Storage Allocation
When less than 20 percent of the memory is free, then garbage
collection is performed.
In garbage collection, cells that can no longer be accessed are
de-allocated. (Storage that has been allocated but can no
longer be accessed is called 'garbage'.)
90. Generally languages like Lisp and ML which do not allow for explicit de-allocation
of memory do garbage collection. A reference to a pointer that is no longer
valid is called a 'dangling reference'. For example, consider this C code:
int main (void)
{
int* a=fun();
}
Dynamic Storage Allocation
90
}
int* fun()
{
int a=3;
int* b=&a;
return b;
}
Here, the pointer returned by fun() no longer points to a valid address in
memory as the activation of fun() has ended. This kind of situation is called
a 'dangling reference'. In case of explicit allocation it is more likely to
happen as the user can de-allocate any part of memory, even something
that has to a pointer pointing to a valid piece of memory.
91. Explicit Allocation of Fixed Sized Blocks
Link the blocks in a list
Allocation and de-allocation can be done with very little overhead
The simplest form of dynamic allocation involves blocks of
a fixed size.
Dynamic Storage Allocation
91
a fixed size.
By linking the blocks in a list, as shown in the figure, allocation
and de-allocation can be done quickly with little or no storage
overhead.
92. Explicit Allocation of Fixed Sized Blocks .
blocks are drawn from contiguous area of storage
An area of each block is used as pointer to the next block
A pointer available points to the first block
Allocation means removing a block from the available list
Dynamic Storage Allocation
92
Allocation means removing a block from the available list
De-allocation means putting the block in the available list
Compiler routines need not know the type of objects to be held
in the blocks
Each block is treated as a variant record
93. Explicit Allocation of Variable Size Blocks
• Storage can become fragmented
• Situation may arise
If program allocates five blocks
then de-allocates second and fourth block
Dynamic Storage Allocation
93
• Fragmentation is of no consequence if blocks are of fixed size
• Blocks can not be allocated even if space is available
94. First Fit Method
When a block of size s is to be allocated
- search first free block of size f ≥ s
94
Dynamic Storage Allocation
- sub divide into two blocks of size s and f-s
- time overhead for searching a free block
When a block is de-allocated
- check if it is next to a free block
- combine with the free block to create a larger free block
95. Implicit De-allocation
Requires co-operation between user program and run
time system
Run time system needs to know when a block is no longer in use
Implemented by fixing the format of storage blocks
95
Dynamic Storage Allocation
Implemented by fixing the format of storage blocks
Implicit deallocation requires cooperation between the user
program and run time package,