Runtime Environments in Compiler Design
Last Updated :
28 Dec, 2024
A translation needs to relate the static source text of a program to the dynamic actions that must occur at runtime to implement the program. The program consists of names for procedures, identifiers, etc., that require mapping with the actual memory location at runtime. Runtime environment is a state of the target machine, which may include software libraries, environment variables, etc., to provide services to the processes running in the system.
SOURCE LANGUAGE ISSUES
Activation Tree
A program consist of procedures, a procedure definition is a declaration that, in its simplest form, associates an identifier (procedure name) with a statement (body of the procedure). Each execution of the procedure is referred to as an activation of the procedure. Lifetime of an activation is the sequence of steps present in the execution of the procedure. If âaâ and âbâ be two procedures then their activations will be non-overlapping (when one is called after other) or nested (nested procedures). A procedure is recursive if a new activation begins before an earlier activation of the same procedure has ended. An activation tree shows the way control enters and leaves activations. Properties of activation trees are :-
- Each node represents an activation of a procedure.
- The root shows the activation of the main function.
- The node for procedure âxâ is the parent of node for procedure âyâ if and only if the control flows from procedure x to procedure y.
Example – Consider the following program of Quicksort
main() {
Int n;
readarray();
quicksort(1,n);
}
quicksort(int m, int n) {
Int i= partition(m,n);
quicksort(m,i-1);
quicksort(i+1,n);
}The activation tree for this program will be:
First main function as the root then main calls readarray and quicksort. Quicksort in turn calls partition and quicksort again. The flow of control in a program corresponds to a pre-order depth-first traversal of the activation tree which starts at the root.
CONTROL STACK AND ACTIVATION RECORDS
Control stack or runtime stack is used to keep track of the live procedure activations i.e the procedures whose execution have not been completed. A procedure name is pushed on to the stack when it is called (activation begins) and it is popped when it returns (activation ends). Information needed by a single execution of a procedure is managed using an activation record or frame. When a procedure is called, an activation record is pushed into the stack and as soon as the control returns to the caller function the activation record is popped.

A general activation record consists of the following things:
- Local variables: hold the data that is local to the execution of the procedure.
- Temporary values : stores the values that arise in the evaluation of an expression.
- Machine status: holds the information about the status of the machine just before the function call.
- Access link (optional): refers to non-local data held in other activation records.
- Control link (optional): points to activation record of caller.
- Return value: used by the called procedure to return a value to calling procedure
- Actual parameters

Control stack for the above quicksort example:

SUBDIVISION OF RUNTIME MEMORY
Runtime storage can be subdivided to hold :
- Target code- the program code, is static as its size can be determined at compile time
- Static data objects
- Dynamic data objects- heap
- Automatic data objects- stack

STORAGE ALLOCATION TECHNIQUES
I. Static Storage Allocation
The names are bound with the storage at compiler time only and hence every time procedure is invoked its names are bound to the same storage location only So values of local names can be retained across activations of a procedure. Here compiler can decide where the activation records go with respect to the target code and can also fill the addresses in the target code for the data it operates on.
- For any program, if we create a memory at compile time, memory will be created in the static area.
- For any program, if we create a memory at compile-time only, memory is created only once.
- It doesnât support dynamic data structure i.e memory is created at compile-time and deallocated after program completion.
- The drawback with static storage allocation is recursion is not supported.
- Another drawback is the size of data should be known at compile time
Eg- FORTRAN was designed to permit static storage allocation.
II. Stack Storage Allocation
- Storage is organized as a stack and activation records are pushed and popped as activation begins and end respectively. Locals are contained in activation records so they are bound to fresh storage in each activation.
- Recursion is supported in stack allocation
III. Heap Storage Allocation
- Memory allocation and deallocation can be done at any time and at any place depending on the requirement of the user.
- Heap allocation is used to dynamically allocate memory to the variables and claim it back when the variables are no more required.
- Recursion is supported.

PARAMETER PASSING: The communication medium among procedures is known as parameter passing. The values of the variables from a calling procedure are transferred to the called procedure by some mechanism.
Basic terminology :
- R- value: The value of an expression is called its r-value. The value contained in a single variable also becomes an r-value if its appear on the right side of the assignment operator. R-value can always be assigned to some other variable.
- L-value: The location of the memory(address) where the expression is stored is known as the l-value of that expression. It always appears on the left side if the assignment operator.

- i.Formal Parameter: Variables that take the information passed by the caller procedure are called formal parameters. These variables are declared in the definition of the called function. ii.Actual Parameter: Variables whose values and functions are passed to the called function are called actual parameters. These variables are specified in the function call as arguments.
Different ways of passing the parameters to the procedure:
- Call by Value: In call by value the calling procedure passes the r-value of the actual parameters and the compiler puts that into called procedure’s activation record. Formal parameters hold the values passed by the calling procedure, thus any changes made in the formal parameters do not affect the actual parameters.

