Module 4
Module 4
com/
MODULE 4
Syntax directed translation –
Syntax directed definitions, S-attributed definitions, L-attributed definitions, Bottom-up evaluation
of S-attributed definitions.
Run-Time Environments - Source Language issues, Storage organization, Storage-allocation
strategies.
Intermediate Code Generation - Intermediate languages, Graphical representations, Three-Address
code, Quadruples,Triples
------------------------------------------------------------------------------------------------------------------------
m
and performs certain checks based on this information.
It logically follows the parsing phase, in which the parse tree is generated, and logically
co
precedes the code generation phase, in which (intermediate/target) code is generated. (In a
compiler implementation, it may be possible to fold different phases into one pass.)
s.
Typical examples of semantic information that is added and checked is typing information
te
( type checking ) and the binding of variables and function names to their definitions
no
( object binding ).
Sometimes also some early code optimization is done in this phase. For this phase the
la
compiler usually maintains symbol tables in which it stores what each symbol (variable
names, function names, etc.) refers to.
ra
2. Type checking : The process of verifying and enforcing the constraints of types is called type checking.
This may occur either at compile-time (a static check) or run-time (` dynamic check).
Static type checking is a primary task of the semantic analysis carried out by a compiler.
If type rules are enforced strongly (that is, generally allowing only those automatic type conversions
which do not lose information), the process is called strongly typed, if not, weakly typed.
3. Uniqueness checking : Whether a variable name is unique or not, in the its scope.
4. Type coercion : If some kind of mixing of types is allowed. Done in languages which are not
strongly typed. This can be done dynamically as well as statically.
5. Name Checks : Check whether any variable has a name which is not allowed. Ex. Name is same
as an identifier( Ex. int in java).
A parser has its own limitations in catching program errors related to semantics, something
that is deeper than syntax analysis.
Typical features of semantic analysis cannot be modeled using context free grammar
formalism.
If one tries to incorporate those features in the definition of a language then that language
m
doesn't remain context free anymore.
co
These are a couple of examples which tell us that typically what a compiler has to do
beyond syntax analysis.
s.
An identifier x can be declared in two separate functions in the program, once of the type
int and then of the type char. Hence the same identifier will have to be bound to these two
te
different properties in the two different contexts.
no
Semantic Errors
We have mentioned some of the semantics errors that the semantic analyzer is expected to
la
recognize:
ra
Type mismatch
Undeclared variable
ke
m
co
Syntax Directed Definitions
Syntax Directed Definitions are a generalization of context-free grammars in which:
s.
1. Grammar symbols have an associated set of Attributes;
te
2. Productions are associated with Semantic Rules for computing the values of attributes.
• Such formalism generates Annotated Parse-Trees where each node of the tree is a record with a
no
field for each attribute (e.g., X.a indicates the attribute a of the grammar symbol X).
The value of an attribute of a grammar symbol at a given parse-tree node is defined by a
la
ATTRIBUTE GRAMMAR
ke
Attributes are properties associated with grammar symbols. Attributes can be numbers,
strings, memory locations, datatypes, etc.
Attribute grammar is a special form of context-free grammar where some additional
information (attributes) are appended to one or more of its non-terminals in order to
provide context-sensitive information.
Semantic attributes may be assigned to their values from their domain at the time of parsing
and evaluated at the time of assignment or conditions.
Based on the way the attributes get their values, they can be broadly divided into two
categories : synthesized attributes and inherited attributes
ATTRIBUTES
Synthesized Inherited
m
1. Synthesized Attributes: These are those attributes which get their values from their
children nodes i.e. value of synthesized attribute at node is computed from the values of
co
attributes at children nodes in parse tree.
To illustrate, assume the following production:
s.
EXAMPLE : S -> ABC
te
S.a= A.a,B.a,C.a
no
If S is taking values from its child nodes (A,B,C), then it is said to be a synthesized attribute, as
the values of ABC are synthesized to S.
la
Write the SDD using apppropriate semantic rules for each production in given grammar.
The annotated parse tree is generated and attribute values are computed in bottom up
ke
manner.
The value obtained at root node is the final output.
Consider the following grammar:
S --> E
E --> E1 + T
E --> T
T --> T1 * F
T --> F
F --> digit
Let us assume an input string 4 * 5 + 6 for computing synthesized attributes. The annotated parse
tree for the input string is
S
m
co
s.
te
no
la
ra
ke
For computation of attributes we start from leftmost bottom node. The rule F –> digit is
used to reduce digit to F and the value of digit is obtained from lexical analyzer which
becomes value of F i.e. from semantic action [Link] = [Link].
Hence, [Link] = 4 and since T is parent node of F so, we get [Link] = 4 from semantic action
[Link] = [Link].
Then, for T –> T1 * F production, the corresponding semantic action is [Link] = [Link] *
[Link] . Hence, [Link] = 4 * 5 = 20
Similarly, combination of [Link] + [Link] becomes [Link] i.e. [Link] = [Link] + [Link] = 26.
Then, the production S –> E is applied to reduce [Link] = 26 and semantic action associated
with it prints the result [Link] . Hence, the output will be 26.
EXAMPLE:
B can get values from A, C and D. C can take values from A, B, and D. Likewise, D cantake
m
values from A, B, and C.
co
Computation of Inherited Attributes
Construct the SDD using semantic actions.
s.
The annotated parse tree is generated and attribute values are computed in top down
te
manner.
Consider the following grammar:
no
D --> T L
la
T --> int
ra
T --> float
T --> double
ke
L --> L1, id
L --> id
D TL [Link]==[Link]
m
co
s.
The value of L nodes is obtained from [Link] (sibling) which is basically lexical value
te
obtained as int, float or double.
no
Then L node gives type of identifiers a and c. The computation of type is done in top
down manner or preorder traversal.
la
Using function Enter_type the type of identifiers a and c is inserted in symbol table at
ra
corresponding [Link].
1. Dependency Graphs
Implementing a Syntax Directed Definition consists primarily in finding an order for the
evaluation of attributes
Each attribute value must be available when a computation is performed.
Dependency Graphs are the most general technique used to evaluate syntax directed
definitions with both synthesized and inherited attributes.
Annotated parse tree shows the values of attributes, dependency graph helps to determine
how those values are computed
The interdependencies among the attributes of the various nodes of a parse-tree can be
depicted by a directed graph called a dependency graph.
7
m
co
s.
te
no
la
ra
ke
m
evaluate SDD on this parse tree.
co
TYPES OF SDT’S s.
1. S –attributed definition
te
2. L –attributed definition
no
S-attributed definition
la
EXAMPLE:
{ A.a=B.a,C.a}
S-attributed SDTs are evaluated in bottom-up parsing, as the values of the parent nodes
depend upon the values of the child nodes.
Semantic actions are placed in rightmost place of RHS.
}.
Note: (Also write SDD for desk calculator as example).
L –attributed definition
L stands for one parse from left to right.
m
Ie, If an SDT uses both synthesized attributes and inherited attributes with a restriction
that inherited attribute can inherit values from parent and left siblings only, it is called as
co
L-attributed SDT.
EXAMPLE:
A {B.a=A.a, C.a=B.a}
s.
te
C.a=D.a is not possible
no
B{ }C
ke
BC{ }
Note: (Also write SDD for declaration statement as example)
If an attribute is S attributed , it is also L attributed.
Evaluation of L-attributed SDD
10
m
co
s.
SDD for desk calculator/SDD for evaluation of expressions
te
no
la
ra
ke
Evaluate the expression 3*5+4n using the above SDD both in bottom up and top
down approach
Solution: Bottom up evaluation for this expression is shown below
In both case first we need to draw the parse tree.
11
m
co
s.
te
Solution: Top down approach:
no
12
m
co
s.
te
no
la
ra
Workout problems
Traversal
visit(m)
13
m
co
s.
te
no
la
ra
ke
14
m
co
s.
te
no
la
ra
15
m
co
s.
te
no
la
ra
ke
16
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.
m
identifier is procedure name, and statement is the procedure body.
o
For example, the following definition of procedure named readarray
s .c
te
no
la
ra
When a procedure name appears with in an executable statement, the procedure is said to be
called at that point.
ke
Activation Tree
Each execution of 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.
17
quicksort(int m, int n)
{
int i= partition(m,n);
quicksort(m,i-1);
m
quicksort(i+1,n);
}
o
s .c
te
no
la
ra
ke
First main function as root then main calls readarray and quicksort.
18
corresponds to the depth first traversal of activation tree which starts at the root.
Control Stack
m
Control stack or runtime stack is used to keep track of the live procedure activations
o
i.e the procedures whose execution have not been completed.
.c
A procedure name is pushed on to the stack when it is called (activation begins) and
it is popped when it returns (activation ends).
s
te
Information needed by a single execution of a procedure is managed using an
activation record.
no
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 on as the
la
Then the contents of the control stack are related to paths to the root of the activation
tree. When node n is at the top of the control stack, the stack contains the nodes along
ke
Consider the above activation tree, when quicksort(4,4) gets executed, the contents of
control stack were main() quicksort(1,10) quicksort(1,4), quicksort(4,4)
The term environment refers to a function that maps a name to a storage location.
The term state refers to a function that maps a storage location to the value held there.
o m
.c
When an environment associates storage location s with a name x, we say that x is
bounds to s. This association is referred to as a binding of x.
s
STORAGE ORGANIZATION
te
The executing target program runs in its own logical address space in which each
no
compiler, operating system and target machine. The operating system maps the
ra
logical address into physical addresses, which are usually spread through memory.
Code area: used to store the generated executable instructions, memory locations for
the code are determined at compile time
Static Data Area: Is the locations of data that can be determined at compile time
20
Activation Records
It is LIFO structure used to hold information about each instantiation.
m
Procedure calls and returns are usually managed by a run time stack called control
stack.
o
Each live activation has an activation record on control stack, with the root of
.c
the activation tree at the bottom, the latter activation has its record at the top of the
s
stack
te
The contents of the activation record vary with the language being implemented.
no
The purpose of the fields of an activation record is as follows, starting from the
la
2. The field for local data holds data that is local to an execution of a procedure.
3. The field for saved machine status holds information about the state of the machine
just before the procedure is called. This information includes the values of the
program counter and machine registers that have to be restored when control returns
from the procedure.
4. The optional access link is used to refer to nonlocal data held in other activation
records.
5. The optional control /ink paints to the activation record of the caller
6. The field for actual parameters is used by the calling procedure to supply
parameters to the called procedure.
7. The field for the returned value is used by the called procedure to return a value to
the calling procedure, Again, in practice this value is often returned in a register
for greater efficiency.
21
Returned value
Actual parameters
Local data
temporaries
m
STORAGE ALLOCATION STRATEGIES
o
.c
The different storage allocation strategies are:
s
Static allocation - lays out storage for all data objects at compile time
te
Stack allocation - manages the run-time storage as a stack.
no
Heap allocation - allocates and deallocates storage as needed at run time from a data area
known as heap.
la
Static Allocation
Since the bindings do not change at runtime, every time a procedure activated, its run-
time, names bounded to the same storage location.
From the type of a name, the compiler decides amount of storage for the name and
decides where the activation records go. At compile time, we can fill in the address
at which the target code can find the data it operates on.
Stack Allocation
All compilers for languages that use procedures, functions or methods as units of user
functions define actions manage at least part of their runtime memory as a stack run-
time stack.
22
Calling Sequences
A return sequence is similar to code to restore the state of a machine so the calling
procedure can continue its execution after the call.
The code is calling sequence of often divided between the calling procedure (caller)
and a procedure is calls (callee)(callee).
m
When designing calling sequences and the layout of activation record, the following
principles are helpful:
o
5. Value communicated between caller and callee generally placed at the caller
6. Fixed length items generally placed in the middle. Such items typically
te
include the control link, the access link, and the machine status field.
7. Items whose size may not be known early enough placed at the end of the
no
activation record.
8. We must locate the top of the stack pointer judiciously. A common approach
la
is to have it point to the end of fixed length fields in the activation is to have
ra
it point to fix the end of fixed length fields in the activation record. Fixed
length data can then be accessed by fixed offsets, known to the intermediate
ke
23
m
1. The callee places the return value next to the parameters.
2. Using the information in the machine status field, the callee restores top_sp
o
and other registers, and then branches to the return address that the caller
placed in the status field.
.c
3. Although top_sp has been decremented, the caller knows where the return
s
value is, relative to the current value of top_sp; the caller, therefore, may
te
of space for objects the sizesof which are not known at compile time, but which
are local to a procedure and thus may be allocated on the stack.
ra
In modern languages, objects whose size cannot be determined at compile time are
ke
We avoid the expense of garbage collecting their space. Note that the stack can be
used only for an object if it is local to a procedure and becomes inaccessible when the
procedure returns.
24
o m
s .c
te
no
dangling reference occurs when there is a reference to storage that has been
allocated.
ra
Heap Allocation
Pieces may be deallocated in any order, so over the time the heap will consist
25
o m
.c
Records for live activations need not be adjacent in heap
s
The record for an activation of procedure r is retained when the activation ends.
te
Therefore, the record for the new activation q(1 , 9) cannot follow that for s
physically.
no
If the retained activation record for r is deallocated, there will be free space in the
heap between the activation records for s and q.
INTERMEDIATE CODE GENERATION (ICG)
la
2 important things:
It shouldn’t be difficult to produce the target program from the intermediate code.
26
A source program can be translated directly into the target language, but some benefits
of using intermediate form are:
Retargeting is facilitated: a compiler for a different machine can be created by
attaching a Back-end(which generate Target Code) for the new machine to an
existing Front-end (which generate Intermediate Code).
A machine Independent Code-Optimizer can be applied to the Intermediate
Representation.
o m
Logical Structure Of A Compiler Front Ends .c
te
no
la
ra
INTERMEDIATE LANGUAGES
Syntax Tree
DAG (Direct Acyclic Graph)
Postfix Notation
3 Address Code
GRAPHICAL REPRESENTATION
Includes both
Syntax Tree
DAG (Direct Acyclic Graph)
Syntax Tree Or Abstract Syntax Tree(AST)
Graphical Intermediate Representation
Syntax Tree depicts the hierarchical structure of a source program.
27
EXAMPLE
Parse tree and syntax tree for 3 * 5 + 4 as follows.
E→E-T
E + T * 4
E→ T
m
T→T * F
T F 3 5
o
T→F
F→ digit T * F
s .c digit
te
F digit 4
no
digit 5
la
ra
3
ke
28
Eg : No parenthesis
o m
Constructing Syntax Tree For Expression
s .c
Each node in a syntax tree can be implemented in arecord with several fields.
te
In the node of an operator, one field contains operator and remaining field contains
no
When used for translation, the nodes in a syntax tree may contain addition of fields
la
29
P1 = mkleaf(id,entry a)
P2 = mkleaf(num, 4)
P4 = mkleaf(id,entry c)
P5 = mknode(+, P3, P4)
o m
s .c
Syntax directed definition
te
definition.
The two binary operators + and * are examples of the full operator set in a typical
ra
language. Operator associates and precedences are the usual ones, even though they
have not been put into the grammar. This definition constructs the tree from the input
ke
a:=b* -c + b* -c
30
A symbol-table entry can be found from an attribute [Link], representing the lexeme
associated with that occurrence of id.
If the lexical analyser holds all lexemes in a single array of characters, then attribute
name might be the index of the first character of the lexeme.
Two representations of the syntax tree are as follows.
o m
s .c
te
no
la
ra
ke
In (a), each node is represented as a record with a field for its operator and additional
fields for pointers to its children.
In Fig (b), nodes are allocated from an array of records and the index or position of
the node serves as the pointer to the node.
All the nodes in the syntax tree can be visited by following winters, starting from the
root at position 10.
a=b*-c + b*-c
o m
Postfix Notation
s .c
te
Linearized representation of syntax tree
In postfix notation, each operator appears immediately after its last
no
the string
ra
EXAMPLE
Source String : a := b * -c + b * -c
ke
2. If E is an expression of the form E1 op E2 then postfix notation for E is E1’ E2’ op, here
E1’ and E2’ are the postfix notations for E1and E2, respectively
3. If E is an expression of the form (E), then the postfix notation for E is the same as the
postfix notation for E.
32
a = b op c
where,
a, b, c are the operands that can be names, constants or compiler generated temporaries.
op represents operator, such as fixed or floating point arithmetic operator or a logical operator
on Boolean valued data. Thus a source language expression like x + y * z might be translated
m
into a sequence
t1 := y*z
o
t2 := x+t1
s .c
where, t1 and t2 are compiler generated temporary names.
te
Advantages Of Three Address Code
no
The use of names for the intermediate values computed by a program allows three- address
code to be easily rearranged - unlike postfix notation.
ra
33
1. Assignment statements
3. Copy statements
4. Unconditional jump
m
goto L The three-address statement with label L is the next to be executed
o
5. Conditional jump
.c
if x relop y goto L This instruction applies a relational operator ( <, =, =, etc,) to x and y,
and executes the statement with label L next if x stands in relation relop to y. If not, the
s
three-address statement following if x relop y goto L is executed next, as in the usual
te
sequence.
no
param x and call p, n for procedure calls and return y, where y representing a
la
returned value is optional. Their typical use is as the sequence of three-address statements
ra
param x1
param x2
……….
ke
param xn
call p,n
generated as part of the call procedure p( xl , x2, . . . , xn ) . The integer n indicating
the number of actual-parameters in ''call p , n" is not redundant because calls can be
nested.
7. Indexed Assignments
34
o m
s .c
te
no
la
ra
35
The function newlabel returns a new label every time is called. We assume that a
nonzero expression represents true; that is when the value of E becomes zero, control
laves the while statement
m
Implementation Of Three-Address Statements
o
statements can be implemented as records with fields for the operator and the operands. Three
.c
such, representations are
s
Quadruples
te
Triples
Indirect triples
no
QUADRUPLES
la
A quadruple is a record structure with four fields, which are op, ag1, arg2 and result
The op field contains an internal code for the operator. The three address statement
ra
The contents of arg1, arg2, and result are normally pointers to the symbol table entries
for the names represented by these fields. If so temporary names must be entered into
the symbol table as they are created.
EXAMPLE 1
For the first construct the three address code for the expression
t1 = e ^ f
t2 = b * c
t3 = t2 / t1
t4 = b * a
t5 = a + t3
t6 = t5 + t4
36
A statement like param t1 is represented by placing param in the operator field and t1 in
the arg1 field. Neither arg2 not result field is used
Unconditional & Conditional jump statements are represented by placing the target in the
result field.
m
TRIPLES
o
In triples representation, the use of temporary variables is avoided & instead reference
to instructions are made .c
So three address statements can be represented by records with only there fields OP,
s
arg1 & arg2.
te
Since, there fields are used this intermediated code formal is known as triples
no
Advantages
No need to use temporary variable which saves memory as well as time
la
Disadvantages
ra
EXAMPLE 1
a+b*c|e^f +b*a
t1 = e ^ f
t2 = b * c
t3 = t2 / t1
t4 = b * a
t5 = a + t3
t6 = t5 + t4
37
EXAMPLE 2
A ternary operation like x[i] : = y requires two entries in the triple structure while x : = y[i]
is naturally represented as two operations.
o m
s .c
te
x[i] := y x := y[i]
no
INDIRECT TRIPLES
la
It uses an additional instruction array to led the pointer to the triples in the desired
order.
ke
38
This location will be entered into symbol table entry of that data.
Using the quadruple notation, a three address statement containing a temporary can
immediately access the location for that temporary via symbol table.
This is achieved because using quadruple notation the symbol table interposes high
degree of indirection between computation of a value and its use.
m
With quadruple notation, if we move a statement computing x, the statement using x
requires no change.
o
But with triples, moving a statement that defines a temporary value requires us to change
.c
all references to that statement in arg1 and arg2 arrays. This makes triples difficult to use
s
in optimizing compiler
te
Quadruples and indirect triples requires same amount of space for storage (normal
ra
case).
But if same temporary value is used more than once indirect triples can save some space.
ke
This is bcz, 2 or more entries in statement array can point to the same line of op-arg1-
arg2 structure.
Indirect Triples
easier for optimization
space efficiency
39
t1 = uniminus ct2 = b* t1
t3 = uniminus c t4 = b*
t3
t5 = t2 + t4Q = t5
QUADRUPLES
Location OP arg1 arg2 result
(0) uniminus c t1
(1) * b t1 t2
m
(3) uniminus c t3
(4) * b t3 t4
co
(5) + t2 t4 t5
(6) = t5 a
s.
TRIPLES
te
Location OP arg1 arg2
no
(1) uniminus c
(2) * b (1)
(3) uniminus c
la
(4) * b (3)
(5) + (2) (4)
ra
(6) = a (5)
ke
INDIRECT TRIPLES
********