Documente Academic
Documente Profesional
Documente Cultură
such as DO or IF,
such as x or num,
such as <, =, or, +, and
such as parentheses or commas.
The output of the lexical analysis is a stream of tokens, which is passed to the
next phase; the syntax analyzer or parser.
Syntax Analyzer: It groups tokens together into syntactic structure. For
example, the three tokens representing A + B might be grouped into a syntactic structure
called as expression. Expressions might further be combined to form statements. Often
the syntactic structures can be regarded as a tree whose leaves are the tokens. The interior
nodes of the tree represent strings of token that logically belong together. Fig. 1 shows
the syntax tree for READ statement in PASCAL
(read)
Compilers
185
(id - list)
READ
id
{value}
GRAMMARS
A grammar for a programming language is a formal description of the syntax of
programs and individual statements written in the language. The grammar does not
describe the semantics or memory of the various statements. To differentiate between
syntax and semantics consider the following example:
VAR X, Y : REAL
I
: INTEGER
X:=I+Y;
Fig .3
VAR
I, J, K : INTEGER
I:= J+K ;
System Software
186
READ, WRITE
2. A set of terminals. The character strings enclosed between the angle brackets
(<, >) are called terminal symbols. These are the names of the constructs
defined in the grammar.
3. A set of productions where each production consists of a non-terminal called
the left side of the production, as "is defined to be" (:: = ), and a sequence of
token and/or non-terminal, called the right side of the product.
Example: < reads > : : = READ <id - list >.
4. A designation of one of the non-terminals as the start symbol.
This rule offers two possibilities separated by the symbol, for the syntax of an
< id - list > may consist simply of a token id (the notation id denotes an identifier that is
recognized by the scanner). The second syntax.
Example:
ALPHA
ALPHA, BETA
ALPHA is an < id - list > that consist of another < id - list > ALPHA, followed
by a comma, followed by an id BETA.
Tree: It is also called parse tree or syntax tree. It is convenient to display the
analysis of a source statement in terms of a grammar as a tree.
Example:
READ (VALUE)
GRAMMAR: (read) : : = READ ( < id -list>)
Example: Assignment statement:
SUM : = 0 ;
SUM : = + VALUE ;
SUM : = - VALUE ;
Compilers
187
::
::
::
::
=
=
=
=
id
:=
{variance }
<exp >
Fig. 4 (a)
Dir
X
Fig. 4 (b)
factor
|
id
int
Id
Fig.4 (c)
(< exp > )
Fig. 4 (d)
System Software
188
::=
::=
::=
::=
13.
14.
15.
16.
17.
::=
::=
::=
::=
::=
BEGIN
(id - list)
(id - list ) ;
INTEGER
id
{VARIANCE} < stmt - list > ;
(id - list ) ,
END
id
(MEAN)
id
<VALUE > < stmt - list >
; <stmt >
id
{VARIANCE}
id
id
:=
<MEAN>
{VARIANCE} < exp >
< assign >
(id - list ) ,
id
{SUM}
{SUMSQ}
id
{I}
<stmt >
id
{SMSQ} < stmt >
<term>
<term> * <factor>
|
|
< assign > id
:=
<exp> |
|
<factor>
id
|
|
<term> Div <factor>
|
[MEAN]
|
|
|
term
|
>term> Div <factor > id
id
: < exp >
|
factor
{MEAN}
|
factor
< term >
|
|
int
< factor > { 0}
|
int {0}
|
id
{SUM}
Next
Page
int
{100} <factor>
|
id
{SUMSQ}
int
{100}
Compilers
189
|
Id
{I}
Do
: = <exp> To <exp>
BEGIN <stm - list>
END
|
|
< term > <term>
|
|
<factor> <factor>
<stmt - list > ;
< stmt >
|
|
|
int
int
{I}
{100}
<symt - list> ;
<stmt>
<assign >
|
|
< stmy >
<assign >
|
id
:=
<emp>
< read >
(SUMSQ
id
: = <exp>
{SUM}
READ
( < id - list > )
< exp >
+ < term >
< exp >
+ < term >
id
|
|
|
{VALUE?
<term >
< factor > < term > <term> * <factor>
|
|
|
|
|
< factor >.
id
<factor > <factor > id
|
{ value}
|
|
{value}
id
id
id
{SUM}
{SUMSQ} {value}
id
{BETA}
id
{GAMMA}
System Software
190
2 (a) Draw Parse tree, according to the grammar in fig. 5 for the following < exp > S :
(a) ALPHA + BETA
term
{BETA}
Div
{DELTA}
id
{ALPHA}
Compilers
3.
191
Suppose the rules of the grammar for < exp > and < term > is as follows:
< exp > :: = < term > | < exp > * < term> | < exp> Div < term >
< term > :: = <factor> | < term > + < factor > | < term > - < factor >
Draw the parse trees for the following:
(a) A1 + B1 (b) A1 - B1 * G1 (c) A1 + DIV (B1 + G1) - D1
< exp >
|
term
(a) A1 + B1
< term >
factor
id
{A1}
(b) A1 - B1 * G1
teerm
factor
term
factor
|
id
{G1}
id
factor
{A1}
id {B1}
(c) A1 DIV (B1 + A1) - D1
< exp >
DIV
id
{A1}
id
{D1}
System Software
192
{G1}
id
{B1}
LEXICAL ANALYSIS
Lexical Analysis involves scanning the program to be compiled. Scanners are
designed to recognize keywords, operations, identifiers, integer, floating point numbers,
character strings and other items that are written as part of the source program. Items are
recognized directly as single tokens. These tokens could be defined as a part of the
grammar.
Example: <ident> : : = <letter> | <ident> <letter> | <ident> <digit>
<letter> : : = A | B | C | . . . | Z
<digit> : : = 0 | 1 | 2 | . . . | 9
In a such a case the scanner world recognize as tokens the single characters A, B,
. . . Z,, 0, 1, . . . 9. The parser could interpret a sequence of such characters as the
language construct < ident >. Scanners can perform this function more efficiently. There
can be significant saving in compilation time since large part of the source program
consists of multiple-character identifiers. It is also possible to restrict the length of
identifiers in a scanner than in a passing notion. The scanner generally recognizes both
single and multiple character tokens directly.
The scanner output consists of sequence of tokens. This token can be considered
to have a fixed length code. The fig. 7 gives a list of integer code for each token for the
program in fig. 5 in such a type of coding scheme, the PROGRAM is represented by
the integer value 1, VAR has the integer value 2 and so on.
Token
Code
Program
1
VAR
2
BEGIN
3
END
4
END
5
INTEGER
6
FOR
7
Token
Token
READ
:=
WRITE
+
To
-
Do
K
;
DIV
:
(
,
)
Token
Code
:=
15
+
16
17
K
18
DIV
17
(
20
)
21
Token
Code
Id
22
Int
23
Fig. 7 Token Coding Scheme
Compilers
193
Scanners should look into the rules for the formation of tokens.
System Software
194
Each arrow is labeled with a character or set of characters that can be specified for
transition to occur. The starting state has an arrow entering it that is not connected to
anything else.
1
State
Final State
Fig. 8
Transition
A-Z
3
2
2
1
Fig. 9
SYNTACTIC ANALYSIS
During syntactic analysis, the source programs are recognized as language
constructs described by the grammar being used. Parse tree uses the above process for
translation of statements, Parsing techniques are divided into two general classes:
-- Bottom up and -- Top down.
Top down methods begin with the rule of the grammar that specifies the goal of
the analysis ( i.e., the root of the tree), and attempt to construct the tree so that the
terminal nodes match the statement being analyzed.
Bottom up methods begin with the terminal nodes of the tree and attempt to
combine these into successively high - level nodes until the root is reached.
OPERATOR PRECEDENCE PARSING
The bottom up parsing technique considered is called the operator precedence
method. This method is loaded on examining pairs of consecutive operators in the source
program and making decisions about which operation should be performed first.
Compilers
195
Example: A + B * C - D
(1)
process.
PROGRAM
VAR
BEGIN
END
INTEGER
FOR
READ
WRITE
TO
DO
;
:
DIV
)
Id
Int
*
DIV
)
(
<
,
:=
+
-
TO
DO
:
:
,
:=
+
-
(
id
Int
(2)
INTEGER
FOR
REAS
WRITE
VAR
BEGIN
END
END
A+B*C -D
System Software
196
before considering the surrounding terms. The first step in constructing an operatorprecedence parser is to determine the precedence relations between the operators of the
grammar. Operator is taken to mean any terminal symbol (i.e., any token). We also have
precedence relations involving tokens such as BEGIN, READ, id and ( . For the
grammar in fig. 5, the precedence relations is given in the fig. 11.
Example: PROGRAM
Begin FOR ; BEGIN has lower precedence over FOR. There are some values
which do not follows precedence relations for comparisons.
; END
Example:
END ;
and
i.e., when ; is followed by END, the ' ; ' has higher precedence and when END
is followed by ; the END has higher precedence.
In all the statements where precedence relation does not exist in the table, two
tokens cannot appear together in any legal statement. If such combination occurs during
parsing it should be recognized as error.
Let us consider some operator precedence for the grammar in fig. 5.
Example:
Pascal Statement:
BEGIN
READ (VALUE);
These Pascal statements scanned from left to right, one token at a time. For each
pair of operators, the precedence relation between them is determined. Fig. 12(a) shows
the parser that has identified the portion of the statement delimited by the precedence
relations and to be interpreted in terms of the grammar.
(a) . . . BEGIN READ ( id )
( < N1 > ) ;
READ
< N2 >
<N1 >
id
(VALUE)
Fig. 12
According to the grammar id may be considered as < factor > . (rule 12),
<program > (rule 9) or a < id-list > (rule 6). In operator precedence phase, it is not
necessary to indicate which non-terminal symbol is being recognized. It is interpreted as
non-terminal < N1 >. Hence the new version is shown in fig. 12(b).
Compilers
197
<id 2>
<N1>
{SUMSQ}
(iv) . . . . id 1 : = <N3> - id 3 *
<N1>
DIV
id2
{SUMSQ}
int
{100}
<N4>
id 3
{MEAN}
<N5>
id 4
{MEAN}
<id 2>
{SUMSQ}
<N2>
int
{100}
<N2>
<N3>
v) . . . . id 1 : = <N3> - <N4> * id 4
<N1>
<N6>
<N4>
id 3
{MEAN}
<N5>
id 4
{MEAN}
System Software
198
(viii) . . . id : = <N7>
(ix)
<N7>
<N3>
<N6>
. . . <N8>
<N8>
<N7>
<N3>
id 1
{VARIANCE}
:=
<N1>
<N6>
<N2>
<N4>
DIV
id 2
{SUMSQ}
<N5>
*
int id 3
id 4
{100}
{MEAN} {MEAN}
BEGIN
READ ( id ) . . .
Stack
Shift
2. . . . BEGIN
READ ( id )
Shift
BEGIN
3. . . . BEGIN
READ ( id ) . . .
Shift
READ
BEGIN
Compilers
199
4. . . BEGIN
READ ( id ) . . .
(
READ
Shift
BEGIN
5. . . . BEGIN
READ ( id ) . . .
id
(
READ
BEGIN
Shift
6. . . . BEGIN
READ ( id ) . . .
Shift
.
< id-list >
(
READ
BEGIN
Explanation
1. The parser shift (pushing the current token onto the stack) when it encounters
BEGIN
2 to 4. The shift pushes the next three tokens onto the stack.
5. The reduce action is invoked. The reduce converts the token on the top of the
stack to a non-terminal symbol from the grammar.
6. The shift pushes onto the stack, to be reduced later as part of the READ
statement.
Note: Shift roughly corresponds to the action taken by an operator precedence
parses when it encounters the relation and . Reduce roughly corresponds to
the action taken when an operator precedence parser encounters the relation .
RECURSIVE DESCENT PARSING
System Software
200
Example: The procedure for < id - list >, corresponding to rule 6 would be unable
to decide between its alternatives since id and < id-list > can begin with id. <id-list > : : =
id | < id-list >, id
If the procedure somehow decided to try the second alternative <id-list>, it would
immediately call itself recursively to find an <id-list>. This causes unending chain. Topdown parsers cannot be directly used with a grammar that contains this kind of immediate
left recursion.
Similarly the problem occurs for rules 3, 7, 10 and 11. Hence the fig. 13 shows
the rules 3, 6, 7, 10 and 11 modification.
3
6
7
10
11
Fig. 13
Fig. 14 illustrates a recursive-descent parse of the READ statement: READ (VALUE);
The modified grammar is considered in the procedure for the non-terminal <read > and < id-list >.
It is assumed that TOKEN contains the type of the next input token.
PROCEDURE READ
BEGIN
ROUND : = FALSE
If TOKEN + 8 { read } THEN
BEGIN
advance to next token
IF TOKEN + 20 { ( } THEN
BEGIN
advance to next token
IF IDLIST returns success THEN
IF token = 21 { ) } THEN
BEGIN
FOUND : = TRUE
advance to next token
END { if ) }
END { if READ }
IF FOUND = TRUE THEN
return success
else failure
end (READ)
Fig. 14
Procedure IDLIST
begin
FOUND = FALSE
Compilers
201
In this part, the READ procedure has been invoked and has examined the
tokens READ and ' ( " from the input stream (indicated by the dashed
lines).
(ii)
In this part, the READ has called IDLIST (indicated by the solid line),
which has examined the token id.
(iii)
In this part, the IDLIST has returned to READ indicating success; READ
has then examined the input token.
Note that the sequence of procedure calls and token examinations has completely
defined the structures of the READ statement. The parser tree was constructed beginning
at the root, hence the term top-down parsing.
(i)
READ
READ
(II)
IDLIST
READ
(
(iii)
READ
READ
IDLIST
READ
(
id
{ Value }
id
{ Value
Fig. 16
System Software
202
Compilers
203
FOUND : = TRUE
while ((TOKEN = 18 { * }) or (TOKEN = 19 {DIV })
and (FOUND = TRUE) do
begin
advance to next token
if TERM returns failure then
FOUND : = FALSE
end {while}
end {if FACTOR}
if FOUND : = TRUE then
return success
else
return failure
end {TERM}
Procedure FACTOR
begin
FOUND : = FALSE
if (TOKEN = 22 { id } ) or (TOKEN = 23 {int } ) then
begin
FOUND : = TRUE
advance to next token
end { if id or int }
else
if TOKEN = 20 { ( } then
begin
advance to next token
if EXP returns success then
if TOKEN = 21 { ) } then
begin
(FOUND = TRUE)
advance to next token
end { if ) }
end {if ( }
if FOUND : = TRUE then
return success
else
return failure
end {FACTOR}
Fig. 17 Recursive-Descent Parse of an Assignment Statement
A step-by-step representation of the procedure calls and token examination is
shown in fig. 1
System Software
204
(i)
(ii)
ASSIGN
id 1
{ VARIANCE }
:=
(iii) ASSIGN
ASSIGN
id 1 : =
{ VARIANCE }
EXP
id 1
:=
{VARIANCE}
EXP
TERM
(iv)
(v)
id 1
:=
{VARIANCE}
(vi)
ASSIGN
id 1
:=
{VARIANCE}
EXP
TERM
FACTOR
id 2
FACTOR
DIV
(vii)
FACTOR
int
{SUMSQ}
EXP
TERM
id 2
{SUMSQ}
id 1
:=
{VARIANCE}
EXP
TERM
FACTOR
ASSIGN
TERM
DIV
FACTOR
id 2
{100}
{SUMSQ}
int
{100}
ASSIGN
id 1
:=
{VARIANCE}
EXP
-
TERM
FACTOR
DIV
id 2
TERM
FACTOR
FACTOR
int
{SUMSQ}
id 3
{100}
(viii)
{MEANS}
ASSIGN
EXP
id 1
:=
(VARIANCE}
TERM
FACTOR
TERM
FACTOR
FACTOR
DIV
id 2
{SUMSQ}
FACTOR
DIV
int
{100}
id 3
{MEANS}
id 4
{MEANS}
Fig. 18 Step by step Representation for Variance : = SUMSQ Div 100 - MEAN * Mean
Compilers
205
id
int
The code generation routines create segments of object code for the compiled
program. A symbolic representation is given to these codes using SIC assembler
language.
LC (Location Counter): It is a counter which is updated to reflect the next
variable address in the compiled program (exactly as it is in an assembler).
Application Process to READ Statement:
(read)
+ JSUB
WORD
WORD
XREAD
1
VALUE
)
{VALUE}
Using the rule of the grammar the parser recognizes at each step the left most
sub-string of the input that can be interpreted. In an operator precedence parse, the
recognition occurs when a sub-string of the input is reduced to some non-terminal <N i>.
In a recursive-descent parse, the recognition occurs when a procedure returns to
its caller, indicating success. Thus the parser first recognizes the id VALUE as an < id list >, and then recognizes the complete statement as a < read >.
System Software
206
The symbolic representation of the object code to be generated for the READ
statement is as shown in fig. 19(b). This code consists of a call to a statement XREAD,
which world be a part of a standard library associated with the compiler. The subroutine
any program that wants to perform a READ operation can call XREAD. XREAD is
linked together with the generated object program by a linking loader or a linkage editor.
The technique is commonly used for the compilation of statements that perform
voluntarily complex functions. The use of a subroutine avoids the repetitive generation of
large amounts of in-line code, which makes the object program smaller.
The parameter list for XREAD is defined immediately after the JSUB that calls
it. The first word is the number of variable that will be assigned values by the READ.
The following word gives the addresses of three variables.
Fig. 19(c) shows the routines that might be used to accomplish the code
generation.
1. < id - list > : : = id
add ST (id) to list
add 1 to List_count
2. < id - list > : : = < id - list >, id
add ST (id) to list
add 1 to LC List_Current
3. < read > : : = READ (< id - list >)
generate [ + JSUB XREAD ]
record external reference to XREAD
generate [WORD List - count]
for each item on list of do
begin
remove ST (ITEM) from list
generate [WORD ST (ITEM)]
end
List _count : = 0
Fig. 19 (c) Routine for READ Code Generation
The first two statements (1) and (2) correspond to alternative structure for < id list >, that is < id - list > : : = id | < id - list >, id.
In each case the token specifies ST (id) for a new identifier being called to the <
id - list > is inserted into the list used by the code-generation routine, and list-count is
updated to reflect the insertion. After the entire < id-list > has been parsed, the list
contains the token specifiers for all the identifiers that are part of the < id- list >. When
the < read > statement is recognized, the token specifiers are removed from the list and
used to generate the object code for the READ.
Code-generation Process for the Assignment Statement
Example: VARIANCE: = SUMSQ DIV 100 - MEAN * MEAN
The parser tree for this statement is shown in fig. 20. Most of the work of parsing
involves the analysis of the < exp > on the right had side of the " : = " statement.:
Compilers
207
< assign >
:=
id
{ SUMSQ }
int
{100}
id
{MEAN}
id
{MEAN}
Fig. 20
The parser first recognizes the id SUMSQ as a < factor > and < term > ; then it
recognizes the int 100 as a < factor >; then it recognizes SUNSQ DIV 100 as a < term >,
and so forth. The order in which the parts of the statements are recognized is the same as
the order in which the calculations are to be performed. A code-generation routine is
called for each portion of the statement is recognized.
Example; For a rule < term >1: : = < term > 2 * < factor > a code is to be generated.
The subscripts are used to distinguish between the two occurrences of < term > .
The code-generation routines perform all arithmetic operations using register A.
Hence the multiple < term >2 * < factor > after multiplication is available in register A.
Before multiplication one of the operand < term >2 must be located in A-register. The
results after multiplication will be left in register A. So we need to keep track of the
result left in register A by each segment of code that is generated. This is accomplished
by extending the token-specifier idea to non-terminal nodes of the parse tree.
The node specifier ST (< term1>) would be set to rA, indicating that the result of
the completion is in register A. the variable REGA is used to indicate the highest level
node of the parse tree when value is left in register A by the code generated so far.
Clearly there can be only one such node at any point in the code-generation process. If
the value corresponding to a node is not in register A, the specifier for the node is similar
to a token specifier: either a pointer to a symbol table entry for the variable that contains
the value or an integer constant.
Fig. 21 shows the code-generation routine considering the A-register of the
machine.
1.
System Software
208
2.
3.
4.
5.
6.
7.
Compilers
209
else
begin
GETA (< term >2)
generate [ DIV ST (< factor >)]
9.
10.
end
SR (< term >1) : = rA
REGA : = < term >1
< factor > : : = id
ST (< factor >) : = ST (id)
< factor > : : = int
ST (< factor >) : = ST (int)
< factor > : : = < exp >
ST (< factor >) : = ST (< exp >)
if ST (< factor >) = rA then
REGA : = < factor >
Fig. 21 Code Generation Routines
If the node specifies for either operand is rA, the corresponding value is already
in register A, the routine simply generates a MUL instruction. The node specifier for the
other operand gives the operand address for this MUL. Otherwise, the procedure GETA
is called. The GETA procedure is shown in fig. 22.
Procedure - GETA (NODE)
begin
if REGA = null then
generate [LDA ST (NODE) ]
else if ST (NODE) rA then
begin
creates a new looking variable Tempi
generate [STA Tempi]
record forward reference to Tempi
ST (REGA) : = Tempi
Generate [LDA ST (NODE)]
end (if rA)
ST(NODE) : = rA
REGA : = NODE
end {GETA }
Fig. 22
The procedure GETA generates a LDA instruction to load the values associated
to <term> 2 into register A. Before loading the value into A-register, it confirms whether
A is null. If it is not null it generates STA instruction to save the contents of register-A
into Temp-variable. There can be number of Temp variable like Temp1, Temp2 . . . etc.
The temporary variables used during a completion will be assigned storage location at the
end of the object program. The node specifies for the node associated with the value
System Software
210
SUMSQ
* 100
TMP1
MEAN
MEAN
TMP2
TMP1
TMP2
VARIABLE
Fig. 22
For the grammar < prog > the code-generation routine is shown in fig. 23. When
<prog> is recognized, storage locations are assigned to any temporary (Temp) variables
that have been used. Any references to these variables are then fixed in the object code
using the same process performed for forward references by a one-pass assembler. The
compiler also generates any modification records required to describe external references
to library subroutine.
< prog > : : = PROGRAM < prog-name > VAR < dec list >
BEGIN < stmp -- list > END.
generate [LDL RETADR]
generate [RSUB]
for each Temp variable used do
generate [ Temp RESW 1]
insert [ J EXADDR ] {jump to first executable instruction}
in bytes 3 - 5 of object program. fix up forward reference to
Temp variables generate modification records for external
references generates [END].
The < prog-name > generates header information in the object program that is
similar to that created from the START and EXTREF as assembler directives. It also
Compilers
211
generates instructions to save the return address and jump to the first executable
instruction in the compiled program. Fig. 24 shows the code generation routine for the
grammar < prog-name >.
< Program > : : = id
generate [START 0]
generate [EXTREF XREAD, XWRITE]
generate [STL RETADR]
add 3 to LC {leave room for jump to first executable instruction}
generate [RETADR RESW 1]
Fig. 24
Similar to the previous code-generation routine fig. 25 shows the codegeneration for < dec - list >, < dec > , < write >, < for > , < index - exp > and body.
< dec - list > : : = { alternatives }
save LC as EXADDR {tentative address of first executable
instruction}
< dec > : : = > id - list > : < type >
for each item on list do
begin
remove ST (NAME) from list
enter LC symbol table as address for NAME
generate [ST (NAME) RESW 1]
end
LIST COUNT : = 0
< write > : : = WRITE ( < id - list > )
generate [ + JSUB XWRITE]
record external reference to XWRITE
generate [WORD LISTCOUNT]
for each item on list do
begin
remove ST (ITEM) from list
generate [WORD ST (ITEM)]
end
LIST COUNT : = 0
< for > : : = FOR < id ex -- exp > Do < body >
POP JUMPADDR from stack {address of jump out of
loop}
POP ST (INDEX) from stack {index variable}
POP LOOPADDR from stack {beginning address of loop}
generate
[LDA ST (INDEX)]
generate
[ADD #1]
System Software
212
generate
insert
[ J LOOPADDR]
[ JGT LC ] at location JUMPADDR
< index - exp > : : = id : = < exp > | TO < exp >2
GETA (< exp >;)
Push LC onto stack {beginning addressing loop}
Push ST (id) onto stack {index variable}
Generate [STA ST (id)]
Generate [ COMP ST (< exp > 2)]
Push LC onto stack {address of jump out of loop}
and 3 to LC [ leave room for jump instruction]
REGA : = null
Fig. 25
START
EXTREF
STL
J
2 RETADDR RESW
3 SUM
RESW
SUMSQ
RESW
I
RESW
VALUE
RESW
MEAN
RESW
VARIANCE RESW
5 {EXADDR} LDA
STA
6
LDA
STA
7
LDA
{L1}STA
I
COMP
JGT
9
+ JSUB
WORD
WORD
10
LDA
ADD
STA
11
LDA
0
XREAD, XREAD, XWRITE
TETADR
{EXADDR}
1
1
1
1
1
1
1
#0
SUM
#0
SUMSQ
#1
# 100
{L2}
X READ
1
VALUE
SUM
VALUE
SUM
VALUE
{Program Header}
{Save return address}
{SUM = 0}
{SUMSQ : = 0}
{FOR I : = 1 TO 100}
{READ (VALUE) }
Compilers
213
13 {L2}
14
15
TEMP 1`
TEMP 2
MUL
ADD
STA
LDA
ADD
J
LDA
DIV
STA
LDA
DIV
STA
LDA
MUL
STA
LDA
SUB
STA
+JSUB
WORD
WORD
WORD
LDL
RSUB
RESW
RESW
END
VALUE
SUMSQ
SUMSQ
I
#1
{L1}
SUM
# 100
MEAN
SUM
# 100
TEMP1
MEAN
MEAN
TEMP2
TEMP1
TEMP2
VARIANCE
XWRITE
2
MEAN
VARIABLE
RETADR
1
1
Allocation of register
Rearrangement of machine instruction to improve efficiency of execution
The intermediate form that is discussed here represents the executable instruction
of the program with a sequence of quadruples. Each quadruples of the form
System Software
214
The entry i1, designates an intermediate result (SUM + VALUE); the second
quadruple assigns the value of this intermediate result to SUM. Assignment is treated as a
separate operation ( : =).
Example 2 : VARIANCE : = SUMSQ, DIV 100 -- MEAN * MEAN
DIV,
SUMSQ, #100,
i1
*,
MEAN, MEAN, i2
-,
i 1,
i 2,
i3
::=
i3
VARIABLE
Note: Quadruples appears in the order in which the corresponding object code
instructions are to be executed. This greatly simplifies the task of
analyzing the code for purposes of optimization. It is also easy to translate
into machine instructions.
For the source program in Pascal shown in fig. 1. The corresponding quadruples
are shown in fig. 27. The READ and WRITE statements are represented with a CALL
operation, followed by PARM quadruples that specify the parameters of the READ or
WRITE. The JGT operation in quadruples 4 in fig. 27 compares the values of its two
operands and jumps to quadruple 15 if the first operand is greater than the second. The J
operation in quadruples 14 jumps unconditionally to quadruple 4.
Line Operation OP 1
1.
2.
3.
4.
5.
6.
7.
9.
:=
:=
:=
JGT
CALL
PARAM
+
;=
*
#0
#0
#1
I
XREAD
SUMSQ
:=
i3
OP 2
#100
Result
SUM
SUMSQ
I
(15)
SUM : = 0
SUMSQ : = 0
FOR I : = 1 to 100
READ (VALUE)
VALUE
SUM
VALUE i1
i1
SUM
VALUE VALUE i2
VALUE
10.
* VALUE
11.
Pascal Statement
i2
i3
SUMSQ
Compilers
215
12.
13.
14.
15.
16.
17.
1
19.
20.
21.
22.
23.
+
:=
J
DIV
:=
DIV
*
:=
CALL
PARAM
PARAM
I
i4
SUM
i5
SUMSQ
MEAN
i6
i8
XWRITE
#1
i4
I
(4)
#100 i5
MEAN
#100 i6
MEAN i7
i7
i8
MEAN
VARIANCE
8.1.2
System Software
216
Block -- A
Quadruples 1 - 3
Block -- B
Quadruples 4
Block -- C
Quadruples 5 - 14
C : 5 - 14
Block -- D
Quadruples 15 - 20
D : 15 - 20
Block -- E
Quadruples 21 - 23
E : 21 - 23
A : 1-3
B:4
Fig. 28
Fig. 28 shows the basic blocks of the flow group for the quadruples in fig. 27. An
arrow from one block to another indicates that control can pass directly from one
quadruple to another. This kind of representation is called a flow group.
-- Rearranging quadruples before machine code generation:
Example :
1)
2)
3)
4)
DIV
*
:=
LDA
DIV
STA
LDA
MUL
STA
SUMSQ
# 100
MEAN
MEAN i2
i1
i2
i3
i3
VARIANCE
SUMSQ
# 100
T1
MEAN
MEAN
T2
SUB
STA
i1
LDA T1
T2
VARIANCE
Fig. 29
Fig. 29 shows a typical generation of machine code from the quadruples using
only a single register.
Note that the value of the intermediate result, is calculated first and stored in
temporary variable T1. Then the value of i2 is calculated subtracting i2 from ii.
Even though i2 value is in the register, it is not possible to perform the subtraction
operation. It is necessary to store the value of i2 in another temporary variable T2 and then
load the value of i1 from T1 into register A before performing the subtraction.
The optimizing compiler could rearrange the quadruples so that the second
operand of the subtraction is computed first. This results in reducing two memory
accesses. Fig. 29 shows the rearrangements.
*
DIV
MEAN
SUMSQ
MEAN i2
# 100 i1
Compilers
217
:=
i1
i3
LDA
MUL
STA
LDA
DIV
SUB
STA
i2
i3
VARIANCE
MEAN
MEAN
T1
SUMSQ
# 100
T1
VARIANCE
If each integer variable occupies one word of memory, then we require 10 words
of memory to store this array. In general an array declaration is ARRAY [ l .. u ] OF
INTEGER
Memory word allocated = ( u - l + 1) words.
(ii)
B : ARRAY [ 0 .. 3, 1 . . 3 ] OF INTEGER
System Software
218
0,2
0,3
0,4
0,5
0,1
Row 0
1,2
1,3
1,4
1,5
Row 1
2,1
2,2
2,3
2,4
2,5
...
Row 2
Fig. 30 (a)
Fig. 30(b) shows the column major way of storing the data in memory. All
elements that have the same value of the second subscript are stored together; this is
called column major order. In other words, the column major order, the left most
subscript varies most rapidly.
To refer to an element, we must calculate the address of the referenced element
relative to the base address of the array. Compiler would generate code to place the
relative address in an index register. Index addressing mode is made easier to access the
desired array element.
(1) One Dimensional Array: On a SIC machine to access A [6], the address is
calculated by starting address of data + size of each data * number of preceding data.
i.e. Assuming the starting address is 1000H
Size of each data is 3 bytes on SIC machine
Number of preceding data is 5
Therefore the address for A [ 6 ] is = 1000 + 3 * 5 = 1015. In general for A:
ARRAY [ l . . u ] of integer, if each array element occupies W bytes of storage and if the
value of the subscript is S, then the relative address of the referred element A[ S ] is given
by W * ( S - l ).
The code generation to perform such a calculation is shown in fig. 31.
The notation A[ i2 ] in quadruple 3 specifies that the generated machine code
should refer to A using index addressing after having placed the value
A: ARRAY [ 1 . . 10 ] OF INTEGER
.
.
.
A[ I ] : = S
(1)
+
:=
I
i1
#5
#1
#3
i1
i2
A [ i1 ]
Fig. 31 Code Generation for Single Dimension Array of i2 in the Index Register
Compilers
219
1)
*
-+
*
:=
I
j
i1
i3
#5
#6
#1
i2
#3
i1
i2
i3
i4
A [ i1 ]
The symbol - table entry for an array usually specifies the following:
This information is sufficient for the compiler to generate the code required for
array reference. Some of the languages line FORTRAN 90, the values of ROWS and
COLUMNS are not known at completion time. The compiler cannot directly generate
code. Then, the compiler create a descriptor called dope vector for the array. The
descriptor includes space for storing the lower and upper bounds for each array subscript.
When storage is allocated for the array, the values of these bounds are computed and
stored in the descriptor. The generated code for one array reference uses the values from
the descriptor to calculate relative addresses as required. The descriptor may also include
the number of dimension for the array, the type of the array elements and a pointer to the
beginning of the array. This information can be useful if the allocated array is passed as a
parameter to another procedure.
In the compilation of other structured variables like recode, string and sets the
same type of storage allocations are required. The compiler must store information
concerning the structure of the variable and use the information to generate code to
access components of the structure and it must construct a description for situation in
which the required conformation is not known at compilation time.
System Software
220
8.3.1
One important source of code optimization is the elimination of common subexpressions. These are sub-expressions that appear at more than one port in the program
and that compute the same value. Let us consider the example in fig. 33.
x, y : ARRAY [ 0 . . 10, 1 . . 10 ] OF INTEGER
.
.
.
FOR I : = 1 TO 10 DO
X [ I, 2 * J - 1 ] : = [ I, 2 * J }
Fig. 33(a)
1.
2.
3.
4.
5.
6.
7.
9.
10.
11.
12.
13.
14.
15.
16.
17.
1
19.
20.
:=
JGT
*
*
--+
*
-*
*
-+
*
:=
+
:=
J
OP 1
#1
I
I
i1
#2
i3
i4
i2
i6
I
i8
#2
i10
i9
i12
y [ i13 }
#1
i14
OP 2
#10
#1
#10
J
#1
#1
i5
#3
#1
#10
J
31
i11
#3
I
Result
Pascal Statement
I
(20)
i1
i2
i3
i4
i5
i6
i7
i8
i9
i10
i11
i12
i13
x [ i17 ]
i17
I
(2)
[Loop initialization]
[Subscript calculation for x]
[Assignment Operation]
[End of Loop]
[Next Statement]
Fig. 33(b)
Compilers
221
J is not changed in value between quadruples 5 and 12. It is not possible to reach
quadruple 12 without passing through quadruple 5 first because the quadruples are part of
the same basic block. Therefore, quadruples 5 and 12 compute the same value. This
means we can delete quadruple 12 and replace any reference to its result ( i10 ), with the
reference to i3, the result of quadruple 5. this information eliminates the duplicate
calculation of 2 * J which we identified previously as a common expression in the source
statement.
After the substitution of i3 for i10 , quadruples 6 and 13 are the same except for
the name of the result. Hence the quadruple 13 can be removed and substitute i4 for i11
wherever it is used. Similarly quadruple 10 and 11 can be removed because they are
equivalent to quadruples 3 and 4.
Line Operation
1.
2.
3.
4.
5.
6.
7.
9.
10.
11.
12.
13.
14.
15.
16.
OP 1
:=
JGT
*
*
+
*
+
#1
I
I
i1
#2
i3
i4
i2
i6
i2
*
:=
+
:=
J
i12
y [ i13 ]
#1
i14
OP 2
Result
#10
#1
#10
J
#1
#1
i5
#3
i4
I
(16)
i1
i2
i3
i4
i5
i6
i7
i12
#3
I
i13
x [i7 ]
i14
I
(2)
Pascal Statement
[Loop initialization]
[Subscript calculation for x]
[assignment Operation]
[End of Loop]
[Next Statement]
Fig. 34
Names i1 have been left unchanged, except for the substitutions first described, to
make the compromise with fig. 33(b) easier. This optimized code has only 15 quadruples
and hence the time taken is reduced.
Another method of code optimization is the removal of loop invariants. There
are sub-expressions within the loop whose values do not change from one iteration of the
loop to the next. Thus the values can be calculated once, before the loop is entered, rather
than being recalculated for each iteration. In the example shows in fig. 33(a), the loopinvariant computation is the term 2 * J [quadruple 5 fig. 34]. The result of this
computation depends only on the operand J, which does not change the value during the
execution of the loop. Thus we can move quadruple 5 in fig. 34 to a point immediately
before the loop is entered. A similar arrangement can be applied to quadruples 6 and 7.
Fig. 35 shows the sequence of quadruples that result from these modification.
System Software
222
The total number of quadruples remains the same as fig. 34, however, the number
of quadruples within the body of the loop has been reduced from 14 to 11. Our
modification have reduced the total number of quadruples for one execution of the FOR
from 181 [Fig. 23 (b) ], to 114 [Fig 25], which saves a substantial amount of time.
Line Operation
1.
2.
3.
4.
5.
6.
7.
9.
10.
11.
12.
13.
14.
15.
16.
*
:=
JGT
*
+
*
+
*
:=
+
:=
J
OP 1
#2
i3
i4
#1
I
I
i1
i2
i6
i2
i12
y [ i13 ]
#1
i14
OP 2
Result
Pascal Statement
J
#1
#1
i3
i4
i5
I
(16)
i1
i2
i6
i7
i12
i13
x [i7 ]
i14
I
(5)
{Commutation of invariants}
#10
#1
#10
i5
#3
i4
#3
I
{Loop Initialization}
{Next Statement}
Fig. 35
T1 : = 2 * J ;
T2 : = T1 -- 1 ;
FOR : = 1 To 10 Do
x [ I, T2 ] : = y[ I, T1]
Fig. 36(b)
This would achieve only a part of the benefits realized by the optimization
process described. Some time the statement in fig. 36(a) is preferable because it is clearer
than the modified version involving T1 and T2. An optimizing compiler should allow the
programmer to write source code that is clearer and easy to read and it should
compile such a program into machine code that is efficient to execute.
-- Code optimization of another source is the substitution of a more efficient
operation for a less efficient one.
Compilers
223
1.
2.
3.
4.
5.
6.
7.
:=
EXP
-*
:=
+
:=
JLE
OP 1
#1
#2
I
i2
i1
I
i4
I
OP 2
I
#1
#3
#1
#20
Result
Pascal Statement
I
{Loop Initialization}
i1
{ Calculation of 2 *
i5
{Subscript calculation }
i3
TABLE [ i2] {Assignment Operation}
i4
{End of the Loop}
I
i3
Fig. 37(a)
Line Operation
1.
2.
3.
4.
5.
6.
7.
9.
:=
:: =
:=
*
+
:=
+
:=
JLE
OP 1
#1
# (-3)
#1
i1
i3
i1
I
i4
I
OP 2
#2
#3
#1
#20
Result
Pascal Statement
i1
i3
I
i1
i3
TABLE [ i3]
i4
I
(4)
{Initialize temporaries}
{Loop Initialization}
{ Calculation of 2 * * I }
{Subscript calculation }
{Assignment Operation}
{End of the Loop}
Fig. 37(b)
STORAGE ALLOCATION
All the program defined variable, temporary variable, including the location used
to save the return address use simple type of storage assignment called static allocation.
When recursively procedures are called, static allocation cannot be used. This is
explained with an example. Fig. 38(a) shows the operating system calling the program
System Software
224
MAIN. The return address from register 'L' is stored as a static memory location
RETADR within MAIN.
SYSTEM
(1)
MAIN
SYSTEM
(1)
MAIN
SYSTEM
(1)
CALL SUB
RETADR
RETADR
(2)
(a)
MAIN
CALL SUB
RETADR
(2)
SUB
(b)
(3)
RETADR
(c)
CALL SUB
RETADR(c)
Fig. 38
In fig. 38(b) MAIN has called the procedure SUB. The return address for the call
has been stored at a fixed location within SUB (invocation 2). If SUB now calls itself
recursively as shown in fig. 38(c), a problem occurs. SUB stores the return address for
invocation 3 into RETADR from register L. This destroys the return address for
invocation 2. As a result, there is no possibility of ever making a correct return to MAIN.
There is no provision of saving the register contents. When the recursive call is
made, variable within SUB may set few variables. These variables may be destroyed.
However, these previous values may be needed by invocation 2 or SUB after the return
from the recursive call. Hence it is necessary to preserve the previous values of any
variables used by SUB, including parameters, temporaries, return addresses, register save
areas etc., when a recursive call is made. This is accomplished with a dynamic storage
allocation technique. In this technique, each procedure call creates an activation record
that contains storage for all the variables used by the procedure. If the procedure is called
recursively, another activation record is created. Each activation record is associated
with a particular invocation of the procedure, not with the itself. An activation record is
not deleted until a return has been made from the corresponding invocation.
Activation records are typically allocated on a stack, with the correct record at
the tip of the stack. It is shown in fig. 39(a). Fig. 39(a) corresponds to fig. 39(b). The
procedure MAIN has been called; its activation record appears on the stack. The base
register B has been set to indicate the starting address of this correct activation record.
The first word in an activation record would normally contain a pointer PREV to the
previous record on the stack. Since the record is the first, the pointer value is null. The
second word of the activation record contain a portion NEXT to the first unused word of
the stack, which will be the starting address for the next activation record created. The
Compilers
225
third word contain the return address for this invocation of the procedure, and the
necessary words contain the values of variables used by the procedure.
SYSTEMS
MAIN
RETADR
NEXT
0
Stack
Fig. 39 (a)
SYSTEM
(1)
Variables
For SUB
MAIN
CALL SUB
B
SUB
Stack
RETADR
NEXT
PREV
Variable
For MAIN
RETADR
NE XT
0
stacl
Fig. 39(b)
In fig. 39 (b), MAIN has called the procedure SUB. A new activation record has
been created on the top of the stack, with register B set to indicate this new current
record. The pointers PREV and NEXT in the time records have been set as shown.
SYSTEM
(1)
Variables
For SUB
MAIN
RETADR
NEXT
CALL SUB
B
PREV
Variable
For MAIN
RETADR
NEXT
CALL SUB
Fig. 39 (c)
PREV
Variable
For MAIN
RETADR
NEXT
0
Stack
System Software
226
In fig. 39(c), SUB has called itself recursively another activation record has been
created for this current invocation for SUB. Note that the return address and variable
values for the two invocations of SUB are kept separate by this process.
When a procedure returns to its caller, the current activation record (which
corresponds to the most recent invocation) is deleted. The pointer PREV in the deleted
record is used to reestablish the previous activation record as the current one, and
execution continues.
SYSTEM
(1)
Variables
For SUB
MAIN
CALL SUB
B
SUB
Fig. 39(d)
RETADR
NEXT
PREV
Variable
For MAIN
RETADR
NEXT
0
Stack
Fig. 39(d) shows the stack as it would appear after SUB returns from the
recursive call. Register B has been reset to point to the instruction record for the previous
invocation of SUB. The return address and all the variable values in this activation record
are exactly the same as they were before the recursive call.
This technique is called automatic allocation of storage. When the technique is
used the compiler must generate code for the reference to variables using some sort of
relative addressing. In our example the compiler assigns to each variable an address that
is relative to the beginning of the activation record, instead of an actual location within
the object program. The address of the current activation record is, by convention
contained in register B, so a reference to a variable is translated as an instruction that uses
base relative addressing. The displacement in this instruction is the relative address of the
variable within the activation record.
The compiler must also generate additional code to manage the activation records
themselves. At the beginning of each procedure there must be code to create a new
activation record, linking it to the previous one and setting the appropriate pointers as
shown in fig. 39. This code is often called a prologue for the procedure. At the end of the
procedure, there must be code to delete the current activation record, resulting
pointers as needed. This code is called an epilogue.
Example: IN FOTRAN 90 :ALLOCATE (MATRIX (ROWS, COLUMNS) )
allocation storage for the dynamic array MATRIX with the specified dimensions.
DE-ALLOCATE MATRIX
releases the storage assigned to MATRIX by a previous ALLOCATE.
IN PASCAL: NEW (P)
allocates storage for a variable and sets the pointer P to indicate the variable just
created.
Compilers
227
DISPOSE (P)
releases the storage that was previously assigned to the variable pointed to by P.
System Software
228
PROCEDURE A ;
VAR X, Y, Z : INTEGER ;
:
PROCEDURE B ;
VAR W, X, Y : REAL ;
:
PROCEDURE C ;
VAR W, V
: INTEGER ;
:
END { C };
:
END { B };
:
PROCEDURE D ;
VAR X, Z
: CHAR ;
.
2
.
END { D};
END { A};
1
3
Name
A
B
C
D
Block
Number Level
1
1
2
2
3
3
4
2
Fig. 41
Surrounding
Block
-1
2
1
Since a name can be declared more than once in a program (by different blocks),
each symbol-table entry for an identifier must contain the number of the declaring block.
A declaration of an identifier is legal if there has been no previous declaration of that
identifier by the current block, so there can be several symbolic table entries for the same
name. The entries that represent declaration of the same name by different blocks can be
linked together in the symbol table with a chain of pointers.
When a reference to an identifier appears in the source program, the compiler
must first check the symbol table for a definition of that identifier by the current block. If
not such definition is found, the compiler looks for a definition by the block that
surrounds the current one, then by the block that surrounds that and so on. If the
outermost block is reached without finding a definition of the identifier, then the
reference is an error.
The search process just described can easily be implemented within a symbol
table that uses hashed addressing. The hashing function is used to locate one definition of
the identifier. The chain of definitions for that identifier is then searched for the
appropriate entry.
Most block-structured languages make use of automatic storage allocation. The
variables that are defined by a block are stored in an activation record that is created each
Compilers
229
time the block is entered. If a statement refers to a variable that is declared within the
current block, this variable is present in the current activation record, so it can be
accessed in the usual way. It is possible to refer to a variable that is declared in some
surrounding block. In that case, the most recent activation record for that block must be
located to access the variable.
Activation
Record for C
Activation
Record for C
Activation
Record for B
Activation
Stack
Record
(a) for A
Activation
Record for C
C
B
A
Activation
Record for B
(b)
Activation
Record for A
C
B
A
Example:
D
A
A
Display
Stack
Fig 42(c)
System Software
230
Now if procedure 'C' call procedure D the resulting stack and display are as
illustrated in fig. 42(c) . An activation record for D has been created in the usual way and
added to the stack. Note, that the display now contains only two pointers: one each to the
activation records for D and A. This is because procedure D cannot refer to variable in B
or C, except through parameters that are passed to it, even though it is called from C.
According to the rules for the scope of names in as block-structured language, procedure
D can refer only to variable that are declared by D or by some block that contains D in
the source program.
8.4 COMPILER DESIGN OPTIONS
The compiler design is briefly discussed in this section. The compiler is divided
into single pass and multi pass compilers.
4.1. COMPILER PASSES
One pass compiler for a subset of the Pascal language was discussed in section 1.
In this design the parsing process drove the compiler. The lexical scanner was called
when the parser needed another input token and a code-generation routine was invoked as
the parser recognized each language construct. The code optimization techniques
discussed cannot be applied in total to one-pass compiler without intermediate codegeneration. One pass compiler is efficient to generate the object code.
One pass compiler cannot be used for translation for all languages. FORTRAN
and PASCAL language programs have declaration of variable at the beginning of the
program. Any variable that is not declared is assigned characteristic by default.
One pass compiler may fix the formal reference jump instruction without
problem as in one pass assembler. But it is difficult to fix if the declaration of an
identifier appears after it has been used in the program as in some programming
languages.
Example:
X:=Y*Z
If all the variables x, y and z are of type INTEGER, the object code for this
statement might consist of a simple integer multiplication followed by storage of the
result. If the variable are a mixture of REAL and INTEGER types, one or more
conversion operations will need to be included in the object code, and floating point
arithmetic instructions may be used. Obviously the compiler cannot decide what machine
instructions to generate for this statement unless instruction about the operands is
available. The statement may even be illegal for certain combinations of operand types.
Thus a language that allows forward reference to data items cannot be compiled in one
pass.
Some programming language requires more than two passes. Example :
ALGOL-98 requires at least 3 passes.
There are a number of factors that should be considered in deciding between one
pass and multi pass compiler designs.
(1) One Pass Compiles: Speed of compilation is considered important.
Computer running students jobs tend to spend a large amount of time performing
compilations. The resulting object code is usually executed only once or twice for each
Compilers
231
compilation, these test runs are not normally very short. In such an environment,
improvement in the speed of compilation can lead to significant benefit in system
performance and job turn around time.
(2) Multi-Pass Compiles: If programs are executed many times for each
compilation or if they process large amount of data, then speed of executive becomes
more important than speed of compilation. In a case, we might prefer a multi-pass
compiler design that could incorporate sophisticated code-optimization technique.
Multi-pass compilers are also used when the amount of memory, or other
systems resources, is severely limited. The requirements of each pass can be kept smaller
if the work by compilation is divided into several passes.
Other factors may also influence the design of the compiler. If a compiler is
divided into several passes, each pass becomes simpler and therefore, easier to
understand, read and test. Different passes can be assigned to different programmers and
can be written and tested in parallel, which shortens the overall time require for compiler
construction.
INTERPRETERS
An interpreter processes a source program written in a high-level language. The
main difference between compiler and interpreter is that interpreters execute a version of
the source program directly, instead of translating it into machine code.
An interpreter performs lexical and syntactic analysis functions just like compiler
and then translates the source program into an internal form. The internal form may also
be a sequence of quadruples.
After translating the source program into an internal form, the interpreter
executes the operations specified by the program. During this phase, an interpreter can be
viewed as a set of subtractions. The internal form of the program drives the execution of
this subtraction.
The major differences b/w interpreter and compiler are:
Interpreters
Compilers
System Software
232
1) The process of translating a source
program into some internal form is
simpler and faster
2) Execution of the translated program
is much slower.
3) Debugging facilities can be easily
provided.
4) During execution the interpreter
produce symbolic dumps of data
values, trace of program execution
related to the source statement.
Compilers
233
P-Code
Compiler
Compiler
Object Program
P - Code
P - Code
Interpreter
Execute
Fig. 43
The design of a P-machine and the associated P-code is often related to the
requirements of the language being compiled. For example, the P-code for a Pascal
compiler might include single P-instructions that perform:
Array subscript calculation
Handle the details of procedure entry and exit and
Perform elementary operation on sets
This simplifies the code generation process, leading to a smaller and more
efficient compiler.
The P-code object program is often much smaller than a corresponding machine
code program. This is particularly useful on machines with severely limited memory size.
The interpretive execution of P-code program may be much slower than the
execution of the equivalent machine code. Many P-code compilers are designed for a
single user running on a dedicated micro-computer systems. In that case, the speed of
execution may be relatively insignificant because the limiting factor is system
performance may be the response time and " think time " of the user.
If execution speed is important, some P-code compilers support the use of
machine-language subtraction. By rewriting a small number of commonly used routines
in machine language, rather than P-code, it is often possible to improve the performance.
Of course, this approach sacrifices some of the portability associated with the use of Pcode compilers.
8.4.2
COMPILER-COMPILERS
System Software
234
Lexical Ruler
Grammar
Compiler-Compiler
Scanner
Parser
Semantic
Routines
Fig. 44
Code
Generator
Compiler