- Call by Reference In call by reference the formal and actual parameters refers to same memory location. The l-value of actual parameters is copied to the activation record of the called function. Thus the called function has the address of the actual parameters. If the actual parameters does not have a l-value (eg- i+3) then it is evaluated in a new temporary location and the address of the location is passed. Any changes made in the formal parameter is reflected in the actual parameters (because changes are made at the address).

- Call by Copy Restore In call by copy restore compiler copies the value in formal parameters when the procedure is called and copy them back in actual parameters when control returns to the called function. The r-values are passed and on return r-value of formals are copied into l-value of actuals.
C++
#include <iostream>
using namespace std;
void swap(int& a, int& b)
{
/* A hybrid between call-by-value and call-by-reference
is copy-restore linkage (also known as copy in and
copy out ,or value-result) */
int copy_a, copy_b;
copy_a = a; // copy in phase
copy_b = b;
int temp = copy_a; // function proper
copy_a = copy_b;
copy_b = temp;
a = copy_a; // copy out phase
b = copy_b;
}
int main()
{
int a = 10, b = 20;
swap(a, b);
cout << a << " " << b << endl;
return 0;
}
// code added by raunakraj232
- Call by Name In call by name the actual parameters are substituted for formals in all the places formals occur in the procedure. It is also referred as lazy evaluation because evaluation is done on parameters only when needed.

