Skip to content

[JSC] Fix BytecodeOptimizer abort when jump offsets settle one pass before the forced widening - #807

Merged
dylan-conway merged 5 commits into
mainfrom
robobun/4e01407e/bytecode-optimizer-emit-relaxation
Oct 22, 2026
Merged

dylan-conway merged 5 commits into
mainfrom
robobun/4e01407e/bytecode-optimizer-emit-relaxation

Conversation

@robobun

@robobun robobun commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related to oven-sh/bun#44926

Problem

  • bun build --bytecode aborts on @google-cloud/tasks: ASSERTION FAILED: !offsetsChanged in BytecodeOptimizerAccess::emit() (bytecode/BytecodeOptimizer.cpp:2075). Other functions fail as ASSERTION FAILED: delta (line 1965) for the same reason.
  • emit() re-emits the stream until a pass repeats the previous pass's offsets, then runs one more pass and asserts that nothing moved. At iteration 16 it also forces every branch to Wide32. When offsets settle at iteration 15, the extra pass is iteration 16, so the forced widening runs in it and the offsets move.

Fix

  • emit() keeps the pass that repeats the previous pass's offsets. Every jump in it was computed from final offsets: a forward target has the previous pass's offset, a backward target this pass's. The extra pass and finalPass are gone.
  • The extra pass also asserted that no delta is zero. With final offsets a zero delta is a jump to itself, so Mapper asserts &targetInsn != insn.
  • The emitted bytecode does not change. minimumSize and newOffset are the only state a pass inherits (restartForReemit() resets the metadata and value profile counters), so the extra pass repeated the bytes of the pass before it.

Test

  • JSTests/stress/bytecode-optimizer-jump-relaxation.js generates functions in which each branch jumps over some padding and the next branch. With the right padding a branch's offset fits in 8 bits only until the next branch is widened, so each pass widens one more branch and the number of branches sets the number of passes.
  • It sweeps 10 to 20 branches and 33 to 45 padding statements. On main the function with 15 branches and 39 padding statements aborts. Functions with more branches go through the forced widening.
  • It runs in one configuration. With --useConcurrentJIT=0 --jitPolicyScale=0 it takes 1.58 s, over the 200 ms rule.

Verified

Release jsc with assertions, main at 5e3554fa, with and without this change:

  • Under run-jsc-stress-tests the new test fails on main (ASSERTION FAILED: !offsetsChanged) and passes here in 61 ms. All 38 runs of the 19 bytecode-optimizer-*.js files pass.
  • The bytecode cache files (--useBytecodeOptimizer=1 --diskCachePath) are byte-identical for 5,845 programs (5,984 cache files, 191.7 MB): 845 files of JSTests/stress, 30 JetStream2 programs, 18 bytecode-optimizer-*.js files, and 4,952 generated programs with branches at the 8-bit and 16-bit offset boundaries. No program differs.
  • 50 more of the generated programs abort on main (41 with !offsetsChanged, 9 with delta). With this change each exits 0 and prints what it prints with the optimizer off.

Background

  • The bytecode optimizer (fork only) rewrites a code block after copy propagation, scope caching and dead code removal. emit() writes the new stream. An instruction's size depends on its operands, and a jump operand is a delta that depends on the sizes in between, so sizes are found by relaxation: each pass emits at the smallest size that fits and minimumSize only grows.

Alternative

  • if (iteration == 16 && !finalPass) also stops the abort, but keeps a second emission of every function whose only job is to assert.

Downsides

  • None found.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this PR and didn't find any bugs. Because it changes which relaxation pass's stream every optimized function ships (fork-only bytecode optimizer, CODEOWNER-covered JSC path), a human look would still be worthwhile.

