CD Unit3,4
CD Unit3,4
This process of locating errors and reporting it to user is called Error Handling process.
Functions of Error handler
● Detection
● Reporting
● Recovery
Classification of errors:-
1. Compile time
2. Run time
Finding error or reporting an error – Viable-prefix is the property of a parser which allows
These errors are detected during the lexical analysis phase. Typical lexical errors are
These errors are detected during syntax analysis phase. Typical syntax errors are
● Errors in structure
● Missing operator
● Misspelled keywords
● Unbalanced parenthesis
Semantic errors
These errors are detected during semantic analysis phase. Typical semantic errors are
● To implement type checking, by verifying assignments and expressions in the source code are
semantically correct.
1. List –In this method, an array is used to store names and associated information.
● A pointer “available” is maintained at end of all stored records and new names are added in
the order as they arrive
● To search for a name we start from beginning of list till available pointer and if not found
we get an error “use of undeclared name”
● While inserting a new name we must ensure that it is not already present otherwise error
occurs i.e. “Multiple defined name”
● Insertion is fast O(1), but lookup is slow for large tables – O(n) on average
● Advantage is that it takes minimum amount of space.
2. LinkedList
3. HashTable
4. Bst
A symbol table is simply a table which can be either linear or a hash table. It maintains an entry for each
name in the following format:
For example, if a symbol table has to store information about the following variable declaration:
Scope Management
A compiler maintains two types of symbol tables: a global symbol table which can be accessed by all the
procedures and scope symbol tables that are created for each scope in the program.
To determine the scope of a name, symbol tables are arranged in hierarchical structure
● first a symbol will be searched in the current scope, i.e. current symbol table.
● if a name is found, then search is completed, else it will be searched in the parent symbol table
until,
● either the name is found or global symbol table has been searched for the name.
procedure is called its activation. An activation record contains all the necessary information required to
call a procedure. An activation record may contain the following units (depending upon the source
language used).
Machine Status Stores machine status such as Registers, Program Counter etc., before the
procedure is called.
Control Link Stores the address of activation record of the caller procedure.
Access Link Stores the information of data which is outside the local scope.
Actual Parameters Stores actual parameters, i.e., parameters which are used to send input to
the called procedure.
stack.
We assume that the program control flows in a sequential manner and when a procedure is called, its
control is transferred to the called procedure. When a called procedure is executed, it returns the
control back to the caller. This type of control flow makes it easier to represent a series of activations
. . .
scanf(“%s”, username);
show_data(username);
. . .
{
return 0;
}
Storage Allocation
Runtime environment manages runtime memory requirements for the following entities:
● Code : It is known as the text part of a program that does not change at runtime. Its memory requirements
● Procedures : Their text part is static but they are called in a random manner. That is why, stack storage is
● Variables : Variables are known at the runtime only, unless they are global or constant. Heap memory
allocation scheme is used for managing allocation and de-allocation of memory for variables in runtime.
Static Allocation
In this allocation scheme, the compilation data is bound to a fixed location in the memory and it does not change
when the program executes. As the memory requirement and storage locations are known in advance, runtime
support package for memory allocation and de-allocation is not required.
Stack Allocation
Procedure calls and their activations are managed by means of stack memory allocation. It works in last-in-first-out
(LIFO) method and this allocation strategy is very useful for recursive procedure calls.
Heap Allocation
Variables local to a procedure are allocated and de-allocated only at runtime. Heap allocation is used to
dynamically allocate memory to the variables and claim it back when the variables are no more required.
Except statically allocated memory area, both stack and heap memory can grow and shrink dynamically and
unexpectedly. Therefore, they cannot be provided with a fixed amount of memory in the system.
Stack and heap memory are arranged at the extremes of total memory allocated to the program. Both shrink and
grow against each other.
Parameter Passing
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 it appears on the right-hand side of the assignment operator.
l-value
The location of memory (address) where an expression is stored is known as the l-value of that
expression. It always appears at the left hand side of an assignment operator.
Code Optimization
Optimization is a program transformation technique, which tries to improve the code by making it
consume less resources (i.e. CPU, Memory) and deliver high speed.
In optimization, high-level general programming constructs are replaced by very efficient low-level
programming codes. A code optimizing process must follow the three rules given below:
● The output code must not, in any way, change the meaning of the program.
● Optimization should increase the speed of the program and if possible, the program should demand
● Optimization should itself be fast and should not delay the overall compiling process.
Efforts for an optimized code can be made at various levels of compiling the process.
● At the beginning, users can change/rearrange the code or use better algorithms to write the code.
● After generating intermediate code, the compiler can modify the intermediate code by address
● While producing the target machine code, the compiler can make use of memory hierarchy and CPU
registers.
Optimization can be categorized broadly into two types : machine independent and machine
dependent.
Machine-independent Optimization
In this optimization, the compiler takes in the intermediate code and transforms a part of the code
that does not involve any CPU registers and/or absolute memory locations. For example:
do
} while(value<100);
This code involves repeated assignment of the identifier item, which if we put this way:
do
} while(value<100);
Machine-dependent Optimization
Machine-dependent optimization is done after the target code has been generated and when the code
is transformed according to the target machine architecture. It involves CPU registers and may have
absolute memory references rather than relative references. Machine-dependent optimizers put
efforts to take maximum advantage of memory hierarchy.
Basic Blocks
Source codes generally have a number of instructions, which are always executed in sequence and
are considered as the basic blocks of the code. These basic blocks do not have any jump statements
among them,
Basic blocks are important concepts from both code generation and optimization point of view.
Basic blocks play an important role in identifying variables, which are being used more than once in
a single basic block. If any variable is being used more than once, the register memory allocated to
that variable need not be emptied unless the block finishes execution.
Most programs run as a loop in the system. It becomes necessary to optimize the loops in order to
save CPU cycles and memory. Loops can be optimized by the following techniques:
● Invariant code : A fragment of code that resides in the loop and computes the same value at each
iteration is called a loop-invariant code. This code can be moved out of the loop by saving it to be
● Induction analysis : A variable is called an induction variable if its value is altered within the loop by a
loop-invariant value.
● Strength reduction : There are expressions that consume more CPU cycles, time, and memory. These
expressions should be replaced with cheaper expressions without compromising the output of
expression. For example, multiplication (x * 2) is expensive in terms of CPU cycles than (x << 1) and
Dead-code Elimination
Dead code is one or more than one code statements, which are:
There are some code statements whose computed values are used only under certain circumstances,
i.e., sometimes the values are used and sometimes they are not. Such codes are known as partially
dead-code.
The above control flow graph depicts a chunk of program where variable ‘a’ is used to assign the
output of expression ‘x * y’. Let us assume that the value assigned to ‘a’ is never used inside the
loop.Immediately after the control leaves the loop, ‘a’ is assigned the value of variable ‘z’, which
would be used later in the program. We conclude here that the assignment code of ‘a’ is never used
anywhere, therefore it is eligible to be eliminated.
Partial Redundancy
Redundant expressions are computed more than once in parallel path, without any change in
operands.whereas partial-redundant expressions are computed more than once in a path, without any
change in operands. For example,
[redundant expression] [partially redundant expression]
Directed Acyclic Graph (DAG) is a tool that depicts the structure of basic blocks, helps to see the
flow of values flowing among the basic blocks, and offers optimization too. DAG provides easy
transformation on basic blocks. DAG can be understood here:
● Interior nodes also represent the results of expressions or the identifiers/name where the values are to
be stored or assigned.
Example:
[t1 = t0 + c]
[d = t0 + t1]
Peephole Optimization
This optimization technique works locally on the source code to transform it into an optimized code.
By locally, we mean a small portion of the code block at hand. These methods can be applied on
intermediate codes as well as on target codes. A bunch of statements is analyzed and are checked for
the following possible optimization:
int add_ten(int x) int add_ten(int x) int add_ten(int x) int add_ten(int x)
{ { { {
int y, z; int y; int y = 10; return x + 10;
y = 10; y = 10; return x + y; }
z = x + y; y = x + y; }
return z; return y;
} }
At compilation level, the compiler searches for instructions redundant in nature. Multiple loading
and storing of instructions may carry the same meaning even if some of them are removed. For
example:
● MOV x, R0
● MOV R0, R1
We can delete the first instruction and rewrite the sentence as:
MOV x, R1
Unreachable code
Unreachable code is a part of the program code that is never accessed because of programming constructs.
Programmers may have accidentally written a piece of code that can never be reached.
Example:
void add_ten(int x)
return x + 10;
In this code segment, the printf statement will never be executed as the program control returns back before it can
execute, hence printf can be removed.
...
MOV R1, R2
GOTO L1
...
L1 : GOTO L2
L2 : INC R1
In this code,label L1 can be removed as it passes the control to L2. So instead of jumping to L1 and then to L2, the
control can directly reach L2, as shown below:
...
MOV R1, R2
GOTO L2
...
L2 : INC R1
Strength reduction
There are operations that consume more time and space. Their ‘strength’ can be reduced by replacing
them with other operations that consume less time and space, but produce the same result.
For example, x * 2 can be replaced by x << 1, which involves only one left shift. Though the output of a
* a and a2 is same, a2 is much more efficient to implement.
Code Generator
A code generator is expected to have an understanding of the target machine’s runtime environment and its
instruction set. The code generator should take the following things into consideration to generate the code:
● Target language : The code generator has to be aware of the nature of the target language for which
the code is to be transformed. That language may facilitate some machine-specific instructions to help
the compiler generate the code in a more convenient way. The target machine can have either CISC or
● IR Type : Intermediate representation has various forms. It can be in Abstract Syntax Tree
● Selection of instruction : The code generator takes Intermediate Representation as input and converts
(maps) it into target machine’s instruction set. One representation can have many ways (instructions)
to convert it, so it becomes the responsibility of the code generator to choose the appropriate
instructions wisely.
● Register allocation : A program has a number of values to be maintained during the execution.
The target machine’s architecture may not allow all of the values to be kept in the CPU memory or
registers. Code generator decides what values to keep in the registers. Also, it decides the registers to
● Ordering of instructions : At last, the code generator decides the order in which the instruction will be
Descriptors
The code generator has to track both the registers (for availability) and addresses (location of values) while
generating the code. For both of them, the following two descriptors are used:
● Register descriptor : Register descriptor is used to inform the code generator about the
availability of registers. Register descriptor keeps track of values stored in each register. Whenever a
new register is required during code generation, this descriptor is consulted for register availability.
● Address descriptor : Values of the names (identifiers) used in the program might be stored at different
locations while in execution. Address descriptors are used to keep track of memory locations where
the values of identifiers are stored. These locations may include CPU registers, heaps, stacks, memory
Code generator keeps both the descriptor updated in real-time. For a load statement, LD R1, x, the code generator:
● updates the Register Descriptor R1 that has value of x and
● updates the Address Descriptor (x) to show that one instance of x is in R1.
Code Generation
Basic blocks comprise of a sequence of three-address instructions. Code generator takes these sequence of
instructions as input.
getReg : Code generator uses getReg function to determine the status of available registers and the location of name
values. getReg works as follows:
● Else if both the above options are not possible, it chooses a register that requires minimal number of
For an instruction x = y OP z, the code generator may perform the following actions. Let us assume that L is
the location (preferably register) where the output of y OP z is to be saved:
y is not presently in register L, then generate the following instruction to copy the value of y to L:
MOV y’, L
● Determine the present location of z using the same method used in step 2 for yand generate the
following instruction:
OP z’, L
● Now L contains the value of y OP z, that is intended to be assigned to x. So, if L is a register, update
its descriptor to indicate that it contains the value of x. Update the descriptor of x to indicate that it is
stored at location L.
● If y and z has no further use, they can be given back to the system.