Skip to content

Commit da92b6c

Browse files
committed
perf(runtime): store instance fields in the object and share one slot for monitor, hash and VM data, cutting a small object from 107 to 32 bytes (#102)
1 parent 079ce11 commit da92b6c

21 files changed

Lines changed: 630 additions & 220 deletions

‎AGENTS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,12 @@ Node, which is how the tests run.
107107
- **PendingThrow**: thrown by JS code to raise a new Java exception; the
108108
interpreter builds it with its real constructor.
109109
- **mirror**: the `java.lang.Class` object of a runtime class.
110+
- **object layout**: a Java object is a JS object with `cls`, `s` (identity
111+
hash, monitor and VM data, once it has any) and its instance fields as
112+
properties `f0`, `f1`, ... (`JField.key`). Classes whose fields have the same
113+
kinds share one generated constructor, so one JS shape. An object whose class
114+
has a finalizer keeps its fields in a second object, `st`, that the Finalizer
115+
also holds.
110116
- **handle**: how the VM names a Java object it gave to JS; the page's proxy
111117
holds it until the proxy is dropped.
112118
- **wire value**: a value as it crosses between the VM and JS (library.ts).

‎src/interp.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -332,7 +332,19 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
332332
if (fld === undefined) { f.pc = ipc; f.sp = sp; return budget; }
333333
o = stack[sp - 1];
334334
if (o === null) npe();
335-
stack[sp - 1] = o.f[fld.slot];
335+
// a named load per slot: the engine caches each by shape, which a computed key cannot
336+
switch (fld.slot) {
337+
case 0: v = o.f0; break;
338+
case 1: v = o.f1; break;
339+
case 2: v = o.f2; break;
340+
case 3: v = o.f3; break;
341+
case 4: v = o.f4; break;
342+
case 5: v = o.f5; break;
343+
case 6: v = o.f6; break;
344+
case 7: v = o.f7; break;
345+
default: v = o[fld.key];
346+
}
347+
stack[sp - 1] = v;
336348
if (fld.wide) stack[sp++] = undefined;
337349
pc += 3;
338350
break;
@@ -345,7 +357,17 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
345357
v = stack[--sp];
346358
o = stack[--sp];
347359
if (o === null) npe();
348-
o.f[fld.slot] = v;
360+
switch (fld.slot) {
361+
case 0: o.f0 = v; break;
362+
case 1: o.f1 = v; break;
363+
case 2: o.f2 = v; break;
364+
case 3: o.f3 = v; break;
365+
case 4: o.f4 = v; break;
366+
case 5: o.f5 = v; break;
367+
case 6: o.f6 = v; break;
368+
case 7: o.f7 = v; break;
369+
default: o[fld.key] = v;
370+
}
349371
pc += 3;
350372
break;
351373
}
@@ -412,7 +434,7 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
412434
if (c === undefined) { f.pc = ipc; f.sp = sp; return budget; }
413435
if (c.state !== INITIALIZED && !vm.initialize(t, c)) { f.pc = ipc; f.sp = sp; return budget; }
414436
if (c.access & 0x0600) throw new PendingThrow("java/lang/InstantiationError", c.javaName);
415-
const o = new JObject(c, c.template.slice());
437+
const o = new c.ctor(c);
416438
if (c.finalizable) registerFinalizer(vm, o);
417439
stack[sp++] = o;
418440
pc += 3;

‎src/jit.ts‎

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@
1515
// interpreted call.
1616