What was reviewed:

  • The keep-the-settled-pass argument in emit(): all live insns refresh newOffset every pass, so when offsetsChanged is false the forward targets' previous-pass offsets equal this pass's, and backward targets already read this pass's — deltas are exact.
  • First-pass case: newOffset starts at UINT_MAX, so pass 0 always reports changed offsets and the oldOffset fallback can never be the kept stream.
  • RELEASE_ASSERT(!usedPlaceholder) on a self-targeting jump: same abort the old RELEASE_ASSERT(delta) final pass already had, not a new failure mode.
  • Post-loop consumers (switch jump tables, handlers, expression info) read newOffset, which now belongs to the same pass as newWriter — consistent, previously it was the extra pass in both cases.
Extended reasoning...

The change touches Source/JavaScriptCore/bytecode/BytecodeOptimizer.cpp (the Mapper struct and the relaxation loop in BytecodeOptimizerAccess::emit(), roughly lines 1922-2084) and adds one stress test under JSTests/stress. It removes the separate final emission pass and replaces the finalPass flag with a per-pass usedPlaceholder flag asserted on the settled pass. No security-sensitive surface (no auth, injection, or data exposure) is involved. The diff is small and the correctness argument holds on reading, but it alters the emitted stream selection for every function the fork-only bytecode optimizer processes and the paths are covered by CODEOWNERS (/Source/JavaScriptCore, /JSTests), so a human review is appropriate rather than auto-approval.

@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 9538c24e-ae85-4695-bb8c-1f07472bfb16
📥 Commits

Reviewing files that changed from the base of the PR and between 4b724e9 and 55feeca.

📒 Files selected for processing: 2
  • JSTests/stress/bytecode-optimizer-relaxation-settles-at-forced-widening.js
  • Source/JavaScriptCore/bytecode/BytecodeOptimizer.cpp

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

Walkthrough

Bytecode emission now tracks placeholder jump deltas and continues relaxation until offsets are unchanged and the pass uses no placeholder. A new stress test exercises conversion and serialization with the optimizer enabled under two JIT configurations.

Changes

Jump Relaxation

Layer / File(s) Summary
Track placeholder deltas during relaxation
Source/JavaScriptCore/bytecode/BytecodeOptimizer.cpp
The mapper records when it substitutes 1 for a zero jump delta. Emission accepts a pass only when offsets are unchanged and no placeholder was used.
Exercise forced widening in optimizer stress test
JSTests/stress/bytecode-optimizer-relaxation-settles-at-forced-widening.js
The test runs with two optimizer configurations. It checks conversion and serialization for three inputs, including nested defaults.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 55fee

The change fixes an optimizer assertion crash during bytecode builds and adds a regression test. No actionable merge-blocking risk remains in the supplied evidence.

Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the primary fix: preventing BytecodeOptimizer aborts when jump offsets settle before forced widening.
Description check Passed The description is detailed and directly covers the problem, fix, rationale, tests, verification, and affected behavior. It does not include the template's Bugzilla URL, reviewer line, or an explicit …
Full details: Description check

Explanation

The description is detailed and directly covers the problem, fix, rationale, tests, verification, and affected behavior. It does not include the template's Bugzilla URL, reviewer line, or an explicit changed-file/function list, but the core required information is present.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Preview build of e9db6a8: autobuild-preview-pr-807-e9db6a8e

The emit() relaxation loop re-emits the instruction stream until a pass
produces the same offsets as the pass before it, then ran one more pass
with exact jump deltas and asserted that the offsets did not move. At
iteration 16 the loop also forces every branch to Wide32 to cut short a
chain where each pass widens only one or two branches. When the layout
settled at exactly iteration 15, that forced widening ran on the extra
pass, every branch grew, and the assertion aborted the process.

A pass whose offsets match the previous pass's computed every jump delta
from exact offsets: forward targets read the previous pass's offset and
backward targets read this pass's. So that pass is the result, and the
extra pass is removed together with the finalPass state. Nothing runs
between the stability verdict and the stream it applies to.

The zero-delta placeholder stays for passes that still move. The kept
pass asserts that it did not need it, since a zero delta there would be
a jump to itself.

A stress test reduced from protobufjs-generated code settles at
iteration 15 on the old loop and aborted.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

