Java Reference
In-Depth Information
Consider the case where we were implementing the Java do-while statement; for ex-
ample,
do{
a++;
}
while(a<b);
The do-while statement is not in j-- but we could add it 5 . The code we generate might
have the form
topLabel:
<codeforbody>
branchtotopLabelif<condition>istrue
While we branch on the condition false for the if-then-else statement, we would
branch on the condition true for the do-while statement.
In generating code for a condition, one needs a method of specifying three arguments:
1. The CLEmitter ,
2. The target label for the branch, and
3. A boolean ag, onTrue . If onTrue is true , then the branch should be made on the
condition; if false , the branch should be made on the condition's complement.
Thus, every boolean expression must support a version of codegen() with these three
arguments. For example, consider that for JGreaterThanOp is:
publicvoidcodegen(CLEmitteroutput,StringtargetLabel,
booleanonTrue){
lhs.codegen(output);
rhs.codegen(output);
output.addBranchInstruction(onTrue?IF_ICMPGT:IF_ICMPLE,
targetLabel);
}
A method of this sort is invoked on the condition controlling execution; for example, the
following codegen() for JIfStatement makes use of such a method in producing code for
the if-then-else statement.
publicvoidcodegen(CLEmitteroutput){
StringelseLabel=output.createLabel();
StringendLabel=output.createLabel();
condition.codegen(output,elseLabel,false);
thenPart.codegen(output);
if(elsePart!=null){
output.addBranchInstruction(GOTO,endLabel);
}
output.addLabel(elseLabel);
if(elsePart!=null){
elsePart.codegen(output);
output.addLabel(endLabel);
}
}
Notice that method createLabel() creates a unique label each time it is invoked, and the
addLabel() and addBranchInstruction() methods compute the necessary offsets for the
actual JVM branches.
5 Implementing the do-while statement is left as an exercise.
 
Search WWH ::




Custom Search