1717
import { cpB, cpTag, cpValue, Tag, utf8 } from "./classfile.ts";
18-
import {
19-
ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin,
20-
} from "./runtime.ts";
18+
import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, dataOf } from "./runtime.ts";
2119
import { memberTarget } from "./natives/invoke.ts";
2220
import { concatStrings } from "./natives/strings.ts";
2321
import { Frame, JavaThrow, NativeFrame, PendingThrow, fromNative } from "./thread.ts";
@@ -76,7 +74,7 @@ export function restoreJit(vm: JVM, m: JMethod, code: SavedJit) {
7674

7775
// A constant of compiled code that holds a class another loader can drop.
7876
function namesUnloadable(v: unknown, caller: JClass): boolean {
79-
const c = v instanceof JClass ? v : v instanceof JMethod || v instanceof JField ? v.cls : v instanceof JObject ? (v.x instanceof JClass ? v.x : v.cls) : null;
77+
const c = v instanceof JClass ? v : v instanceof JMethod || v instanceof JField ? v.cls : v instanceof JObject ? (dataOf(v) instanceof JClass ? dataOf(v) : v.cls) : null;
8078
return c !== null && c !== caller && c.unloadable && (c.hidden || c.loader !== caller.loader);
8179
}
8280

@@ -1021,11 +1019,11 @@ function insnCode(g: Gen, b: Body, pc: number) {
10211019
case 0xb4: case 0xb5: {
10221020
const fld = cls.rcp[idx2] as JField | undefined;
10231021
if (!fld) { emit(slow(pc, d)); break; }
1024-
if (op === 0xb4) emit(`${b.nn.has(d - 1) ? "" : `if(${top()}===null)np(${pc});`}${top()}=${top()}.f[${fld.slot}];`);
1022+
if (op === 0xb4) emit(`${b.nn.has(d - 1) ? "" : `if(${top()}===null)np(${pc});`}${top()}=${top()}.${fld.key};`);
10251023
else {
10261024
const k = fld.wide ? 2 : 1;
10271025
const obj = top(k);
1028-
emit(`${b.nn.has(d - 1 - k) ? "" : `if(${obj}===null)np(${pc});`}${obj}.f[${fld.slot}]=${fld.wide ? top(1) : top()};`);
1026+
emit(`${b.nn.has(d - 1 - k) ? "" : `if(${obj}===null)np(${pc});`}${obj}.${fld.key}=${fld.wide ? top(1) : top()};`);
10291027
}
10301028
break;
10311029
}
@@ -1055,7 +1053,7 @@ function insnCode(g: Gen, b: Body, pc: number) {
10551053
}
10561054
const k = cls.rcp[idx2] as JClass | undefined;
10571055
if (!k || k.state !== INITIALIZED || k.access & 0x0600 || k.finalizable) { emit(slow(pc, d)); break; }
1058-
emit(`${S(d)}=new rt.JObject(${K(k)},${K(k)}.template.slice());`);
1056+
emit(`${S(d)}=new ${K(k)}.ctor(${K(k)});`);
10591057
break;
10601058
}
10611059
case 0xbc: {
@@ -1088,11 +1086,12 @@ function insnCode(g: Gen, b: Body, pc: number) {
10881086
}
10891087
case 0xc2:
10901088
if (region) throw new NoInline();
1091-
emit(`if(${top()}===null)np(${pc});if(!vm.monitorEnter(t,${top()}))${g.exit(pc, d, EXIT_SUSPEND)}`);
1089+
// an idle or own monitor is taken inline, so the object's shape is seen by this site alone
1090+
emit(`if(${top()}===null)np(${pc});{const mo=${top()}.s;if(mo!==null&&typeof mo==="object"&&mo.owner===null&&t.mounted===null&&!t.blockedOnMonitor){mo.owner=t;mo.count=1}else if(mo!==null&&typeof mo==="object"&&mo.owner===t)mo.count++;else if(!vm.monitorEnter(t,${top()}))${g.exit(pc, d, EXIT_SUSPEND)}}`);
10921091
break;
10931092
case 0xc3:
10941093
if (region) throw new NoInline();
1095-
emit(`if(${top()}===null)np(${pc});vm.monitorExit(t,${top()});`);
1094+
emit(`if(${top()}===null)np(${pc});{const mo=${top()}.s;if(mo!==null&&typeof mo==="object"&&mo.owner===t){if(mo.count>1)mo.count--;else if(mo.entry===null&&t.mounted===null){mo.owner=null;mo.count=0}else vm.monitorExit(t,${top()})}else vm.monitorExit(t,${top()})}`);
10961095
break;
10971096
case 0xc4: {
10981097
const wop = c[pc + 1], i = u16(c, pc + 2);
@@ -1190,7 +1189,7 @@ function numLit(v: number): string {
11901189

11911190
// Bodies that can be inlined at a call site: they neither call nor throw.
11921191
type Trivial =
1193-
| { kind: "empty" } | { kind: "get"; slot: number } | { kind: "set"; slot: number } | { kind: "const"; value: string }
1192+
| { kind: "empty" } | { kind: "get"; key: string } | { kind: "set"; key: string } | { kind: "const"; value: string }
11941193
| { kind: "expr"; build: (args: string[]) => string };
11951194

11961195
// Pure arithmetic on parameters, as one JS expression, or null. Only
@@ -1219,7 +1218,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null {
12191218
const c = code.code;
12201219
if (c.length > 32 || code.handlers.length > 0) return null;
12211220
// the expression is built from tokens: ["arg", slot] refers to a parameter
1222-
type Tok = string | ["arg", number] | ["field", number, number];
1221+
type Tok = string | ["arg", number] | ["field", number, string];
12231222
const stack: Tok[][] = [];
12241223
// negative literals in parentheses, so "a - -5" cannot become "a--5"
12251224
const lit = (s: string): Tok[] => [s.startsWith("-") ? `(${s})` : s];
@@ -1249,7 +1248,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null {
12491248
const a = stack.pop();
12501249
const fld = m.cls.rcp[(c[pc + 1] << 8) | c[pc + 2]] as JField | undefined;
12511250
if (!a || !fld || a.length !== 1 || !Array.isArray(a[0]) || a[0][0] !== "arg" || a[0][1] !== 0) return null;
1252-
push = [["field", 0, fld.slot]];
1251+
push = [["field", 0, fld.key]];
12531252
len = 3;
12541253
} else if (op >= 0xac && op <= 0xb0) {
12551254
if (pc + 1 !== c.length || stack.length !== 1) return null;
@@ -1264,7 +1263,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null {
12641263
function render(toks: Tok[], args: string[]): string {
12651264
return toks.map((x: any) => {
12661265
if (typeof x === "string") return x;
1267-
if (Array.isArray(x)) return x[0] === "arg" ? args[x[1]] : `${args[x[1]]}.f[${x[2]}]`;
1266+
if (Array.isArray(x)) return x[0] === "arg" ? args[x[1]] : `${args[x[1]]}.${x[2]}`;
12681267
if (x.op) return x.op(render(x.a, args), render(x.b, args));
12691268
return x.op1(render(x.a, args));
12701269
}).join("");
@@ -1286,12 +1285,12 @@ function trivialBody(m: JMethod): Trivial | null {
12861285
// aload_0 getfield xreturn
12871286
if (c.length === 5 && c[1] === 0xb4 && c[4] >= 0xac && c[4] <= 0xb0) {
12881287
const f = field();
1289-
return f ? { kind: "get", slot: f.slot } : null;
1288+
return f ? { kind: "get", key: f.key } : null;
12901289
}
12911290
// aload_0 xload_1 putfield return
12921291
if (c.length === 6 && [0x1b, 0x1f, 0x23, 0x27, 0x2b].includes(c[1]) && c[2] === 0xb5 && c[5] === 0xb1) {
12931292
const f = m.cls.rcp[(c[3] << 8) | c[4]] as JField | undefined;
1294-
return f ? { kind: "set", slot: f.slot } : null;
1293+
return f ? { kind: "set", key: f.key } : null;
12951294
}
12961295
const build = leafExpr(m);
12971296
return build ? { kind: "expr", build } : null;
@@ -1302,8 +1301,8 @@ function genInline(body: Trivial, res: string, args: string[], pc: number, check
13021301
switch (body.kind) {
13031302
case "empty": return nullCheck;
13041303
case "const": return `${nullCheck}${res}=${body.value};`;
1305-
case "get": return `${nullCheck}${res}=${args[0]}.f[${body.slot}];`;
1306-
case "set": return `${nullCheck}${args[0]}.f[${body.slot}]=${args[1]};`;
1304+
case "get": return `${nullCheck}${res}=${args[0]}.${body.key};`;
1305+
case "set": return `${nullCheck}${args[0]}.${body.key}=${args[1]};`;
13071306
case "expr": return `${nullCheck}${res}=${body.build(args)};`;
13081307
}
13091308
}

0 commit comments

Comments
 (0)