@dylan-conway dylan-conway changed the title [JSC] BytecodeOptimizer keeps the first stable relaxation pass instead of re-emitting after the forced widening [JSC] Fix BytecodeOptimizer abort when jump offsets settle one pass before the forced widening Oct 22, 2026

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed the latest push (the self-jump assert and the rewritten sweep test) and found no bugs; because this changes which emission pass becomes the final bytecode stream and the paths are CODEOWNERS-covered (jsc-reviewers), a human look is still worthwhile.

What was reviewed:

  • The keep-first-stable-pass argument in emit(): a forward target reads the previous pass's offset and a backward target this pass's, so when offsets repeat every delta in the kept stream is exact; the first pass can never be kept since newOffset starts at UINT_MAX.
  • The new RELEASE_ASSERT(&targetInsn != insn): a self-targeting jump needs the whole loop body dead, and loop_hint/check_traps have no defs so eliminateDeadStores keeps them; the removed final-pass RELEASE_ASSERT(delta) would have fired on the same input, so this is not a new crash surface.
  • The test: padding 33..45 (op_not at 3 bytes each) brackets the 127-byte narrow jump limit and branches 10..20 cover stabilization on both sides of the iteration-16 forced widening. I could not measure whether the 143 new Function compilations stay under the 200 ms budget JSTests/README asks for in debug configurations.
Extended reasoning...

The diff touches Source/JavaScriptCore/bytecode/BytecodeOptimizer.cpp (the Bun-fork bytecode optimizer's jump-size relaxation loop in emit(), removing the extra finalPass emission and its Mapper flag, adding a self-jump RELEASE_ASSERT) and adds JSTests/stress/bytecode-optimizer-jump-relaxation.js. No security-sensitive surface such as auth, injection or data exposure is involved, but incorrect jump deltas in emitted bytecode would be a memory-safety-relevant miscompile, so the correctness argument matters. The argument checks out from the code and the self-jump assert is not a regression, but the changed paths are covered by .github/CODEOWNERS (jsc-reviewers), the change alters core bytecode emission, and the new test's runtime against the 200 ms budget could not be measured here, which decided defer over approve. One commit landed after the prior review, so this note is not redundant with it.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I re-reviewed the latest revision (self-jump assert replacing the placeholder tracking, and the rewritten sweep test) and found no bugs; since this is the emission path for every function compiled under the bytecode optimizer, a human look is still worthwhile.

What was reviewed:

  • Adopting the first pass whose offsets repeat the previous pass: forward jumps read the previous pass's newOffset, backward jumps this pass's, and both equal the final layout when offsetsChanged is false; newOffset starts at UINT_MAX, so iteration 0 can never be adopted and the oldOffset fallback never reaches the kept stream.
  • delta == 0 in the adopted pass: live instructions have strictly increasing offsets, so a zero delta there is only a jump to itself, which the new RELEASE_ASSERT(&targetInsn != insn) rejects (equivalent to the old final-pass RELEASE_ASSERT(delta)); dead-code removal skips instructions with no defs, so op_loop_hint stays between a for(;;); jmp and its target.
  • Test expectations: the pad-count parities for key 0, 1..branches-1, and branches match the label nesting the generator builds; the 200 ms budget and whether 15 branches / 39 padding still hits the pre-fix abort were not run here.
Extended reasoning...

The change removes the verification pass from the jump-size relaxation loop in BytecodeOptimizerAccess::emit() in Source/JavaScriptCore/bytecode/BytecodeOptimizer.cpp, replacing the finalPass flag and its two RELEASE_ASSERTs with a direct self-jump assert in Mapper::target(), and adds JSTests/stress/bytecode-optimizer-jump-relaxation.js. It touches no security-sensitive surface (no auth, injection, or data exposure), but it is the bytecode emission path for every function compiled with the optimizer, so a logic error would be a silent miscompile rather than a crash. The soundness argument (offsets strictly increasing among live instructions, forward targets read the previous pass) checks out on reading, and the bug hunt ran dry, but .github/CODEOWNERS covers Source/JavaScriptCore and JSTests, nothing could be executed in this session to confirm the test reproduces the abort on the base commit, and the PR has been revised twice since my last review, so a human confirmation is still worthwhile rather than an approval.

@dylan-conway
dylan-conway merged commit 5cfcac0 into main Oct 22, 2026
55 checks passed
dylan-conway added a commit to oven-sh/bun that referenced this pull request Oct 24, 2026
### What does this PR do?

Moves `WEBKIT_VERSION` from `5e3554face13` to `680ef47cec2c`, the head
of oven-sh/WebKit `main`. The `autobuild-680ef47c…` release is
published.

What the fork's `main` gained in that range:

- oven-sh/WebKit#889: merge of upstream
[`f59345e04a8d`](WebKit/WebKit@f59345e)
(2026-10-22). 193 upstream commits since `33ce3bf11a71`, 37 of them in
JavaScriptCore, WTF or bmalloc.
- oven-sh/WebKit#892: a completely full block that the allocator
stumbles on is recorded as allocated.
- oven-sh/WebKit#880: the control flow profiler counts the parts of a
loop header.
- oven-sh/WebKit#807: `BytecodeOptimizer` aborted when jump offsets
settled one pass before the forced widening.
- oven-sh/WebKit#881: CI only (sha256 for toolchain downloads, FreeBSD
14.4, which is what Bun already targets). The Android NDK is unchanged.

