3 - Controlling the Flow: the GOTO solution!
What to implement
Update your step
function.
Update your step
function.
Instructions
OP_GOTO
OP_IFEQ
OP_IFLT
OP_IF_ICMPEQ
In order to pass test3, correctly implement all of the functions and instructions listed above.
OP_GOTO
OP_IFEQ
OP_IFLT
OP_IF_ICMPEQ
In order to pass test3, correctly implement all of the functions and instructions listed above.
Introduction
In this chapter, you will be tasked with implementing basic branching. The IJVM instruction set contains four instructions that control the flow of the program: GOTO, IFEQ, IFLT and IF_ICMPEQ. The idea behind the GOTO instruction is simple: add an offset to the program counter, and continue executing the program from that address. Other instructions such as IFEQ do the same, but only branch if a certain condition is met.
To illustrate how GOTO should behave, consider the following example program which prints 13 (and skips printing 2):
.main
L1:
BIPUSH 0x31 // Push ’1’
OUT // Print ’1’
GOTO L3 // Jump to L3
L2:
BIPUSH 0x32 // Push '2'
OUT // Print ’2’
L3:
BIPUSH 0x33 // Push '3'
OUT // Print ’3’
HALT
.end-main
In contrast to the instructions you've implemented so far, the GOTO, IFEQ, IFLT and IF_ICMPEQ instructions take a signed short as an argument. The figure below illustrates the layout of different IJVM instruction formats:
The suggested approach
Start with implementing the GOTO instruction, then move to the other three.
OpCode | Instruction | Args | Description |
---|---|---|---|
0xA7 | GOTO | short | Increment the program counter by a (signed) short |
0x99 | IFEQ | short | Pop a word from the stack and branch if it equals zero |
0x9B | IFLT | short | Pop a word from the stack and branch if it is less than zero |
0x9F | IF_ICMPEQ | short | Pop two words from the stack and branch if they are equal |
Hints
Keep in mind that the offset is calculated based on the program counter value at the beginning of the branching instruction, so you might obtain an incorrect value if you directly increment your program counter to obtain the argument.
Some instructions, such as the branching instructions, have arguments that are signed, while other instructions have an unsigned argument. In general, instructions that take an index as argument have an unsigned argument, while other instructions have signed arguments.
Keep in mind that the offset is calculated based on the program counter value at the beginning of the branching instruction, so you might obtain an incorrect value if you directly increment your program counter to obtain the argument.
Some instructions, such as the branching instructions, have arguments that are signed, while other instructions have an unsigned argument. In general, instructions that take an index as argument have an unsigned argument, while other instructions have signed arguments.