Hey everyone,
I've been working for some time on (Java) Bytecode, however, it had never occurred to me to ask why are some instructions typed? I understand that in an ADD operation, we need to distinguish between an integer addition and a FP addition (that's why we have IADD and FADD). However, why do we need to distinguish between ISTORE and FSTORE? They both involve the exact same operation, which is moving 32 bits from the stack to a local variable position?
The only answer I can think of is for type-safety, to prevent this: (ILOAD, ILOAD, FADD). However, I believe that type-safety is already enforced at the Java language level. OK, the Class file format is not directly coupled with Java, so is this a way to enforce type-safety for languages that do not support it? Any thought? Thank you.
EDIT: to follow up on Reedy's answer. I wrote this minimal program:
public static void main(String args[])
{
int x = 1;
}
which compiled to:
iconst_1
istore_1
return
using a bytecode editor, I changed the second instruction:
iconst_1
fstore_1
return
and it returned a java.lang.VerifyError: Expecting to find float on stack.
I wonder, if on the stack there's no information on the type, just bits, how did the FSTORE instruction knew that it was dealing with a int and not a float?
Note: I couldn't find a better title for this question. Feel free to improve it.