Skip to content

InternalFieldTuple: cast by JSType instead of walking ClassInfo - #410

Merged
Jarred-Sumner merged 1 commit into
mainfrom
farm/d28c9e5d/internal-field-tuple-fast-cast
Aug 12, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
farm/d28c9e5d/internal-field-tuple-fast-cast

Conversation

@robobun

@robobun robobun commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

InternalFieldTuple has its own JSType (InternalFieldTupleType) but is not in FOR_EACH_JS_DYNAMIC_CAST_JS_TYPE_OVERLOAD, so dynamicDowncast<InternalFieldTuple> falls back to JSCell::inherits(): decode the StructureID, load the Structure, load its ClassInfo, then walk parentClass until it hits InternalFieldTuple::s_info or null. For the common case (the value is not a tuple) that is the full walk. The cast is on the promise reaction path: AsyncContextSwapScope::unwrapContextTuple (runtime/AsyncContextSwapScope.h) runs it for every reaction job in JSMicrotask.cpp (AsyncFunctionResume, then reactions, async generator steps, finally jobs) and in Interpreter.cpp, so every await resumption in Bun pays for it.

Change

  • JSCast.h: add macro(InternalFieldTuple, JSType::InternalFieldTupleType, JSType::InternalFieldTupleType) to the forward-declared overload list, so the cast is a compare of the type byte in the cell header.
  • InternalFieldTuple.h: the class is final, and a comment says why InternalFieldTupleType has to stay exclusive to it. The ctor section becomes private since nothing can derive any more.
  • InternalFieldTuple::create(vm, structure, a, b) constructs the cell and stores a and b directly instead of calling create(vm, structure) first, which stored undefined into both fields and then overwrote them (four barriered stores per tuple instead of two). create(vm, structure) still initialises both fields to undefined.

Why the JSType mapping is exact

In this tree InternalFieldTupleType is only used by InternalFieldTuple::createStructure, nothing derives from InternalFieldTuple, and every create() call site (here and in Bun) passes JSGlobalObject::internalFieldTupleStructure(), which comes from that createStructure. inheritsJSTypeImpl asserts canCast == inheritsSlow(info()) on every cast in debug builds, so a future violation would fail loudly in Bun's debug/ASAN lanes.

