Stack Machine Design problems.

Started by
0 comments, last by Mithrandir 22 years, 7 months ago
Now, im working on a virtual machine project, where I am tasked to write a simple virtual machine that will be stack based. At the initial viewing of the instruction set, stack machines appear simple, as almost all operands are implicit. This allows us to create an instruction format which is relatively simple and small. The problem arises when an immediate value is required. My dillemma is such: my instructions are byte-sized, but immediate values may need to be up to 4 bytes long. Should i create a variable-length instruction format (1-5 bytes) to handle immediates? This solution initially appeared unviable to me, because it introduces complexity within a simple system. Variable width instruction formats are a pain in the butt. So the other option that jumped out at me would be to use a 32 bit instruction format, where the first byte is the opcode, and the next 3 bytes are the immediate value (I think i can get away with 24 bit immediates). This also has a major drawback: Since the majority of instructions do not require immediate operands, most instructions are wasting 3 bytes. sigh. Anyone have experience with stack machines they wish to share with me?
This is my signature. There are many like it, but this one is mine. My signature is my best friend. It is my life. I must master it as I must master my life. My signature, without me, is useless. Without my signature, I am useless.
Advertisement
The java virtual machine is a stack based machine. It uses variable length instructions, kind of. Each instruction is only one byte, but may be followed by one or two bytes of operand information.

If the value x is in the range -1 <= x <= 5, there is a dedicated instruction for pushing that constant onto the stack.

If the value x is in the range -128 <= x <= 127, it uses a "byte integer push" (bipush) instruction, followed by an additional byte for the value to push.

If the value x is in the range -32768 <= x <= 32767, it uses a "short integer push" (sipush) instruction, followed by an additional two bytes for the value to push.

If the value is outside of the above ranges, a "load constant" (ldc) instruction is used, giving a two byte index (unsigned short) into the constant pool portion of the .class file, pointing to the value to load.

That''s probably a far more sophisticated setup than you need. But that''s how it''s been done in one fairly popular VM design.

This topic is closed to new replies.

Advertisement