`JSType.h`, the WebCore bindings code generator and the release tarball
names did not change.

#### Changes in Bun besides the version

**BIGINT32 is gone upstream**
([`f59345e04a`](WebKit/WebKit@f59345e)).
It was never enabled (`USE_BIGINT32` was `0`), so none of this changes
behaviour, but Bun does not compile without it:

- `JSBigInt::makeHeapBigIntOrBigInt32(g, v)` → `JSBigInt::createFrom(g,
v)`, which is what it expanded to (`NodeSqlite.cpp`, `JSBuffer.cpp`,
`JSCTestingHelpers.cpp`). Every call site passes an `int64_t` or a
`uint64_t`, so the overload is exact.
- `JSValue::isBigInt32()` always returned `false`. Removed:
`JSC__JSValue__isBigInt32` and `JSValue::is_big_int32`, their uses in
`toBeEven` / `toBeOdd`, an `ASSERT` in `JSC__JSValue__asBigIntCompare`,
and the test bindgen emitted for a `bigint` that is not a cell.
- `tryConvertToBigInt32(bigInt)` → `bigInt` in
`SerializedScriptValue.cpp`.
- The `#if USE(BIGINT32)` blocks in `bindings.cpp`,
`SerializedScriptValue.cpp` and `napi.cpp`, which call functions that no
longer exist.
- The `JSGlobalObject*` of `JSC__JSValue__asBigIntCompare`, which only
one of those blocks read, and with it the `global` of
`JSValue::as_big_int_compare` and of the test runner's wrapper.