Advantages:
Portability: A runtime environment can provide a layer of abstraction between the compiled code and the operating system, making it easier to port the program to different platforms.
Resource management: A runtime environment can manage system resources, such as memory and CPU time, making it easier to avoid memory leaks and other resource-related issues.
Dynamic memory allocation: A runtime environment can provide dynamic memory allocation, allowing memory to be allocated and freed as needed during program execution.
Garbage collection: A runtime environment can perform garbage collection, automatically freeing memory that is no longer being used by the program.
Exception handling: A runtime environment can provide exception handling, allowing the program to gracefully handle errors and prevent crashes.
Disadvantages:
Performance overhead: A runtime environment can add performance overhead, as it requires additional processing and memory usage.
Platform dependency: Some runtime environments may be specific to certain platforms, making it difficult to port programs to other platforms.
Debugging: Debugging can be more difficult in a runtime environment, as the additional layer of abstraction can make it harder to trace program execution.
Compatibility issues: Some runtime environments may not be compatible with certain operating systems or hardware architectures, which can limit their usefulness.
Versioning: Different versions of a runtime environment may have different features or APIs, which can lead to versioning issues when running programs compiled with different versions of the same runtime environment.
Similar Reads
Compiler Design Tutorial
A compiler is software that translates or converts a program written in a high-level language (Source Language) into a low-level language (Machine Language). Compiler design is the process of developing a program or software that converts human-written code into machine code. It involves many stages
3 min read
Introduction
Introduction of Compiler Design
Compiler design is, in fact, the translation of the source code written in a high-order programming language into the machine language that the computer will execute. It comprises a number of phases where the code is pre-processed, and parsed, its semantics or meaning are checked, and optimized, and
11 min read
Compiler construction tools
The compiler writer can use some specialized tools that help in implementing various phases of a compiler. These tools assist in the creation of an entire compiler or its parts. Some commonly used compiler construction tools include: Parser Generator - It produces syntax analyzers (parsers) from the
4 min read
Phases of a Compiler
Prerequisite - Introduction of Compiler design We basically have two phases of compilers, namely the Analysis phase and Synthesis phase. The analysis phase creates an intermediate representation from the given source code. The synthesis phase creates an equivalent target program from the intermediat
7 min read
Symbol Table in Compiler
Every compiler uses a major tool called the symbol table to keep track of all the variables, functions, and other identifiers a program may have. The symbol table will store the name, its type, and perhaps its memory locations to support the compiler in error checking, scope management, and the opti
10 min read
Error detection and Recovery in Compiler
In this phase of compilation, all possible errors made by the user are detected and reported to the user in form of error messages. This process of locating errors and reporting them to users is called the Error Handling process. Functions of an Error handler. DetectionReportingRecoveryClassificatio
6 min read
Error Handling in Compiler Design
The tasks of the Error Handling process are to detect each error, report it to the user, and then make some recovery strategy and implement them to handle the error. During this whole process processing time of the program should not be slow. Functions of Error Handler: Error DetectionError ReportEr
7 min read
Language Processors: Assembler, Compiler and Interpreter
Computer programs are generally written in high-level languages (like C++, Python, and Java). A language processor, or language translator, is a computer program that convert source code from one programming language to another language or to machine code (also known as object code). They also find
5 min read
Generation of Programming Languages
Programming languages have evolved significantly over time, moving from fundamental machine-specific code to complex languages that are simpler to write and understand. Each new generation of programming languages has improved, allowing developers to create more efficient, human-readable, and adapta
6 min read
Parsers
Parsing | Set 1 (Introduction, Ambiguity and Parsers)
Parsing, also known as syntactic analysis, refers to the process of performing token order analysis to determine the syntactic structure of tokens. In parsing, the token stream (generated by the word parser) is processed, and the parser constructs a parse tree or syntax tree. This tree provides a hi
4 min read
Classification of Top Down Parsers
Parsing is classified into two categories, i.e. Top-Down Parsing, and Bottom-Up Parsing. Top-Down Parsing is based on Left Most Derivation whereas Bottom-Up Parsing is dependent on Reverse Right Most Derivation. The process of constructing the parse tree which starts from the root and goes down to
5 min read
Bottom-up or Shift Reduce Parsers | Set 2
In this article, we are discussing the Bottom Up parser. Bottom-up Parsers / Shift Reduce Parsers Build the parse tree from leaves to root. Bottom-up parsing can be defined as an attempt to reduce the input string w to the start symbol of grammar by tracing out the rightmost derivations of w in reve
6 min read
Shift Reduce Parser in Compiler
Prerequisite â Parsing | Set 2 (Bottom Up or Shift Reduce Parsers) Shift Reduce parser attempts for the construction of parse in a similar manner as done in bottom-up parsing i.e. the parse tree is constructed from leaves(bottom) to the root(up). A more general form of the shift-reduce parser is the
8 min read
SLR Parser (with Examples)
LR parsers is an efficient bottom-up syntax analysis technique that can be used to parse large classes of context-free grammar is called LR(k) parsing. L stands for left-to-right scanningR stands for rightmost derivation in reversek is several input symbols. when k is omitted k is assumed to be 1. A
4 min read
CLR Parser (with Examples)
LR parsers :It is an efficient bottom-up syntax analysis technique that can be used to parse large classes of context-free grammar is called LR(k) parsing. L stands for the left to right scanningR stands for rightmost derivation in reversek stands for no. of input symbols of lookahead Advantages of
7 min read
Construction of LL(1) Parsing Table
Parsing is an essential part of computer science, especially in compilers and interpreters. From the various parsing techniques, LL(1) parsing is best. It uses a predictive, top-down approach. This allows efficient parsing without backtracking. This article will explore parsing and LL(1) parsing. It
7 min read
LALR Parser (with Examples)
LALR Parser :LALR Parser is lookahead LR parser. It is the most powerful parser which can handle large classes of grammar. The size of CLR parsing table is quite large as compared to other parsing table. LALR reduces the size of this table.LALR works similar to CLR. The only difference is , it combi
6 min read
Syntax Directed Translation
Code Generation and Optimization
Code Optimization in Compiler Design
Code optimization is a crucial phase in compiler design aimed at enhancing the performance and efficiency of the executable code. By improving the quality of the generated machine code optimizations can reduce execution time, minimize resource usage, and improve overall system performance. This proc
9 min read
Intermediate Code Generation in Compiler Design
In the analysis-synthesis model of a compiler, the front end of a compiler translates a source program into an independent intermediate code, then the back end of the compiler uses this intermediate code to generate the target code (which can be understood by the machine). The benefits of using mach
6 min read
Issues in the design of a code generator
Code generator converts the intermediate representation of source code into a form that can be readily executed by the machine. A code generator is expected to generate the correct code. Designing of the code generator should be done in such a way that it can be easily implemented, tested, and maint
5 min read
Three address code in Compiler
TAC is an intermediate representation of three-address code utilized by compilers to ease the process of code generation. Complex expressions are, therefore, decomposed into simple steps comprising, at most, three addresses: two operands and one result using this code. The results from TAC are alway
6 min read
Data flow analysis in Compiler
Data flow is analysis that determines the information regarding the definition and use of data in program. With the help of this analysis, optimization can be done. In general, its process in which values are computed using data flow analysis. The data flow property represents information that can b
6 min read
Compiler Design | Detection of a Loop in Three Address Code
Prerequisite - Three address code in Compiler Loop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent actually inside the loop for an iterative program. In the
3 min read
Introduction of Object Code in Compiler Design
Let assume that, you have a c program, then you give the C program to compiler and compiler will produce the output in assembly code. Now, that assembly language code will give to the assembler and assembler is going to produce you some code. That is known as Object Code. In the context of compiler
7 min read
Data flow analysis in Compiler
Data flow is analysis that determines the information regarding the definition and use of data in program. With the help of this analysis, optimization can be done. In general, its process in which values are computed using data flow analysis. The data flow property represents information that can b
6 min read
Compiler Design GATE PYQ's and MCQs