SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Downloaden Sie, um offline zu lesen
UNIT III: COMPILERS
3.2 PHASES OF THE COMPILER
A compiler is a software that accepts a program written in a high-level language and
produces its machine language equivalent. The process of compilation takes place in several
phases, which are shown below.

Source Program

Lexical Analyzer

Syntax Analyzer

Symbol Table

Intermediate Code
Generation & Semantic
Analyzer

Optimization
(optional)

Code Generation

Machine Code

Fig 1. The Compilation Process

Lexical Analysis Phase:
This is the first phase of a compiler. This phase is also called the scanning phase. The
compiler scans the source code from left to right, character by character, and groups
these characters into tokens. Each token represents a logically cohesive sequence of
characters such as variables, keywords, multi-character operators (such as :=, >=, ==,
etc). The main functions of this phase are summarised below:
(i)
(ii)
(iii)
(iv)
(v)

Identify the lexical units in a source statement.
Classify units into different lexical classes e.g., constants, reserved words, etc.,
and enter them in different tables.
build a descriptor (called a token) for each lexical unit.
ignore comments in the source program.
detect tokens which are not a part of the language.

The output of the lexical analysis phase goes to the syntax phase.
mukeshtekwani@hotmail.com

Page 1 of 6
Phases of the Compiler

Prof. Mukesh N. Tekwani

Syntax Analysis Phase:
This phase is also called the parsing phase. The following operations are performed in
this phase:
(i)
(ii)
(iii)
(iv)
(v)
(vi)

Obtain tokens from lexical analyzer.
check whether the expression is syntactically correct.
report syntax errors, if any.
determine the statement class, i.e., is it an assignment statement, a condition
statement (if statement), etc.
group tokens into statements,
construct hierarchical structures called parse trees. These parse trees represent
the syntactic structure of the program.

Consider the statement X = Y + Z. It is represented by the parse tree as shown below:
=

X

+

Y

Z

Fig 2. A Parse Tree

Intermediate Code Generation and Semantic Analysis Phase:
The intermediate code produces a program in a different language, at an intermediate
level between the source code and the machine code. Intermediate languages are
sometimes assembly languages. The generation of an intermediate code offers the
following advantages:
(i)

Flexibility: a single lexical analyzer / parser can be used to generate code for
several different machines by providing separate back-ends that translate a
common intermediate language to a machine-specific assembly language.

(ii)

Intermediate code is used in interpretation. The intermediate code is executed
directly rather than translating it into binary code and storing it.

Semantic Phase:
The semantic phase has the following functions:
(i)

check phrases for semantic errors e.g., type-checking. In a C program, int x =
10.5 should be detected as a semantic error.

Page 2 of 6

mukeshtekwani@hotmail.com
Prof. Mukesh N. Tekwani

Phases of the Compiler

(ii)

semantic analyzer keeps track of types of identifiers and expressions, to verify
their consistent usage.

(iii)

semantic analyzer maintains the symbol table. The symbol table contains
information about each identifier in a program. This information includes
identifier type, scope of identifier, etc.

(iv)

using the symbol table, the semantic analyzer enforces a large number of rules
such as:
a. every identifier is declared before it is used.
b. no identifier is used in an inappropriate context (e.g., adding a string to an
integer);
c. subroutine or function calls have a correct number and type of arguments,
d. every function contains at least one statement that specifies a return value.
These values are checked at compile time, hence they are called static semantics.

(v)

Certain semantic rules are checked at run time; these are called dynamic
semantics. Examples of these are:
a. array subscript expression lie within the bounds of the array.
b. variables are never used in an expression unless they have been given a
value.

Symbol Table:
The symbol table is built and maintained by the semantic analysis phase. It maps each
identifier to the information known about it. This information includes the identifier’s
type (int, char, float, etc), internal structure (if any), and scope (the portion of the
program in which it is valid). Using the symbol table, the semantic analyzer enforces a
large variety of rules, e.g., it ensures that
!" a variable is declared before it is used,
!" no identifier is used in an inappropriate context (adding a string to an integer,
!" subroutine calls provide the correct number and types of arguments,
!" labels on the arms of a case statement are distinct constants,
!" every function contains at least one statement that specifies a return value.
Code Generation Phase:
The code generated depends upon the architecture of the target machine. A knowledge
of the instructions and addressing modes in target computer is necessary for code
generation process.
One of the important aspects of code generation is the efficient initialization of machine
resources. A number of assumptions may be made such as:
a) instruction types in target machines
mukeshtekwani@hotmail.com