Bun itself has two classes (ErrorCodeCache, InternalModuleRegistry) that reuse InternalFieldTupleType for their own structures. Neither is ever handed to a site that casts to InternalFieldTuple, but with this change they would pass the cast, so the Bun PR that bumps to this commit switches them to ObjectType (what Bun's other internal-field objects already use).

Verification

Compiled Bun's seven translation units that create, dynamicDowncast or uncheckedDowncast InternalFieldTuple (AsyncContextFrame.cpp, JSSQLStatement.cpp, ReadableStreamOperations.cpp, JSReadRequest.cpp, NodeHTTP.cpp, ErrorCode.cpp, InternalModuleRegistry.cpp) against these headers with Bun's debug flags (ASSERT_ENABLED=1, so the asserting path is instantiated too); all compile. InheritsTraits<InternalFieldTuple>::typeRange is now engaged (static_asserted in a probe TU; the same assert fails on the unmodified headers).

-O2 codegen of dynamicDowncast<InternalFieldTuple>(JSValue) before and after, x86_64:

before (ClassInfo walk)
        movl    (%rdi), %ecx                       ; StructureID
        andl    $-2, %ecx
        movq    g_config+1808(%rip), %rdx          ; structure heap base
        movq    80(%rdx,%rcx), %rcx                ; Structure::m_classInfo
        ...
        cmpq    $_ZN3JSC18InternalFieldTuple6s_infoE, %rcx
        ...
.LBB0_4:                                           ; parentClass loop
        movq    16(%rcx), %rcx
        testq   %rcx, %rcx
        cmpq    $_ZN3JSC18InternalFieldTuple6s_infoE, %rcx
        je      .LBB0_6
        testq   %rcx, %rcx
        jne     .LBB0_4
after (JSType compare)
        cmpb    $97, 5(%rdi)                       ; JSCell::m_type == InternalFieldTupleType
        jne     .LBB0_4

Bun's test suite will run against this PR's preview tarballs from the Bun bump PR; I will link it here.

Side note (not changed here)

JSType.h maps InternalFieldTupleType to SpecCellOther, but the class is a JSObject, and every comparable JSC internal-field type (and the default for unlisted types in speculatedTypeMapping) is SpecObjectOther. Bun's builtins only ever use these values as @getInternalField / @putInternalField operands, so nothing observes it today; flagging it in case we want to fix it separately.

InternalFieldTuple has had its own JSType (InternalFieldTupleType) but was
not listed in FOR_EACH_JS_DYNAMIC_CAST_JS_TYPE_OVERLOAD, so every
dynamicDowncast<InternalFieldTuple> went through JSCell::inherits: decode
the StructureID, load the Structure, load its ClassInfo, then chase
parentClass until InternalFieldTuple::s_info or null. The non-tuple case,
which is the common one, walks the whole chain. This cast sits on the
promise reaction / await resumption path (AsyncContextSwapScope::
unwrapContextTuple, used by the JSMicrotask.cpp jobs and
Interpreter.cpp), so every reaction paid for it.

Add the overload so the cast becomes a compare of the type byte in the
cell header. Every InternalFieldTuple is created with the Structure from
InternalFieldTuple::createStructure, which is the only place JSC uses
InternalFieldTupleType, so the JSType identifies the class exactly; the
class is now final to keep it that way.

While here, make create(vm, structure, a, b) construct the cell and
store a and b directly instead of going through create(vm, structure),
which stored undefined into both fields first (four barriered stores
per tuple instead of two). create(vm, structure) keeps its behaviour of
initialising both fields to undefined.
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 56d15c4d-0b08-426a-a6b4-7c48f24dc93f

📥 Commits

Reviewing files that changed from the base of the PR and between 7b76394 and 7f4c4d7.

📒 Files selected for processing (2)
  • Source/JavaScriptCore/runtime/InternalFieldTuple.h
  • Source/JavaScriptCore/runtime/JSCast.h

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

robobun added a commit to oven-sh/bun that referenced this pull request Aug 12, 2026
…leType

Both classes copied their Structure setup from InternalFieldTuple, including
its JSType. oven-sh/WebKit#410 makes dynamicDowncast<InternalFieldTuple>
check that JSType instead of walking ClassInfo, which requires the type to
mean InternalFieldTuple and nothing else. Create these two structures with
ObjectType instead, which is what the other internal-field objects in this
directory (JSNextTickQueue, JSSocketHandlers, ModuleLoader, BunStreamSource)
already use. Neither object is ever handed to a site that casts to
InternalFieldTuple, so nothing observable changes; this keeps the JSType
mapping exact before the WebKit bump lands.

@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.

LGTM — mechanical addition to the JSType cast overload list plus a small create() cleanup.

What was reviewed:

  • Confirmed InternalFieldTupleType is exclusive to InternalFieldTuple::createStructure in this tree; final now enforces no subclassing.
  • protected → private is safe: DECLARE_VISIT_CHILDREN_WITH_MODIFIER resets access internally, and finishCreation/ctor are only used by the in-class create().
  • create() refactor is behaviorally identical (DECLARE_DEFAULT_FINISH_CREATION does not touch internal fields), just drops the two redundant barriered stores.
Extended reasoning...

Overview

Two-file header-only change. JSCast.h gains one line adding InternalFieldTuple to FOR_EACH_JS_DYNAMIC_CAST_JS_TYPE_OVERLOAD_FORWARD_DECLARED, so InheritsTraits<InternalFieldTuple> is specialized to a single JSType byte compare instead of the generic ClassInfo chain walk. InternalFieldTuple.h marks the class final, moves the ctor block to private, adds a comment tying InternalFieldTupleType exclusivity to the cast, and inverts the two create overloads so the 4-arg form does the allocation and the 2-arg form delegates with jsUndefined().

Security risks

None. This is a type-dispatch optimization on an internal Bun-only helper class. The JSType-based cast path already carries a debug ASSERT(canCast == inheritsSlow(info())) in inheritsJSTypeImpl, so any future structure that reused InternalFieldTupleType without inheriting the class would trip debug/ASAN builds. Grep confirms the only TypeInfo(InternalFieldTupleType, ...) in this repo is InternalFieldTuple::createStructure (InternalFieldTuple.cpp:21), and no class derives from InternalFieldTuple. The author correctly flagged the two Bun-side classes that borrow this JSType and is fixing them in the paired Bun bump PR; that is outside this repo.

Level of scrutiny

Low-to-moderate. The pattern is identical to the ~50 other entries in the same macro list (e.g. JSGenerator, JSArrayIterator, WebAssemblyGCObjectBase on the line directly above). The create refactor is a trivial reordering — I checked DECLARE_DEFAULT_FINISH_CREATION (JSCell.h:81) and it only calls Base::finishCreation plus a debug assert, so writing a/b after it (rather than undefined then a/b) is equivalent. The access-specifier change from protected to private looked like it could affect visitChildren, but DECLARE_VISIT_CHILDREN_WITH_MODIFIER (SlotVisitorMacros.h:61) explicitly emits private:/public: labels internally, so visitChildren stays public regardless and CREATE_METHOD_TABLE in the .cpp is unaffected.

Other factors

The PR description includes before/after -O2 disassembly and a compile check against Bun's consuming TUs with ASSERT_ENABLED=1. No prior human reviews or outstanding comments on the timeline (only a rate-limited CodeRabbit placeholder). Small, self-contained, and follows an established pattern with a debug safety net.

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
7f4c4d72 autobuild-preview-pr-410-7f4c4d72 2026-08-12 04:13:06 UTC

@robobun

robobun commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

The Bun side of this is oven-sh/bun#48869. Bun's pin moved past this commit through another bump, without the two ObjectType lines that the description mentions, so ErrorCodeCache and InternalModuleRegistry still have InternalFieldTupleType on Bun's main. That PR changes them, and ActiveSpySet, which has JSWeakSetType in the same way.

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.

3 participants