Sub topic 6
Frames, locals and the operand stack
This chapter assumes you can read basic javap -c output (see the previous chapter on bytecode) and know that each Java thread has its own stack. You will learn what a frame holds, how bytecode moves values between locals and the operand stack, and how arguments and return values cross a method call.
What a frame is
The JVM creates a frame every time a method is invoked and discards it when the method returns, normally or by exception. Frames live on the invoking thread's stack. The frame at the top belongs to the method that is currently running.
A frame has three main parts:
- Local variable array. A numbered set of slots holding the method's parameters and local variables.
- Operand stack. A last-in, first-out work area. Instructions push values onto it, pop values off it, and leave results on it.
- Reference to the runtime constant pool. This lets instructions such as
invokestaticresolve the symbolic names in the class's constant pool.
The compiler computes the size of the first two parts for each method. They are stored in the method's Code attribute as max_locals and max_stack. The JVM can therefore allocate each frame at its exact size.
Locals and the operand stack in practice
Compile this class with javac -g FrameDemo.java. The -g flag keeps variable names, so javap -c -l can show which slot each variable occupies.
public class FrameDemo {
public static int sum(int a, int b) {
int c = a + b;
int d = c * 2;
return d - a;
}
public int twice(int x) {
return x * 2;
}
public static long widen(long a, int b) {
return a + b;
}
public static void main(String[] args) {
int r = sum(3, 4);
System.out.println(r);
}
}Run javap -c -l FrameDemo. The output for sum looks like this:
public static int sum(int, int);
Code:
0: iload_0
1: iload_1
2: iadd
3: istore_2
4: iload_2
5: iconst_2
6: imul
7: istore_3
8: iload_3
9: iload_0
10: isub
11: ireturn
LocalVariableTable:
Start Length Slot Name Signature
0 12 0 a I
0 12 1 b I
4 8 2 c I
8 4 3 d IThe prefix of each instruction tells you the type: i is int, l is long, a is a reference. The names iload_0 through iload_3 are one-byte shortcuts for loading slots 0 to 3. Beyond slot 3 the compiler emits iload 4 with an explicit index.
Tracing the stack
Follow sum(3, 4) one instruction at a time. Brackets show the operand stack with the top on the right.
| Offset | Instruction | Operand stack after | Locals after |
|---|---|---|---|
| 0 | `iload_0` | [3] | a=3, b=4 |
| 1 | `iload_1` | [3, 4] | a=3, b=4 |
| 2 | `iadd` | [7] | a=3, b=4 |
| 3 | `istore_2` | [] | c=7 |
| 4 | `iload_2` | [7] | c=7 |
| 5 | `iconst_2` | [7, 2] | c=7 |
| 6 | `imul` | [14] | c=7 |
| 7 | `istore_3` | [] | d=14 |
| 8 | `iload_3` | [14] | d=14 |
| 9 | `iload_0` | [14, 3] | a=3 |
| 10 | `isub` | [11] | a=3 |
| 11 | `ireturn` | (frame discarded) |
The deepest the stack gets is two entries, so javac records max_stack=2. Four slots are used, so it records max_locals=4. Run javap -c -v to see these numbers in the stack=2, locals=4, args_size=2 line.
Two patterns recur everywhere in bytecode:
- Load, operate, store. Values are copied from locals to the stack, an instruction consumes them, and
storemoves the result back into a local. - Operators take their operands from the stack.
iaddhas no operands in the class file. It pops two ints and pushes their sum.
Slot numbering rules
Slot numbers are assigned by the compiler in a fixed order.
- Instance methods start with
thisin slot 0, then the parameters. Intwice(int x),thisis slot 0 andxis slot 1, so the body isiload_1,iconst_2,imul,ireturn. - Static methods have no
this, so the first parameter is slot 0. - Local variables get the next free slots after the parameters.
- Block-scoped variables share slots. javac reuses a slot once the variable's block ends. In
if (f) { int x = 1; return x; } int y = 2;, bothxandycan occupy slot 1.
Calls: how values cross frames
The operand stack is also how methods exchange data. Here is main from FrameDemo:
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: iconst_4
2: invokestatic #7 // Method sum:(II)I
5: istore_1
6: getstatic #13 // Field java/lang/System.out:Ljava/io/PrintStream;
9: iload_1
10: invokevirtual #19 // Method java/io/PrintStream.println:(I)V
13: returnThe # indexes depend on your compiler version, so yours may differ. The sequence of events does not:
mainpushes the arguments 3 and 4 onto its own operand stack.invokestaticreads the descriptor(II)Ifrom the constant pool. It pops two ints and copies them into slots 0 and 1 of a new frame forsum.sumruns with its own empty operand stack.ireturnpops 11 fromsum's stack, discards thesumframe, and pushes 11 onto the operand stack ofmain.istore_1moves that 11 into the local variabler.
For an instance call, the receiver reference is pushed first, then the arguments. The callee sees the receiver as this in slot 0. This is why println(I)V in the example is preceded by getstatic for System.out. The next chapter covers the invocation instructions in detail.
Updating locals without the stack: iinc
Not every local update goes through the stack. For i++ or i += 5 on an int local, javac emits iinc <slot>, <constant>, which changes the slot directly. A counting loop therefore needs no iload, iconst_1, iadd, istore sequence for its increment.
Limits and failure modes
- StackOverflowError. Each thread's stack has a maximum size, set with
-Xss. Deep or unbounded recursion creates frames until the limit is reached, and the JVM throwsStackOverflowError. The error concerns the number of frames. It is unrelated to the size of the operand stack in any one frame. - Verification. Before a class runs, the verifier checks that every instruction finds the types it expects in the right slots and stack positions. It also checks that the stack never exceeds
max_stackand that no code path reads a local before it is assigned. At a branch target, the stack shape must be the same no matter which path led there. This is why the Java compiler rejectsint x; return x;and why hand-generated bytecode that breaks the rules fails with aVerifyError. - Exceptions. When an exception reaches a matching handler in the same method, the JVM clears the operand stack and pushes the exception reference. Locals keep their values.
- Frames are not the heap. Primitives in locals live in the frame. An object reference in a local lives in the frame, but the object it points to lives on the heap.
Exercises
Exercise
For the instance method public int twice(int x) { return x * 2; }, which slot holds x, and what is the full instruction sequence? Why is it different from a static method with the same body?
Show answer
x is in slot 1, because slot 0 holds this. The sequence is iload_1, iconst_2, imul, ireturn. In a static method there is no this, so x would be in slot 0 and the first instruction would be iload_0.
Exercise
A static method has the signature static double scale(double v, int n). Which slots do v and n occupy, and what is the smallest max_locals the method can declare if it has no other locals?
Show answer
v is a double, so it occupies slots 0 and 1. n is in slot 2. The smallest max_locals is 3.
Exercise
Trace the operand stack for static int f(int a, int b) { return a * b + a; } called as f(2, 5). List the instructions and the stack after each one.
Show answer
The instructions are iload_0 [2], iload_1 [2, 5], imul [10], iload_0 [10, 2], iadd [12], ireturn. The method returns 12 and max_stack is 2.