Page 3 of 6
Phases of the Compiler

Prof. Mukesh N. Tekwani

b) commutative property of operators in an expression
c) proper usage of syntax for syntax directed translation.

Code Optimization Phase:
Optimization improves programs by making them smaller or faster or both. The goal of
code optimization is to translate a program into a new version that computes the same
result more efficiently – by taking less time, memory, and other system resources. For
example, the C compiler “Turbo C” permits the programmer to optimize code for speed
or for size.
Code optimization is achieved in 2 ways:
a) rearranging computations in a program to make them execute more efficiently,
b) eliminating redundancies in a program.
Code optimization should not change the meaning of the program. Code optimization tries
to improve the program; the underlying algorithm is not affected. Thus, code optimization
cannot replace an inefficient algorithm with an algorithm which is more efficient. Code
optimization also cannot fully utilize the instruction set of a particular architecture. Thus,
code optimization is independent of the target machine and the PL.
An optimizing compiler is shown below. Note the presence of the optimization phase.

Source
Program

Front
End

Optimization
Phase

Back
End

Target
Program

Optimizing Transformations:
It is a rule for rewriting a segment of a program to improve its execution efficiency without
affecting its meaning. The two types of optimizing transformations are:
a) local transformations (applied over small segments of a program)
b) global transformations (applied over larger segments consisting of loops or function
bodies).
Some of the optimizing transformations used by compilers are:
i.

ii.

Compile time evaluation: Certain actions specified ina program can be
performed during the compilation stage itself. This eliminates the need to
perform them during execution stage. The main optimization of this type is
constant folding; if all the operands in an expression are constant, the operation
can be performed at compile time itself. The result of the operation, itself a
constant, then replaces the original expression. E.g., an assignment of the type
a:= 2.718/2 can be replaced by a:= 1.354. this eliminates an operation of
division.
Dead Code elimination:

Page 4 of 6

mukeshtekwani@hotmail.com
Prof. Mukesh N. Tekwani

Phases of the Compiler

Code which can be omitted from a program without affecting its results is called
dead code. If a variable is assigned a value which is never used subsequently in
the program, then that statement is a dead code.
E.g., j = 30;
Turbo C can point out such instances by way of a warning message.
iii.

Elimination of common sub-expressions:
Expressions which yield the same value are called common sub-expressions or
equivalent expressions. Consider the following code segments:
a:= b * c;

t := b*c;

:

a := t;

:

:

x := b * c + 3.5;

x := t + 3.5;

Here the two occurrences of b*c were eliminated by using a variable t.
iv.

Frequency Reduction:
Execution time of a program can be reduced by moving code from a part of a
program which is executed very frequently to another part of the program which
is executed fewer times. E.g., the transformation of loop optimization involves
moving loop invariant code out of a loop.

v.

Strength reduction:
This optimization technique reduces operation with a more efficient operation or
a series of operations that yield the same result in fewer machine clock cycles.
For example, multiplication by a power of two is replaced by a left shift, which
executes faster on most machines.
a = b * 4; becomes

a = b + b + b + b;

or

a = b << 2;

Similarly, division by powers of two are expensive operations and these can be
replaced with right shift.
c = d / 2; becomes

c = d >> 1;

Local and Global optimization:
a) Local transformations are applied over small segments of a program. This is a
preparatory phase for global optimization. It can be performed by the front end while
converting a source code into the IR. Local optimization provides limited benefits at
a low cost. The scope of this type of optimization is a basic block which is a
sequential set of instructions. Loop optimization cannot be performed by local
optimization.
b) Global transformations are applied over larger segments consisting of loops or
function bodies. It requires more analysis efforts to determine the feasibility of an
optimization. The techniques of control flow analysis and data flow analysis are
used to achieve global optimization.
mukeshtekwani@hotmail.com

Page 5 of 6
Phases of the Compiler

Prof. Mukesh N. Tekwani

Passes of a compiler:
Several phases of compilation are usually grouped into one pass consisting of reading an
input file and writing an output file.
For example, the following stages can be grouped into one pass:
i.

Lexical analysis,

ii.

Syntax analysis,

iii.

Semantic analysis, and

iv.

Intermediate code generation

It is desirable to have relatively few passes, since it takes time to read and write
intermediate files. On the other hand, if we group several phases into one pass, we may be
forced to keep the entire program in memory.