**Loop headers have basic blocks of their own** (oven-sh/WebKit#880):

- `JSInspectorProfiler.cpp` leaves out the blocks with
`m_isInLoopHeader`. V8 has no range for them, and what reads
`Profiler.takePreciseCoverage` is written for V8's ranges.
- `source-positions-corpus.ts`: the count of nine loop header lines.
`for (let i = 0; i < 3; i++) {` is 4, how often the condition ran, and
was 1.

Both are the same hunks as in #46534, so they merge cleanly with it.
`WEBKIT_VERSION` will conflict there: #46534 pins `e450c494a84f`, which
this contains.

**`test/bundler/bundler_bytecode_portable.test.ts`**: the snapshot.
Removing `op_is_big_int` renumbers the opcodes after it, so the
serialized bytecode changed on every platform. 24 hashes and 13 sizes of
`.jsc` payloads change, and no hash of the printed JavaScript.

**`test/js/bun/jsc/webkit-upgrade-f59345e04a.test.ts`** (new): pins five
of the engine changes below, like the files for the earlier syncs.

#### Other upstream changes that reach Bun

Checked against Bun's sources, no change needed:

- `numberToShortestStringBufferSize` is 39, was 34. Bun passes the
124-byte `NumberToStringBuffer`.
- `JSObject::forEachOwnIndexedProperty` lost its `JSGlobalObject*`,
`immutableButterflyToStringCache` moved from `Heap` to `VM`, the inline
parts of `HasOwnPropertyCache` moved to `HasOwnPropertyCacheInlines.h`,
the `swapCodeRefForDebugger` family moved to `NativeExecutable`. Bun
uses none of them.
- `JSBoundFunction::create` gained an overload that takes a
`SourceTaintedOrigin`. The one that takes a `SourceCode`, which Bun
calls, is still there.
- `SpecDataViewObject` is bit 49, was 50. Bun has no copy of
`SpeculatedType`.
- The bytecode cache key is a hash of the WebKit commit, so a cache
written before the opcodes were renumbered is not read.

Behaviour that changes with the engine:

- In the head of a `for`: a destructuring declaration without an
initializer is a SyntaxError, `let` is an identifier in sloppy code, and
`for await (async of` is allowed
([`926bafc4e`](WebKit/WebKit@926bafc4e)).
- An overwritten `length` of a sloppy arguments object is converted with
`ToLength`
([`7b1cfc54c`](WebKit/WebKit@7b1cfc54c)). `-1`
was 4294967295, so `Array.prototype.slice.call(arguments)` looped 2^32
times, and 2^32 and up were truncated.
- `Stopwatch::reset()` clears past run intervals
([`49902180d`](WebKit/WebKit@49902180d)), and
moving a `SamplingProfiler::StackTrace` keeps `stopwatchTimestamp`
([`b6c984205`](WebKit/WebKit@b6c984205)).
- DFG fixes: a promise resolved with itself was fulfilled with itself in
optimized code instead of rejected with a TypeError
([`b45f2446d`](WebKit/WebKit@b45f2446d)),
`op_has_private_name` is not compiled as `InById`
([`dd24421c8`](WebKit/WebKit@dd24421c8)).
- GC: leftover marks after the marking version wraps
([`e1a28d3cf`](WebKit/WebKit@e1a28d3cf)), a
heap's Collector threads stop when it shuts down
([`eaf0efa57`](WebKit/WebKit@eaf0efa57)).

### How did you verify your code works?

No local build. The first commit was built by CI
([#131689](https://buildkite.com/bun/bun/builds/131689)): all 13
`build-bun` jobs and the three `verify-baseline` jobs passed, so the
aarch64 allowlist stays as it is, and the only test that failed was the
bytecode snapshot, on all ten platforms that ran it.

With the `bun-linux-x64` binary of that build, and the one of `main` at
`a8fcd319` ([#131688](https://buildkite.com/bun/bun/builds/131688),
WebKit `5e3554face13`) as the baseline:

| | `main` | this PR |
| --- | --- | --- |
| `webkit-upgrade-f59345e04a.test.ts` | 0 of 5 pass | 5 of 5, also with
`BUN_JSC_useJIT=0` |
| `bundler_bytecode_portable.test.ts` | | 22 of 22 with the new
snapshot, 21 of 22 before |
| `source-positions.test.ts` | | 325 of 325 |
| `inspector-profiler.test.ts` | | 52 of 52 |

The snapshot was written by `--update-snapshots` on Linux x64. All 24
hashes are the ones in the CI logs of Windows x64, Linux aarch64 and
Linux x64 ASAN, and the 11 that the annotation shows are the same on all
ten platforms.

The second commit's Rust was checked with `cargo check -p bun_jsc -p
bun_runtime`; its C++ (one signature) is first compiled by CI.

Before the first build, by reading: the diff of every JavaScriptCore,
WTF and bmalloc header in the range, with each removed or changed name
searched for in Bun, and every `JSBigInt::` member Bun uses looked up in
the new `JSBigInt.h`.


---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants