Syntax Directed TranslationSyntax Directed Translation
66.648 Compiler Design Lecture (03/16//98)66.648 Compiler Design Lecture (03/16//98)
Computer ScienceComputer Science
Rensselaer PolytechnicRensselaer Polytechnic
Lecture OutlineLecture Outline
• Syntax Directed TranslationSyntax Directed Translation
• Java Virtual MachineJava Virtual Machine
• ExamplesExamples
• AdministrationAdministration
Phases of a CompilerPhases of a Compiler
1. Lexical Analyzer (Scanner)1. Lexical Analyzer (Scanner)
Takes source Program and Converts into tokensTakes source Program and Converts into tokens
2. Syntax Analyzer (Parser)2. Syntax Analyzer (Parser)
Takes tokens and constructs a parse tree.Takes tokens and constructs a parse tree.
3. Semantic Analyzer3. Semantic Analyzer
Takes a parse tree and constructs an abstract Takes a parse tree and constructs an abstract syntax tree with attributes.syntax tree with attributes.
Phases of a Compiler- ContdPhases of a Compiler- Contd
4. Syntax Directed Translation 4. Syntax Directed Translation
Takes an abstract syntax tree and produces an Takes an abstract syntax tree and produces an Interpreter code (Translation output)Interpreter code (Translation output)
5. Intermediate-code Generator 5. Intermediate-code Generator
Takes an abstract syntax tree and produces un- Takes an abstract syntax tree and produces un- optimized Intermediate code.optimized Intermediate code.
Syntax Directed Translation Syntax Directed Translation SchemeScheme
A syntax directed translation scheme is a syntax A syntax directed translation scheme is a syntax directed definition in which the net effect of directed definition in which the net effect of semantic actions is to print out a translation of semantic actions is to print out a translation of the input to a desired output form.the input to a desired output form.
This is accomplished by including “emit” This is accomplished by including “emit” statements in semantic actions that write out statements in semantic actions that write out text fragments of the output, as well as string-text fragments of the output, as well as string-valued attributes that compute text fragments to valued attributes that compute text fragments to be fed into emit statements.be fed into emit statements.
1. Postfix and Prefix notations:1. Postfix and Prefix notations:
We have already seen how to generate them.We have already seen how to generate them.
Let us generate Java Byte code.Let us generate Java Byte code.
E -> E’+’ E { emit(“iadd”);}E -> E’+’ E { emit(“iadd”);}
E-> E ‘* ‘ E { emit(“imul”);}E-> E ‘* ‘ E { emit(“imul”);}
E-> TE-> T
T -> ICONST { emit(“sipush ICONST.string);}T -> ICONST { emit(“sipush ICONST.string);}
T-> ‘(‘ E ‘)’T-> ‘(‘ E ‘)’
ExamplesExamples
We now present (Read Java Virtual Machine Spec) We now present (Read Java Virtual Machine Spec) a simple stack machine and illustrate how to a simple stack machine and illustrate how to generate code for it via syntax-directed generate code for it via syntax-directed translations.translations.
The abstract machine code for an expression The abstract machine code for an expression simulates a stack evaluation of the postfix simulates a stack evaluation of the postfix representation for the expression. Expression representation for the expression. Expression evaluation proceeds by processing the postfix evaluation proceeds by processing the postfix representation from left to right.representation from left to right.
Abstract Stack MachineAbstract Stack Machine
EvaluationEvaluation
1. Pushing each operand onto the stack when 1. Pushing each operand onto the stack when encountered.encountered.
2. Evaluating a k-ary operator by using the value 2. Evaluating a k-ary operator by using the value located k-1 positions below the top of the stack located k-1 positions below the top of the stack as the leftmost operand, and so on, till the value as the leftmost operand, and so on, till the value on the top of the stack is used as the rightmost on the top of the stack is used as the rightmost operand.operand.
3. After the evaluation, all k operands are popped 3. After the evaluation, all k operands are popped from the stack, and the result is pushed onto from the stack, and the result is pushed onto the stack (or there could be a side-effect)the stack (or there could be a side-effect)
ExampleExample
Stmt -> ID ‘=‘ expr Stmt -> ID ‘=‘ expr { stmt.t = expr.t || ‘istore a’}{ stmt.t = expr.t || ‘istore a’}
applied to a = 3*b -capplied to a = 3*b -c
bipush 3bipush 3
iload biload b
imulimul
iload ciload c
isubisub
istore aistore a
Java Virtual MachineJava Virtual Machine
Analogous to the abstract stack machine, the Java Analogous to the abstract stack machine, the Java Virtual machine is an abstract processor Virtual machine is an abstract processor architecture that defines the behavior of Java architecture that defines the behavior of Java Bytecode programs.Bytecode programs.
The stack (in JVM) is referred to as the operand The stack (in JVM) is referred to as the operand stack or value stack. Operands are fetched from stack or value stack. Operands are fetched from the stack and the result is pushed back on to the stack and the result is pushed back on to the stack.the stack.
Advantages: VM code is compact as the operands Advantages: VM code is compact as the operands need not be explicitly named.need not be explicitly named.
Data TypesData Types
The int data type ca nold 32 bit signed integers in The int data type ca nold 32 bit signed integers in the range -2^31 to 2^(31) -1.the range -2^31 to 2^(31) -1.
The long data type can hold 64 bit signed integers.The long data type can hold 64 bit signed integers.
Integer instructions in the Java VM are also used Integer instructions in the Java VM are also used to operate on Boolean values.to operate on Boolean values.
Other data types that Java VM supports are byte, Other data types that Java VM supports are byte, short, float, double. (Your project should handle short, float, double. (Your project should handle at least three data types).at least three data types).
Selected Java VM InstructionsSelected Java VM Instructions
Java VM instructions are typed I.e., the operator Java VM instructions are typed I.e., the operator explicitly specifies what operand types it expects.explicitly specifies what operand types it expects.
Expression EvaluationExpression Evaluation
sipush n sipush n push a 2 byte signed int on to stackpush a 2 byte signed int on to stack
iload viload v load/push a local variable vload/push a local variable v
istore vistore v store top of stack onto local var vstore top of stack onto local var v
iaddiadd pop tow elements and push their sumpop tow elements and push their sum
isubisub pop two elements and push their pop two elements and push their differencedifference
Selected Java VM InstructionsSelected Java VM Instructions
Imul Imul pop two elements and push their productpop two elements and push their product
iandiand pop two lements and push their bitwise andpop two lements and push their bitwise and
iorior
inegineg pop top element and push its negationpop top element and push its negation
lcmplcmp pop two elements (64 bit integers), push the pop two elements (64 bit integers), push the comparison result. 1 if Vs[0]<vs[1], 0 if vs[0]=vs[1] comparison result. 1 if Vs[0]<vs[1], 0 if vs[0]=vs[1] otherwise -1.otherwise -1.
I2LI2L convert integers to long convert integers to long
L2iL2i
Selected Java VM InstructionsSelected Java VM Instructions
Branches:Branches:
GOTO LGOTO L unconditional transfer to label lunconditional transfer to label l
ifeq Lifeq L transfer to label L if top of stack is transfer to label L if top of stack is 00
ifneifne transfer to label L if top of stack !transfer to label L if top of stack !=0=0
Call/Return: Each method/procedure has memory Call/Return: Each method/procedure has memory space allocated to hold local variables (vars space allocated to hold local variables (vars register), an operand stack (optop register) and register), an operand stack (optop register) and an execution environment (frame register)an execution environment (frame register)
Selected Java VM InstructionsSelected Java VM Instructions
Invokestatic p invoke method p. pop args from Invokestatic p invoke method p. pop args from stack as initial values of formal parameters stack as initial values of formal parameters (actual parameters are pushed before calling).(actual parameters are pushed before calling).
ReturnReturn return from current procedurereturn from current procedure
ireturn ireturn return from current procedure with return from current procedure with integer value on top of stack.integer value on top of stack.
Areturn Areturn return from current procedure with object return from current procedure with object reference return value on top of stack. reference return value on top of stack.
Selected Java VM InstructionsSelected Java VM Instructions
Array Manipulation: Java VM has an object data Array Manipulation: Java VM has an object data type reference to arrays and objectstype reference to arrays and objects
newarray intnewarray int create a new arrae of create a new arrae of integers using the top of the stack as the size. integers using the top of the stack as the size. Pop the stack and push a reference to the newly Pop the stack and push a reference to the newly created array.created array.
Iaload Iaload pop array subscript expression on top of pop array subscript expression on top of stack and array pointer (next stack element). stack and array pointer (next stack element). Push value contained in this array element.Push value contained in this array element.
iastore iastore
Selected Java VM InstructionsSelected Java VM Instructions
Object ManipulationObject Manipulation
new cnew c create a new instance of class C (using create a new instance of class C (using heap) and push the reference onto stack.heap) and push the reference onto stack.
Getfield f Getfield f push value from object field f of push value from object field f of object pointed by object reference at the top of object pointed by object reference at the top of stack.stack.
Putfield fPutfield f store value from vs[1] into field f of store value from vs[1] into field f of object pointed by the object reference vs[0]object pointed by the object reference vs[0]
Selected Java VM InstructionsSelected Java VM Instructions
Simplifying Instructions:Simplifying Instructions:
ldc constant is a macro which will generate either ldc constant is a macro which will generate either bipush or sipush depending on c.bipush or sipush depending on c.
For the project, we will use the java assembler of For the project, we will use the java assembler of Jason Hunt (washington university).Jason Hunt (washington university).
Advantages:Advantages:
No need to worry about binary class files. They No need to worry about binary class files. They get generated automatically.Named local get generated automatically.Named local variables. Labels instead of byte offsets.variables. Labels instead of byte offsets.
Byte Code (JVM Instructions)Byte Code (JVM Instructions)
No-arg operand: (instructions needing no No-arg operand: (instructions needing no arguments hence take only one byte.)arguments hence take only one byte.)
examples: aaload, aastore,aconsta_null, aload_0, examples: aaload, aastore,aconsta_null, aload_0, aload_1, areturn, arraylength, astore_0, athrow, aload_1, areturn, arraylength, astore_0, athrow, baload, iaload, imul etcbaload, iaload, imul etc
One-arg operand: bipush, sipush,ldc etcOne-arg operand: bipush, sipush,ldc etc
methodref op:methodref op:
invokestatic, invokenonvirtual, invokevirtualinvokestatic, invokenonvirtual, invokevirtual
Byte Code (JVM Instructions)Byte Code (JVM Instructions)
Fieldref_arg_op:Fieldref_arg_op:
getfield, getstaic, putfield, pustatic.getfield, getstaic, putfield, pustatic.
Class_arg_op:Class_arg_op:
checkcast, instanceof, newcheckcast, instanceof, new
labelarg_op (instructions that use labels)labelarg_op (instructions that use labels)
goto, ifeq, ifne, jsr, jsr_w etcgoto, ifeq, ifne, jsr, jsr_w etc
Localvar_arg_op:Localvar_arg_op:
iload, fload, aload, istoreiload, fload, aload, istore
Translating an if statementTranslating an if statement
Stmt -> if expr then stmt1 { out = newlabel();Stmt -> if expr then stmt1 { out = newlabel();
stmt.t = expr.t|| ‘ifnnonnull’ || out || stmt1.t ||stmt.t = expr.t|| ‘ifnnonnull’ || out || stmt1.t ||
‘‘label’ out: ‘nop’ }label’ out: ‘nop’ }
example:example:
if ( a +90==7) { x = x+1; x = x+3;}if ( a +90==7) { x = x+1; x = x+3;}
Translating a while statementTranslating a while statement
Stmt -> WHILE (expr) stmt1 { in =newlabel(); out= Stmt -> WHILE (expr) stmt1 { in =newlabel(); out= neewlabel(); neewlabel();
stmt.t = ‘label’ || in|| ‘nop’ || expr.t || ‘ifnonnull’|| stmt.t = ‘label’ || in|| ‘nop’ || expr.t || ‘ifnonnull’|| out|| stmt1.t || ‘goto’ || in|| ‘label’ || out }out|| stmt1.t || ‘goto’ || in|| ‘label’ || out }
Comments and FeedbackComments and Feedback
Project 3 is out. Please start working. PLEASE do Project 3 is out. Please start working. PLEASE do not wait for the due date to come.not wait for the due date to come.
We are looking at the relevant portion of Java. We are looking at the relevant portion of Java. Please keep studying this material. Please keep studying this material.