Difference between a phase and a pass of a compilation
Compilation proceeds through a set of well-defined phases; these are the lexical analysis,
syntax analysis, semantic analysis, intermediate code generation, machine independent code
optimization, code generation, and machine dependent code generation. Each phase
discovers information of use to later phases, or transforms the program into a form that is
more useful to the subsequent phases.
A pass is a phase or a set of phases that is serialized with respect to the rest of the
compilation. A pass does not start until the previous phases have been completed and it
finishes before any subsequent phases start.

REVIEW QUESTIONS
1.

List the principal phases of compilation and describe the work performed by each
phase.

2.

Explain the syntax analysis phase. What operations are carried out in this phase?

3.

Explain the semantic analysis phase. What operations are carried out in this phase?

4.

What is the difference between a phase and a pass of a compilation?

5.

What is the purpose of the compiler’s symbol table?

6.

What is the difference between static and dynamic semantics?

7.

What is meant by the term “compiler pass” ? How does it differ from a phase of
compilation?
#####

Page 6 of 6

mukeshtekwani@hotmail.com

Weitere Àhnliche Inhalte

Was ist angesagt?

Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow AnalysisEelco Visser
 
Basic blocks - compiler design
Basic blocks - compiler designBasic blocks - compiler design
Basic blocks - compiler designhmnasim15
 
Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)guest251d9a
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programmingMukesh Tekwani
 
Introduction to Compiler Construction
Introduction to Compiler Construction Introduction to Compiler Construction
Introduction to Compiler Construction Sarmad Ali
 
Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compilerAbha Damani
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compilerKaran Deopura
 
Types of Compilers
Types of CompilersTypes of Compilers
Types of CompilersHemant Chetwani
 
Assembler design options
Assembler design optionsAssembler design options
Assembler design optionsMohd Arif
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignKuppusamy P
 
phases of a compiler
 phases of a compiler phases of a compiler
phases of a compilerMs.SHANTHI.S CSE
 
Control hijacking
Control hijackingControl hijacking
Control hijackingG Prachi
 
Chapter 1 1
Chapter 1 1Chapter 1 1
Chapter 1 1bolovv
 
8 statement level
8 statement level8 statement level
8 statement levelMunawar Ahmed
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recoveryTech_MX
 

Was ist angesagt? (20)

Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow Analysis
 
Basic blocks - compiler design
Basic blocks - compiler designBasic blocks - compiler design
Basic blocks - compiler design
 
Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 
Introduction to Compiler Construction
Introduction to Compiler Construction Introduction to Compiler Construction
Introduction to Compiler Construction
 
Introduction to compiler
Introduction to compilerIntroduction to compiler
Introduction to compiler
 
Phases of compiler
Phases of compilerPhases of compiler
Phases of compiler
 
Compiler design
Compiler designCompiler design
Compiler design
 
Types of Compilers
Types of CompilersTypes of Compilers
Types of Compilers
 
Compiler1
Compiler1Compiler1
Compiler1
 
Context free grammar
Context free grammar Context free grammar
Context free grammar
 
Assembler design options
Assembler design optionsAssembler design options
Assembler design options
 
Intermediate code generation in Compiler Design
Intermediate code generation in Compiler DesignIntermediate code generation in Compiler Design
Intermediate code generation in Compiler Design
 
phases of a compiler
 phases of a compiler phases of a compiler
phases of a compiler
 
Control hijacking
Control hijackingControl hijacking
Control hijacking
 
Chapter 1 1
Chapter 1 1Chapter 1 1
Chapter 1 1
 
8 statement level
8 statement level8 statement level
8 statement level
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recovery
 
Yacc
YaccYacc
Yacc
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 

Andere mochten auch

Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQMukesh Tekwani
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examplesMukesh Tekwani
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular ExpressionsMukesh Tekwani
 
Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer Mukesh Tekwani
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signalsMukesh Tekwani
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1Mukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferWayne Jones Jnr
 

Andere mochten auch (18)

Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Java misc1
Java misc1Java misc1
Java misc1
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examples
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Html graphics
Html graphicsHtml graphics
Html graphics
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signals
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
 

Ähnlich wie Phases of the Compiler - Systems Programming

Dineshmaterial1 091225091539-phpapp02
Dineshmaterial1 091225091539-phpapp02Dineshmaterial1 091225091539-phpapp02
Dineshmaterial1 091225091539-phpapp02Tirumala Rao
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdfSemsemSameer1
 
Compiler Design(Nanthu)
Compiler Design(Nanthu)Compiler Design(Nanthu)
Compiler Design(Nanthu)guest91cc85
 
Compilerdesignnew 091219090526-phpapp02
Compilerdesignnew 091219090526-phpapp02Compilerdesignnew 091219090526-phpapp02
Compilerdesignnew 091219090526-phpapp02Anil Thakral
 
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docxvenkatapranaykumarGa
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compileradilmehmood93
 
Chapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdfChapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdfDrIsikoIsaac
 
Introduction to Compilers
Introduction to CompilersIntroduction to Compilers
Introduction to Compilersvijaya603274
 
unit1pdf__2021_12_14_12_37_34.pdf
unit1pdf__2021_12_14_12_37_34.pdfunit1pdf__2021_12_14_12_37_34.pdf
unit1pdf__2021_12_14_12_37_34.pdfDrIsikoIsaac
 
Ch 1.pptx
Ch 1.pptxCh 1.pptx
Ch 1.pptxwoldu2
 
Chapter#01 cc
Chapter#01 ccChapter#01 cc
Chapter#01 ccabdulbaki3
 
Compiler Construction introduction
Compiler Construction introductionCompiler Construction introduction
Compiler Construction introductionRana Ehtisham Ul Haq
 
design intoduction of_COMPILER_DESIGN.pdf
design intoduction of_COMPILER_DESIGN.pdfdesign intoduction of_COMPILER_DESIGN.pdf
design intoduction of_COMPILER_DESIGN.pdfadvRajatSharma
 

Ähnlich wie Phases of the Compiler - Systems Programming (20)

Dineshmaterial1 091225091539-phpapp02
Dineshmaterial1 091225091539-phpapp02Dineshmaterial1 091225091539-phpapp02
Dineshmaterial1 091225091539-phpapp02
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf
 
Compiler Design Material
Compiler Design MaterialCompiler Design Material
Compiler Design Material
 
Compiler Design(Nanthu)
Compiler Design(Nanthu)Compiler Design(Nanthu)
Compiler Design(Nanthu)
 
Compilerdesignnew 091219090526-phpapp02
Compilerdesignnew 091219090526-phpapp02Compilerdesignnew 091219090526-phpapp02
Compilerdesignnew 091219090526-phpapp02
 
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
2-Design Issues, Patterns, Lexemes, Tokens-28-04-2023.docx
 
Assignment1
Assignment1Assignment1
Assignment1
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
 
what is compiler and five phases of compiler
what is compiler and five phases of compilerwhat is compiler and five phases of compiler
what is compiler and five phases of compiler
 
Chapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdfChapter1pdf__2021_11_23_10_53_20.pdf
Chapter1pdf__2021_11_23_10_53_20.pdf
 
Introduction to Compilers
Introduction to CompilersIntroduction to Compilers
Introduction to Compilers
 
unit1pdf__2021_12_14_12_37_34.pdf
unit1pdf__2021_12_14_12_37_34.pdfunit1pdf__2021_12_14_12_37_34.pdf
unit1pdf__2021_12_14_12_37_34.pdf
 
Compiler presentaion
Compiler presentaionCompiler presentaion
Compiler presentaion
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Ch 1.pptx
Ch 1.pptxCh 1.pptx
Ch 1.pptx
 
3.2
3.23.2
3.2
 
phase of compiler
phase of compilerphase of compiler
phase of compiler
 
Chapter#01 cc
Chapter#01 ccChapter#01 cc
Chapter#01 cc
 
Compiler Construction introduction
Compiler Construction introductionCompiler Construction introduction
Compiler Construction introduction
 
design intoduction of_COMPILER_DESIGN.pdf
design intoduction of_COMPILER_DESIGN.pdfdesign intoduction of_COMPILER_DESIGN.pdf
design intoduction of_COMPILER_DESIGN.pdf
 

Mehr von Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code? Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrorsMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Mehr von Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

KĂŒrzlich hochgeladen

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...Nguyen Thanh Tu Collection
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 

KĂŒrzlich hochgeladen (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 

Phases of the Compiler - Systems Programming

  • 1. UNIT III: COMPILERS 3.2 PHASES OF THE COMPILER A compiler is a software that accepts a program written in a high-level language and produces its machine language equivalent. The process of compilation takes place in several phases, which are shown below. Source Program Lexical Analyzer Syntax Analyzer Symbol Table Intermediate Code Generation & Semantic Analyzer Optimization (optional) Code Generation Machine Code Fig 1. The Compilation Process Lexical Analysis Phase: This is the first phase of a compiler. This phase is also called the scanning phase. The compiler scans the source code from left to right, character by character, and groups these characters into tokens. Each token represents a logically cohesive sequence of characters such as variables, keywords, multi-character operators (such as :=, >=, ==, etc). The main functions of this phase are summarised below: (i) (ii) (iii) (iv) (v) Identify the lexical units in a source statement. Classify units into different lexical classes e.g., constants, reserved words, etc., and enter them in different tables. build a descriptor (called a token) for each lexical unit. ignore comments in the source program. detect tokens which are not a part of the language. The output of the lexical analysis phase goes to the syntax phase. mukeshtekwani@hotmail.com Page 1 of 6
  • 2. Phases of the Compiler Prof. Mukesh N. Tekwani Syntax Analysis Phase: This phase is also called the parsing phase. The following operations are performed in this phase: (i) (ii) (iii) (iv) (v) (vi) Obtain tokens from lexical analyzer. check whether the expression is syntactically correct. report syntax errors, if any. determine the statement class, i.e., is it an assignment statement, a condition statement (if statement), etc. group tokens into statements, construct hierarchical structures called parse trees. These parse trees represent the syntactic structure of the program. Consider the statement X = Y + Z. It is represented by the parse tree as shown below: = X + Y Z Fig 2. A Parse Tree Intermediate Code Generation and Semantic Analysis Phase: The intermediate code produces a program in a different language, at an intermediate level between the source code and the machine code. Intermediate languages are sometimes assembly languages. The generation of an intermediate code offers the following advantages: (i) Flexibility: a single lexical analyzer / parser can be used to generate code for several different machines by providing separate back-ends that translate a common intermediate language to a machine-specific assembly language. (ii) Intermediate code is used in interpretation. The intermediate code is executed directly rather than translating it into binary code and storing it. Semantic Phase: The semantic phase has the following functions: (i) check phrases for semantic errors e.g., type-checking. In a C program, int x = 10.5 should be detected as a semantic error. Page 2 of 6 mukeshtekwani@hotmail.com
  • 3. Prof. Mukesh N. Tekwani Phases of the Compiler (ii) semantic analyzer keeps track of types of identifiers and expressions, to verify their consistent usage. (iii) semantic analyzer maintains the symbol table. The symbol table contains information about each identifier in a program. This information includes identifier type, scope of identifier, etc. (iv) using the symbol table, the semantic analyzer enforces a large number of rules such as: a. every identifier is declared before it is used. b. no identifier is used in an inappropriate context (e.g., adding a string to an integer); c. subroutine or function calls have a correct number and type of arguments, d. every function contains at least one statement that specifies a return value. These values are checked at compile time, hence they are called static semantics. (v) Certain semantic rules are checked at run time; these are called dynamic semantics. Examples of these are: a. array subscript expression lie within the bounds of the array. b. variables are never used in an expression unless they have been given a value. Symbol Table: The symbol table is built and maintained by the semantic analysis phase. It maps each identifier to the information known about it. This information includes the identifier’s type (int, char, float, etc), internal structure (if any), and scope (the portion of the program in which it is valid). Using the symbol table, the semantic analyzer enforces a large variety of rules, e.g., it ensures that !" a variable is declared before it is used, !" no identifier is used in an inappropriate context (adding a string to an integer, !" subroutine calls provide the correct number and types of arguments, !" labels on the arms of a case statement are distinct constants, !" every function contains at least one statement that specifies a return value. Code Generation Phase: The code generated depends upon the architecture of the target machine. A knowledge of the instructions and addressing modes in target computer is necessary for code generation process. One of the important aspects of code generation is the efficient initialization of machine resources. A number of assumptions may be made such as: a) instruction types in target machines mukeshtekwani@hotmail.com Page 3 of 6
  • 4. Phases of the Compiler Prof. Mukesh N. Tekwani b) commutative property of operators in an expression c) proper usage of syntax for syntax directed translation. Code Optimization Phase: Optimization improves programs by making them smaller or faster or both. The goal of code optimization is to translate a program into a new version that computes the same result more efficiently – by taking less time, memory, and other system resources. For example, the C compiler “Turbo C” permits the programmer to optimize code for speed or for size. Code optimization is achieved in 2 ways: a) rearranging computations in a program to make them execute more efficiently, b) eliminating redundancies in a program. Code optimization should not change the meaning of the program. Code optimization tries to improve the program; the underlying algorithm is not affected. Thus, code optimization cannot replace an inefficient algorithm with an algorithm which is more efficient. Code optimization also cannot fully utilize the instruction set of a particular architecture. Thus, code optimization is independent of the target machine and the PL. An optimizing compiler is shown below. Note the presence of the optimization phase. Source Program Front End Optimization Phase Back End Target Program Optimizing Transformations: It is a rule for rewriting a segment of a program to improve its execution efficiency without affecting its meaning. The two types of optimizing transformations are: a) local transformations (applied over small segments of a program) b) global transformations (applied over larger segments consisting of loops or function bodies). Some of the optimizing transformations used by compilers are: i. ii. Compile time evaluation: Certain actions specified ina program can be performed during the compilation stage itself. This eliminates the need to perform them during execution stage. The main optimization of this type is constant folding; if all the operands in an expression are constant, the operation can be performed at compile time itself. The result of the operation, itself a constant, then replaces the original expression. E.g., an assignment of the type a:= 2.718/2 can be replaced by a:= 1.354. this eliminates an operation of division. Dead Code elimination: Page 4 of 6 mukeshtekwani@hotmail.com
  • 5. Prof. Mukesh N. Tekwani Phases of the Compiler Code which can be omitted from a program without affecting its results is called dead code. If a variable is assigned a value which is never used subsequently in the program, then that statement is a dead code. E.g., j = 30; Turbo C can point out such instances by way of a warning message. iii. Elimination of common sub-expressions: Expressions which yield the same value are called common sub-expressions or equivalent expressions. Consider the following code segments: a:= b * c; t := b*c; : a := t; : : x := b * c + 3.5; x := t + 3.5; Here the two occurrences of b*c were eliminated by using a variable t. iv. Frequency Reduction: Execution time of a program can be reduced by moving code from a part of a program which is executed very frequently to another part of the program which is executed fewer times. E.g., the transformation of loop optimization involves moving loop invariant code out of a loop. v. Strength reduction: This optimization technique reduces operation with a more efficient operation or a series of operations that yield the same result in fewer machine clock cycles. For example, multiplication by a power of two is replaced by a left shift, which executes faster on most machines. a = b * 4; becomes a = b + b + b + b; or a = b << 2; Similarly, division by powers of two are expensive operations and these can be replaced with right shift. c = d / 2; becomes c = d >> 1; Local and Global optimization: a) Local transformations are applied over small segments of a program. This is a preparatory phase for global optimization. It can be performed by the front end while converting a source code into the IR. Local optimization provides limited benefits at a low cost. The scope of this type of optimization is a basic block which is a sequential set of instructions. Loop optimization cannot be performed by local optimization. b) Global transformations are applied over larger segments consisting of loops or function bodies. It requires more analysis efforts to determine the feasibility of an optimization. The techniques of control flow analysis and data flow analysis are used to achieve global optimization. mukeshtekwani@hotmail.com Page 5 of 6
  • 6. Phases of the Compiler Prof. Mukesh N. Tekwani Passes of a compiler: Several phases of compilation are usually grouped into one pass consisting of reading an input file and writing an output file. For example, the following stages can be grouped into one pass: i. Lexical analysis, ii. Syntax analysis, iii. Semantic analysis, and iv. Intermediate code generation It is desirable to have relatively few passes, since it takes time to read and write intermediate files. On the other hand, if we group several phases into one pass, we may be forced to keep the entire program in memory. Difference between a phase and a pass of a compilation Compilation proceeds through a set of well-defined phases; these are the lexical analysis, syntax analysis, semantic analysis, intermediate code generation, machine independent code optimization, code generation, and machine dependent code generation. Each phase discovers information of use to later phases, or transforms the program into a form that is more useful to the subsequent phases. A pass is a phase or a set of phases that is serialized with respect to the rest of the compilation. A pass does not start until the previous phases have been completed and it finishes before any subsequent phases start. REVIEW QUESTIONS 1. List the principal phases of compilation and describe the work performed by each phase. 2. Explain the syntax analysis phase. What operations are carried out in this phase? 3. Explain the semantic analysis phase. What operations are carried out in this phase? 4. What is the difference between a phase and a pass of a compilation? 5. What is the purpose of the compiler’s symbol table? 6. What is the difference between static and dynamic semantics? 7. What is meant by the term “compiler pass” ? How does it differ from a phase of compilation? ##### Page 6 of 6 mukeshtekwani@hotmail.com