react-nitro-hermes 0.0.1-alpha.8 → 0.0.1-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/hermes/CMakeLists.txt +874 -0
  2. package/hermes/android/HostObjectJniTest.cpp +178 -0
  3. package/hermes/android/build-logic/build.gradle.kts +31 -0
  4. package/hermes/android/build-logic/settings.gradle.kts +17 -0
  5. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/helpers/internal/SerializeHermesCompilerPackageJson.kt +33 -0
  6. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/plugins/internal/TestUtilsPlugin.kt +80 -0
  7. package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/tasks/internal/CustomExecTask.kt +46 -0
  8. package/hermes/android/build-logic/src/main/kotlin/publish.gradle.kts +82 -0
  9. package/hermes/android/build.gradle.kts +332 -0
  10. package/hermes/android/cppruntime/build.gradle +72 -0
  11. package/hermes/android/cppruntime/src/main/AndroidManifest.xml +2 -0
  12. package/hermes/android/cppruntime/src/main/cpp/CMakeLists.txt +8 -0
  13. package/hermes/android/cppruntime/src/main/cpp/stub.cpp +12 -0
  14. package/hermes/android/cross-compile/swift-libicu.patch +13 -0
  15. package/hermes/android/cross-compile/toolchain-android-arm-api13-gnustl.cmake +13 -0
  16. package/hermes/android/cross-compile/toolchain-android-arm-api15-gnustl.cmake +14 -0
  17. package/hermes/android/gradle/libs.versions.toml +30 -0
  18. package/hermes/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  19. package/hermes/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  20. package/hermes/android/gradle.properties +3 -0
  21. package/hermes/android/gradlew +248 -0
  22. package/hermes/android/gradlew.bat +93 -0
  23. package/hermes/android/intltest/build.gradle +147 -0
  24. package/hermes/android/intltest/java/com/facebook/hermes/test/CMakeLists.txt +45 -0
  25. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.cpp +68 -0
  26. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.h +44 -0
  27. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.java +45 -0
  28. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogueTestData.java +32 -0
  29. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesInstrumentationTest.java +150 -0
  30. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlAndroidTest.java +147 -0
  31. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlTest262.java +470 -0
  32. package/hermes/android/intltest/java/com/facebook/hermes/test/HermesRuntimeFactory.cpp +73 -0
  33. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.cpp +90 -0
  34. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.h +62 -0
  35. package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.java +155 -0
  36. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.cpp +48 -0
  37. package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.h +36 -0
  38. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoad.cpp +13 -0
  39. package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoadEpilogue.cpp +13 -0
  40. package/hermes/android/intltest/src/main/AndroidManifest.xml +2 -0
  41. package/hermes/android/ios-artifacts/build.gradle.kts +65 -0
  42. package/hermes/android/settings.gradle.kts +27 -0
  43. package/hermes/cmake/modules/Hermes.cmake +481 -0
  44. package/hermes/cmake/modules/Lit.cmake +96 -0
  45. package/hermes/doc/Branches.md +38 -0
  46. package/hermes/doc/BuildingAndRunning.md +121 -0
  47. package/hermes/doc/CodingStandards.md +112 -0
  48. package/hermes/doc/CrossCompilation.md +79 -0
  49. package/hermes/doc/Design.md +217 -0
  50. package/hermes/doc/Emscripten.md +156 -0
  51. package/hermes/doc/Features.md +143 -0
  52. package/hermes/doc/GCSafeCoding.md +563 -0
  53. package/hermes/doc/GenGC.md +300 -0
  54. package/hermes/doc/Hades.md +344 -0
  55. package/hermes/doc/HighLevelOptimizations.md +37 -0
  56. package/hermes/doc/IR.md +1306 -0
  57. package/hermes/doc/IntlAPIs.md +196 -0
  58. package/hermes/doc/JIT.md +999 -0
  59. package/hermes/doc/LazyEvalCompilation.md +84 -0
  60. package/hermes/doc/MemoryProfilers.md +316 -0
  61. package/hermes/doc/Modules.md +144 -0
  62. package/hermes/doc/Optimizer.md +83 -0
  63. package/hermes/doc/PerfProfiling.md +29 -0
  64. package/hermes/doc/ProhibitInvoke.md +329 -0
  65. package/hermes/doc/ReactNative.md +40 -0
  66. package/hermes/doc/ReactNativeIntegration.md +94 -0
  67. package/hermes/doc/RegExp.md +24 -0
  68. package/hermes/doc/SpecIncompat.md +85 -0
  69. package/hermes/doc/Strings.md +140 -0
  70. package/hermes/doc/TypedLanguage.md +432 -0
  71. package/hermes/doc/VM.md +174 -0
  72. package/hermes/doc/blog/2024-11-09-octane-benchmark-jit-progress.md +17 -0
  73. package/hermes/doc/blog/2024-12-19-static-hermes-update-dec-2024.md +47 -0
  74. package/hermes/doc/blog/2024-12-23-compiling-javascript-to-wasm.md +267 -0
  75. package/hermes/doc/blog/2025-06-09-jsi-runtime-data-apis.md +23 -0
  76. package/hermes/doc/blog/2025-07-15-static-h-performance-june-2025.md +18 -0
  77. package/hermes/doc/blog/2025-11-02-hermes-compilation-runtime-modes.md +23 -0
  78. package/hermes/doc/blog/2025-11-06-hermes-memory-modes.md +35 -0
  79. package/hermes/doc/blog/2025-11-24-json-parsing-performance.md +17 -0
  80. package/hermes/doc/blog/2025-12-02-iserialization.md +11 -0
  81. package/hermes/doc/blog/2025-12-12-new-way-to-contribute.md +68 -0
  82. package/hermes/doc/blog/2026-06-05-new-hermes-stable-release.md +51 -0
  83. package/hermes/doc/blog/README.md +25 -0
  84. package/hermes/doc/blog/images/2024-11-09-octane-pi3.jpeg +0 -0
  85. package/hermes/doc/blog/images/2024-11-09-octane-pi5.jpeg +0 -0
  86. package/hermes/doc/blog/images/2025-07-15-perf-hv32-interpreter.jpeg +0 -0
  87. package/hermes/doc/blog/images/2025-07-15-perf-hv32-jit.jpeg +0 -0
  88. package/hermes/doc/icu_license.txt +420 -0
  89. package/hermes/doc/img/heap_snapshot_retainers.png +0 -0
  90. package/hermes/doc/img/logo.svg +1 -0
  91. package/hermes/doc/img/object_captured_by_environment.png +0 -0
  92. package/hermes/doc/img/root_categories.png +0 -0
  93. package/hermes/doc/plans/ir-type/flow-type-system.md +324 -0
  94. package/hermes/doc/plans/ir-type/ir-type-system-v2-design.md +652 -0
  95. package/hermes/doc/plans/ir-type/ir-type-system.md +220 -0
  96. package/hermes/doc/plans/ir-type/ir-type-v2-implementation.md +1187 -0
  97. package/hermes/doc/plans/ir-type/memory.md +48 -0
  98. package/hermes/doc/plans/ir-type/phase1-steps.md +512 -0
  99. package/hermes/doc/plans/ir-type/progress.md +239 -0
  100. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-design.md +203 -0
  101. package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-results.md +71 -0
  102. package/hermes/doc/superpowers/plans/2026-07-28-worker-arraybuffer-input.md +597 -0
  103. package/hermes/doc/superpowers/plans/2026-08-18-jitemitter-split.md +1149 -0
  104. package/hermes/doc/superpowers/plans/2026-08-20-jit-type-asserts.md +969 -0
  105. package/hermes/doc/superpowers/plans/2026-08-23-jit-shared-compiler-driver.md +478 -0
  106. package/hermes/doc/superpowers/plans/2026-08-23-x86-64-jit-skeleton.md +797 -0
  107. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-arith.md +444 -0
  108. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-calls.md +261 -0
  109. package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-props.md +240 -0
  110. package/hermes/doc/superpowers/plans/2026-10-26-regexp-bytecode-sharing.md +2197 -0
  111. package/hermes/doc/superpowers/plans/2026-10-28-regexp-start-filter-and-exec-fast-paths.md +3981 -0
  112. package/hermes/doc/superpowers/specs/2026-07-28-worker-arraybuffer-input-design.md +206 -0
  113. package/hermes/doc/superpowers/specs/2026-08-18-jitemitter-split-design.md +530 -0
  114. package/hermes/doc/superpowers/specs/2026-08-20-jit-type-asserts-design.md +360 -0
  115. package/hermes/doc/superpowers/specs/2026-08-23-x86-64-jit-design.md +246 -0
  116. package/hermes/doc/superpowers/specs/2026-08-26-icu-free-normalize-design.md +355 -0
  117. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-convert-to-case-design.md +305 -0
  118. package/hermes/doc/superpowers/specs/2026-08-27-icu-free-locale-compare-design.md +429 -0
  119. package/hermes/doc/superpowers/specs/2026-08-29-icu-free-date-format-design.md +297 -0
  120. package/hermes/doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md +605 -0
  121. package/hermes/doc/superpowers/specs/2026-10-28-regexp-start-filter-and-exec-fast-paths-design.md +551 -0
  122. package/hermes/doc/typescript-stripping.md +90 -0
  123. package/hermes/external/CMakeLists.txt +20 -0
  124. package/hermes/utils/IntlGen/IntlGen.java +531 -0
  125. package/hermes/utils/bench_with_stats.py +827 -0
  126. package/hermes/utils/build-apple-framework.sh +323 -0
  127. package/hermes/utils/chrome_snapshot_parser.py +210 -0
  128. package/hermes/utils/cmake-dev-build.sh +18 -0
  129. package/hermes/utils/commons.sh +55 -0
  130. package/hermes/utils/dump-cpp-funcs.sh +3 -0
  131. package/hermes/utils/es5objects.js +198 -0
  132. package/hermes/utils/format.sh +145 -0
  133. package/hermes/utils/gen-promise-internal-bc.sh +66 -0
  134. package/hermes/utils/genUnicodeTable.py +2503 -0
  135. package/hermes/utils/hermes-lit/CMakeLists.txt +22 -0
  136. package/hermes/utils/hermes-lit/hermes-lit.in +15 -0
  137. package/hermes/utils/jit/README.md +134 -0
  138. package/hermes/utils/jit/jit-diff.sh +160 -0
  139. package/hermes/utils/jit/jit-dump.sh +193 -0
  140. package/hermes/utils/lit-expect-gen/generate.py +217 -0
  141. package/hermes/utils/promise/index.js +15 -0
  142. package/hermes/utils/promise/package.json +13 -0
  143. package/hermes/utils/promise/rollup.config.js +19 -0
  144. package/hermes/utils/promise/yarn.lock +247 -0
  145. package/hermes/utils/scripts/hermes/consts.js +26 -0
  146. package/hermes/utils/scripts/hermes/create-tarball.js +75 -0
  147. package/hermes/utils/scripts/hermes/get-hermes-version.js +57 -0
  148. package/hermes/utils/scripts/hermes/hermes-utils.js +122 -0
  149. package/hermes/utils/scripts/hermes/package.json +6 -0
  150. package/hermes/utils/scripts/hermes/prepare-artifacts.js +113 -0
  151. package/hermes/utils/scripts/hermes/publish-artifacts.js +109 -0
  152. package/hermes/utils/scripts/hermes/publish-npm.js +96 -0
  153. package/hermes/utils/scripts/hermes/scm-utils.js +41 -0
  154. package/hermes/utils/scripts/hermes/set-artifacts-version.js +64 -0
  155. package/hermes/utils/scripts/hermes/version-utils.js +98 -0
  156. package/hermes/utils/scripts/hermes/yarn.lock +240 -0
  157. package/hermes/utils/summarize_sizes.py +184 -0
  158. package/hermes/utils/symbolicate-nativecall-stats.py +112 -0
  159. package/hermes/utils/test_runner.py +13 -0
  160. package/hermes/utils/testsuite/README.facebook +3 -0
  161. package/hermes/utils/testsuite/README.md +69 -0
  162. package/hermes/utils/testsuite/cli.py +547 -0
  163. package/hermes/utils/testsuite/es_ast.py +337 -0
  164. package/hermes/utils/testsuite/external/LICENSE +28 -0
  165. package/hermes/utils/testsuite/external/README.facebook +8 -0
  166. package/hermes/utils/testsuite/external/__init__.py +0 -0
  167. package/hermes/utils/testsuite/external/_monkeyYaml.py +164 -0
  168. package/hermes/utils/testsuite/external/parse_test262.py +141 -0
  169. package/hermes/utils/testsuite/hermes.py +522 -0
  170. package/hermes/utils/testsuite/preprocess.py +365 -0
  171. package/hermes/utils/testsuite/progress.py +377 -0
  172. package/hermes/utils/testsuite/skiplist.json +4356 -0
  173. package/hermes/utils/testsuite/skiplist.py +270 -0
  174. package/hermes/utils/testsuite/test_run_defs.py +435 -0
  175. package/hermes/utils/testsuite/typing_defs.py +52 -0
  176. package/hermes/utils/testsuite/utils.py +214 -0
  177. package/hermes/utils/tidy.sh +22 -0
  178. package/hermes/utils/update-fbcode-hermes.sh +53 -0
  179. package/hermes/utils/updateErrorTest.py +193 -0
  180. package/hermes/utils/wasm-compile.sh +65 -0
  181. package/package.json +1 -1
@@ -0,0 +1,999 @@
1
+ # The Hermes JIT (arm64)
2
+
3
+ This document describes the architecture of the existing arm64 JIT, as a
4
+ reference for maintaining it and for porting it to x86-64. It was produced by
5
+ studying the code on branch `x86-jit` (based on `static_h`) and has been
6
+ revised for the 2026-08 refactor series (the `JitEmitter.cpp` file split,
7
+ thunk removal, capture-based slow paths, and encoding-fallback fixes). Source
8
+ references in the body are to the post-refactor tree; the findings appendix
9
+ deliberately keeps its references to the pre-fix revisions it reviewed.
10
+
11
+ ## Overview
12
+
13
+ The JIT is a simple, single-pass baseline compiler: it translates HBC bytecode
14
+ directly to native code, one instruction at a time, with no IR and no
15
+ scheduling. Its performance comes from:
16
+
17
+ - keeping frame registers in machine registers (a static "global" assignment
18
+ for number/non-pointer registers plus per-basic-block "local" temporaries),
19
+ - inline fast paths for the common cases (arithmetic on doubles, property
20
+ access through inline caches, young-gen bump allocation), with out-of-line
21
+ slow paths that call the same C runtime helpers the Static Hermes native
22
+ backend uses (`_sh_ljs_*`), and
23
+ - reusing the SH ABI: a JIT-compiled function is a drop-in replacement for a
24
+ bytecode CodeBlock, called via `JITCompiledFunctionPtr` =
25
+ `HermesValue (*)(Runtime *)`.
26
+
27
+ The machine-code emitter is [asmjit](https://asmjit.com) (vendored in
28
+ `external/asmjit`; the x86 backend is already present in the vendored copy).
29
+
30
+ ### Source layout
31
+
32
+ | File | Role |
33
+ |---|---|
34
+ | `include/hermes/VM/JIT/Config.h` | Decides `HERMESVM_JIT` from `HERMESVM_ALLOW_JIT` + platform. Requires arm64 and either no compressed pointers or a contiguous heap. On Apple platforms the JIT is additionally disabled *except* on macOS and Mac Catalyst, so arm64 macOS is a supported (and convenient) host for testing the JIT. |
35
+ | `include/hermes/VM/JIT/JIT.h` | Dispatches to the per-arch `JITContext`; provides a no-op `JITContext` when the JIT is disabled. Already contains an `#elif defined(__x86_64__)` branch expecting `hermes/VM/JIT/x86-64/JIT.h` (does not exist yet). |
36
+ | `include/hermes/VM/JIT/arm64/JIT.h` | Public `JITContext`: enablement, thresholds, `shouldCompile`/`compile`, counters, `markRoots`. |
37
+ | `lib/VM/JIT/JitCompiler.cpp` | `JITContext::Compiler`: per-opcode `emitXXX` methods that decode operands and forward to the `Emitter`. Drives BB-by-BB compilation. Arch-independent; compiled inside the arch namespace selected by `JitCurArch.h`. |
38
+ | `lib/VM/JIT/arm64/JIT.cpp` | `JITContext` housekeeping: construction, `setHCIdLimit`, `dumpCounters`, `markRoots`. |
39
+ | `lib/VM/JIT/arm64/JitEmitter.h` | The `Emitter` class definition: the FR/HWReg model, `TempRegAlloc`, the capture-based `SlowPath` class, and the full emitter method surface (which is effectively the porting contract). |
40
+ | `lib/VM/JIT/arm64/JitEmitter.cpp` | Emitter lifecycle: constructor, `enter`/`frameSetup`/`leave` (prologue/epilogue), `newBasicBlock`, the runtime-call plumbing (`callRuntime*`), slow-path/catch-table/RO-data emission, `initHCLazyIDMayAlloc`, `addToRuntime`. |
41
+ | `lib/VM/JIT/arm64/JitEmitter-regalloc.cpp` | The register-file engine: `getOrAllocFRIn*`, `movHW*`, sync/spill/free. |
42
+ | `lib/VM/JIT/arm64/JitEmitter-internal.{h,cpp}` | Shared emission helpers: the `emit_sh_ljs_*` tag/encoding helpers, `emit_load_from_base_offset`, the SHV decoder, `EMIT_RUNTIME_CALL*` macros (`.h`); cold non-member helpers, object/environment init, asmjit error handler and logger (`.cpp`). |
43
+ | `lib/VM/JIT/arm64/JitEmitter-{alloc,const,object,property,call,env,array,arith,control}.cpp` | The per-instruction emitters, split by topic: young-gen allocation; constant materialization; object construction; the property protocol (incl. `GetByIdImpl`); JS calls; environments/closures; arrays/iterators/arguments; arithmetic and comparisons; control flow, switches and throws. See `doc/specs/2026-08-18-jitemitter-split-design.md` for the split rationale and boundaries. |
44
+ | `lib/VM/JIT/arm64/JitImpl.h` | `JITContext::Impl`: the asmjit `JitRuntime` (owns executable memory), HC lazy-ID counter, and `usedHCs` root array. |
45
+ | `lib/VM/JIT/JitHandlers.{h,cpp}` | C++ helpers callable from emitted code that are JIT-specific (the generic ones are the `_sh_ljs_*` functions from the SH runtime). Arch-independent. |
46
+ | `include/hermes/VM/JIT/JitCounters.h` | The `JIT_COUNTERS` list and `JitCounter` enum. The counter array is ABI between the VM and emitted code; arch-independent. |
47
+ | `lib/VM/JIT/DiscoverBB.cpp` | Scans bytecode to find basic-block boundaries (branch targets, fallthroughs after branches, Catch, switch tables, exception handler targets). Arch-independent. |
48
+ | `lib/VM/JIT/RuntimeOffsets.h` | `offsetof` constants for fields the emitted code touches directly (Runtime, StackOverflowGuard, CodeBlock, JSFunction, HiddenClass, IdentifierTable, Hades young-gen fields...). Arch-independent. |
49
+ | `lib/VM/JIT/PerfJitDump.cpp` | Linux `perf` jitdump support. Arch-independent. |
50
+
51
+ ### Tiering / when compilation happens
52
+
53
+ `JITContext::shouldCompile()` is checked by the interpreter (a) when entering a
54
+ function body in `CASE(Call)`-style dispatch and (b) in `interpretFunction`
55
+ entry (`lib/VM/Interpreter.cpp` around lines 563 and 1279). A function is
56
+ compiled when its execution count reaches
57
+ `defaultExecThreshold_ >> (loopDepth * 2)` (default threshold 32, loop depth
58
+ capped at 3, so hot loops compile at count 0), unless `getDontJIT()` is set or
59
+ JIT is disabled. `forceJIT` compiles everything on first call.
60
+
61
+ Compilation failure paths:
62
+
63
+ - Unsupported instruction or asmjit error: the compiler `longjmp`s out
64
+ (`_sh_longjmp` on `errorJmpBuf_`), sets `setDontJIT(true)` on the CodeBlock
65
+ and returns nullptr (or `hermes_fatal` if `crashOnError`). The only
66
+ currently-unsupported opcode is `AsyncBreakCheck` (plus anything new that
67
+ hasn't been implemented).
68
+ - Memory limit (default 32 MB of emitted code): compilation succeeds or is
69
+ discarded, and the JIT disables itself globally (`enabled_ = false`).
70
+
71
+ Compiled code is never freed (the `JitRuntime` holds it for the lifetime of
72
+ the `JITContext`); consequently GC objects referenced by emitted code must be
73
+ permanently rooted (see "GC integration" below).
74
+
75
+ ## The Emitter
76
+
77
+ ### Frame register (FR) model
78
+
79
+ Bytecode operates on frame registers r0..rN. The JIT gives every FR a fixed
80
+ home slot in the VM register stack frame (`xFrame + (FirstLocal + i) * 8`),
81
+ and additionally may cache it in machine registers. Per FR
82
+ (`FRState` in `JitEmitter.h`):
83
+
84
+ - **globalReg**: a callee-saved register statically assigned for the whole
85
+ function in `Emitter::enter()`. The SHBC "number register count" and
86
+ "non-pointer register count" function header fields (computed by the
87
+ compiler's register allocator, which sorts number/non-pointer registers
88
+ first) determine eligibility: number FRs prefer VecD (d8–d15), non-pointer
89
+ FRs prefer GpX (x21–x28), overflowing into the other class while registers
90
+ remain. Pointer-typed FRs never get a global register (they must be visible
91
+ to the GC in the frame).
92
+ - **localGpX / localVecD**: temporary registers (caller-saved: x0–x15,
93
+ d0–d7/d16–d31) holding the value within the current basic block. Allocated
94
+ LRU (`TempRegAlloc` + `SimpleLRU`) with spilling.
95
+ - **Invariants** (documented at `FRState`): local regs, if any, hold the
96
+ latest value; a global reg holds the latest value iff `globalRegUpToDate`;
97
+ the frame slot holds the latest value iff `frameUpToDate`; "global reg stale
98
+ while frame fresh" is not a legal state.
99
+ - **Types**: `FRType` (Number / Bool / OtherNonPtr / Pointer and unions).
100
+ `globalType` holds for the whole function (from the register counts);
101
+ `localType` can be narrowed within a BB by emission (e.g. after `add` the
102
+ result is known Number) and is reset to `globalType` at BB entry. Known
103
+ types let later instructions skip tag checks — a wrong `localType`
104
+ assignment anywhere is a correctness bug elsewhere.
105
+
106
+ Key operations: `getOrAllocFRInGpX/InVecD/InAnyReg(fr, load)` (get a register
107
+ holding the FR, optionally loading the current value), `frUpdatedWithHW`
108
+ (declare that a register now holds the FR's new value), `syncAllFRTempExcept`
109
+ + `freeAllFRTempExcept` (spill/drop all temps — required before any C++ call
110
+ since temps are caller-saved), `syncToFrame` (make the memory slot valid so
111
+ its address can be passed to a helper), `syncFrameOutParam` (a helper wrote
112
+ the frame slot in memory; reload global reg from it).
113
+
114
+ At every basic-block boundary (`newBasicBlock`) all temps are synced and
115
+ freed, so cross-BB state lives only in the frame and global regs. Note the
116
+ subtlety at `newBasicBlock`: for FRs with a global reg, `frameUpToDate` is
117
+ reset to false (the global reg is the canonical copy); the code relies on
118
+ BB-entry state being consistent regardless of predecessor.
119
+
120
+ ### Machine register convention (arm64)
121
+
122
+ - x19 = `xRuntime` (Runtime*), x20 = `xFrame` (current frame base), both saved
123
+ in the prologue.
124
+ - x21 doubles as the return-value stash: `ret()` moves the FR into x21, jumps
125
+ to the shared `leave` label, which moves x21 → x0 (x21 is always saved even
126
+ if no FR global uses it).
127
+ - x0–x15: temporaries / argument registers for helper calls. x16/x17 are
128
+ scratch *outside the allocator's domain*: call-target and IP
129
+ materialization, and the frame-offset fallback in `_loadFrame`/
130
+ `_storeFrame` when a slot offset does not encode. Any future
131
+ emitted-code instrumentation (e.g. the type-assert design) should use
132
+ these, never `allocTempGpX`, to keep assert builds allocation-identical.
133
+ - Helper calls use the standard AAPCS64 ABI; emitted code passes Runtime* in
134
+ x0, usually `xFrame` or FR addresses (`loadFrameAddr`) as pointer args.
135
+
136
+ ### Function prologue (`enter` → `frameSetup`)
137
+
138
+ Native stack layout (grows down): optional `SHJmpBuf` + saved `SHLocals*`
139
+ (only if the function has an exception table), then saved x19..x2x pairs,
140
+ saved d8..d1x pairs, then x29/x30 at the top; x29 points at the saved-fp pair.
141
+ The prologue:
142
+
143
+ 1. Saves callee-saved registers actually used (+x19/x20/x21 always).
144
+ 2. `xRuntime = x0`.
145
+ 3. If there are try regions: saves `runtime.shLocals` into the native frame.
146
+ 4. Native stack overflow check against
147
+ `Runtime::overflowGuard_.nativeStackHigh/Size`, slow path calls
148
+ `_sh_check_native_stack_overflow` (no IP save — the exception belongs to
149
+ the caller).
150
+ 5. `xFrame = runtime.stackPointer`.
151
+ 6. `ProhibitInvoke` check (from the function header flags): loads NewTarget
152
+ from the *incoming* frame and throws invalid-call/invalid-construct via a
153
+ slow path.
154
+ 7. Register-stack overflow check + bump: allocates
155
+ `frameSize + FirstLocal` slots, stores new `stackPointer` and
156
+ `currentFrame`, then zero-fills the newly allocated slots (vectorized,
157
+ loop for >32 regs). Zero is a "raw" value ignored by the GC (HV64
158
+ invariant).
159
+ 8. If there are try regions: pushes an `SHJmpBuf` (links `shr->shCurJmpBuf`)
160
+ and calls `_sh_setjmp`; a non-zero return branches to the catch-table
161
+ dispatch code (see Exceptions).
162
+
163
+ The epilogue (`leave`) undoes this in reverse (pops jmpbuf, restores
164
+ `stackPointer`/`currentFrame` from `xFrame` and the frame's PreviousFrame
165
+ slot, restores saved regs, `ret`).
166
+
167
+ ### VM stack frame layout
168
+
169
+ From `sh_stack_frame_layout.h` (slot indexes relative to the frame pointer):
170
+ locals are at +1.., and the caller-populated metadata sits below:
171
+ PreviousFrame(-1), SavedIP(-2), SavedCodeBlock(-3), SHLocals(-4),
172
+ ArgCount(-5), NewTarget(-6), CalleeClosureOrCB(-7), ThisArg(-8),
173
+ FirstArg(-9)...
174
+
175
+ An outgoing call is set up by writing to FRs *above* the current frame
176
+ (`nRegs + StackFrameLayout::X`), which the callee will see as its metadata:
177
+ see `callImpl` below.
178
+
179
+ ### Making calls to the runtime (helpers)
180
+
181
+ Two macros (in `JitEmitter-internal.h`) wrap `Emitter::callRuntime*`; both
182
+ materialize the target address into x16 with mov/movk and `blr`:
183
+
184
+ - `EMIT_RUNTIME_CALL` → `callRuntimeWithSavedIP`: stores the current bytecode
185
+ IP (`getBytecodeIP`, materialized from `codeBlock_->begin()` + offset) into
186
+ `Runtime::currentIP_` before the call. Required for anything that can
187
+ throw, allocate, or otherwise observe the IP (exception backtraces, lazy
188
+ compilation, GC). With `emitAsserts`, the IP is invalidated after the call
189
+ so stale-IP bugs assert in debug.
190
+ - `EMIT_RUNTIME_CALL_WITHOUT_SAVED_IP` → `callRuntime`: preserves whatever IP
191
+ is already saved (prologue checks, setjmp, catch dispatch, and helpers
192
+ that neither throw nor allocate).
193
+
194
+ Historical note: the JIT once had a thunk mechanism (per-target trampolines
195
+ loading from an RO-data function-pointer table) so each helper call site
196
+ would be a short `bl`. It was disabled after costing 2.8% on a React
197
+ benchmark via branch mispredicts, and later deleted outright — see git
198
+ history for `registerThunk`/`emitThunks` if the tradeoff is ever revisited.
199
+ An x86-64 backend should not resurrect it without new measurements; the
200
+ mov-imm64 + `call reg` shape is the baseline.
201
+
202
+ ### Slow paths, RO data, constants
203
+
204
+ - Slow paths are queued in `slowPaths_` (a `std::deque<SlowPath>`) during
205
+ instruction emission and emitted after the function epilogue by
206
+ `emitSlowPaths()`. `SlowPath` (JitEmitter.h) carries the two labels and
207
+ `emittingIP` (so IP materialization in the slow path is correct) plus a
208
+ type-erased lambda whose captures are stored *inline*: the constructor
209
+ placement-news the lambda into fixed storage, static_asserting that it
210
+ fits, is not over-aligned, and is trivially destructible. Each slow path
211
+ therefore captures exactly the state it needs — no shared field grab-bag,
212
+ no per-lambda heap allocation, and reading state the producer never set is
213
+ unrepresentable. `SlowPath` is deliberately non-copyable/non-movable
214
+ (`std::deque` never relocates elements). Typical shape: fast path branches
215
+ to `slowPathLab` on a failed check; slow path calls the `_sh_ljs_*`
216
+ helper, moves the result and branches back to `contLab`.
217
+ - `roData_` is a byte vector emitted after the code (`emitROData`), addressed
218
+ pc-relative through `roDataLabel_`; it holds 64-bit constants
219
+ (`uint64Const`, deduplicated in `fp64ConstMap_`) and the debug function
220
+ name. The read/write/private-name property-cache base pointers are stored
221
+ there at construction.
222
+ - Doubles/constants are loaded either inline (`isCheapConst`: ≤2 non-zero
223
+ 16-bit words → mov/movk) or from the RO-data pool (pc-relative `ldr`).
224
+
225
+ ### Calls to JS (`callImpl`)
226
+
227
+ `call/callN/callWithNewTarget/callWithNewTargetLong/construct` populate the
228
+ outgoing frame metadata FRs (callee, previous-frame, saved-IP, null
229
+ saved-code-block, null SHLocals, new.target, argcount; small `CallN` forms
230
+ also copy the args), then `callImpl`:
231
+
232
+ 1. Fast path: callee tag is object → GCCell kind in
233
+ `[CodeBlockFunctionKind_first..last]` → its CodeBlock's `JITCompiled_`
234
+ non-null → `blr` directly into the JIT'ed callee (x0=Runtime).
235
+ 2. Kind out of range or not yet JIT'ed → slow path loads
236
+ `VTable::jitCallArray[kind]` (per-CellKind dispatch, handles bound
237
+ functions, native functions, interpreter fallback, and triggers callee
238
+ compilation) and calls it with the same (Runtime*, Callable*) protocol.
239
+ 3. Non-object callee → shared per-function `nonObjCallLabel_` slow path calls
240
+ `_jit_throw_non_object_call` (outgoing frame is already set up, so the
241
+ error can reference the callee value).
242
+
243
+ `CallBuiltin` instead calls the `_jit_call_builtin` C++ handler, which
244
+ finishes populating the already-arg-filled new frame and invokes the native
245
+ builtin. `CallRequire` calls `_sh_ljs_callRequire` with the module cache.
246
+
247
+ ### Exceptions
248
+
249
+ If a function contains any try region, its prologue pushes one `SHJmpBuf` for
250
+ the whole function. Unwinding uses `longjmp`: a throw anywhere below performs
251
+ `_sh_longjmp` to the innermost jmpbuf. On a nonzero setjmp return, control
252
+ goes to `catchTableLabel_` (emitted by `emitCatchTable` after `leave`):
253
+
254
+ - Calls `_jit_find_catch_target(runtime, codeBlock, frame, jmpBuf,
255
+ savedSHLocals, addressTable)`. That handler rethrows uncatchable values,
256
+ finds the faulting bytecode IP (from `Runtime::currentIP_` if the fault was
257
+ in this frame, else from the callee frame's SavedIP slot — the register
258
+ stack has not been reset yet), searches the *bytecode* exception table by
259
+ offset, restores `shLocals`/register-stack via `_sh_catch_no_pop`, and
260
+ returns the native address of the handler BB from the embedded
261
+ `addressTable` (4-byte label deltas emitted next to the dispatch code); if
262
+ no handler covers the offset it pops the jmpbuf and rethrows.
263
+ - `Catch` itself (`catchInst`) then loads `runtime.thrownValue_` into the
264
+ result FR and clears it (writes "empty").
265
+
266
+ Because the JIT does not push/pop per-frame `SHLocals`, the prologue-saved
267
+ `shLocals` value is what gets restored.
268
+
269
+ A crucial supporting invariant lives in the bytecode register allocator, not
270
+ the JIT: `RegisterAllocator::getRegClass` (`lib/BCGen/RegAlloc.cpp`) forces
271
+ *all* registers to `RegClass::Other` in any function containing a try. Since
272
+ the JIT assigns global callee-saved registers only to the Number/NonPtr
273
+ register classes, a function with exception handlers has **no global
274
+ registers at all** — every FR's canonical location is the memory frame, which
275
+ is what makes "longjmp to the entry setjmp, then re-enter a handler BB that
276
+ reads FRs from the frame" correct. Emitters of potentially-throwing
277
+ instructions still must sync live temps before the throwing path when inside
278
+ a try (`isInTry()`), because temps are per-BB and not restored by longjmp.
279
+
280
+ **Sync-only vs. sync-and-free.** The `isInTry()` emitters are not consistent
281
+ about whether the sync is followed by `freeAllFRTempExcept({})`, and the
282
+ distinction is worth understanding before porting them. The two serve
283
+ different purposes:
284
+
285
+ - The **sync** is about the *frame*: it makes the memory frame current, which
286
+ is what a catch handler reads after a longjmp. Required whenever a throwing
287
+ path can be taken inside a try.
288
+ - The **free** is about *registers*: temps are caller-saved, so any call
289
+ clobbers them. Required whenever a call is emitted on a path that then
290
+ continues in this basic block — whether the call is inline or in a slow
291
+ path that returns to the fast path. It is *not* required when the only call
292
+ is a non-returning throw in an out-of-line slow path, because nothing
293
+ resumes with those temps live; the catch handler begins a new basic block,
294
+ which re-normalizes temp state via `newBasicBlock`.
295
+
296
+ That rule accounts for all three shapes in the emitter:
297
+
298
+ | Emitter | Shape | Why |
299
+ |---|---|---|
300
+ | `throwIfThisInitialized`, `fastArrayLoad` (`#else` arm) | in-try sync, no free | only call is a non-returning throw, out of line |
301
+ | `throwInst` | in-try sync, unconditional free | emits its `_sh_throw` call inline |
302
+ | `fastArrayLoad` (`HERMESVM_COMPRESSED_POINTERS` / `HERMESVM_BOXED_DOUBLES` arm) | unconditional sync + free, no `isInTry()` | emits an unconditional `_sh_fastarray_load` call |
303
+
304
+ `throwIfEmpty` also does both; there the free is plausibly for allocation
305
+ rather than safety, since it allocates a result FR immediately afterwards
306
+ that can reuse a freed temp.
307
+
308
+ Note that `fastArrayLoad` appears in two rows: the shape depends on the
309
+ build configuration, so reading only one arm gives the opposite impression.
310
+ When porting, derive the free from "does a path that continues emit a call",
311
+ not from the nearest sibling's shape.
312
+
313
+ ### Inline caches
314
+
315
+ Read caches (`GetById*`), write caches (`PutById*`), and private-name caches
316
+ use the same `SHReadPropertyCacheEntry`/`SHWritePropertyCacheEntry` arrays as
317
+ the interpreter (owned by the CodeBlock, malloc'd — stable addresses baked
318
+ into RO data). The JIT-specific twist for hidden-class identity: instead of
319
+ comparing full HC pointers (which would require materializing a 64-bit
320
+ pointer), emitted code can compare the 16-bit `HiddenClass::lazyJITId_`,
321
+ assigned on demand by `initHCLazyIDMayAlloc()`. Assigned HCs are appended to
322
+ `JITContext::Impl::usedHCs` (an `ArrayStorageSmall` rooted via
323
+ `JITContext::markRoots`), which pins them forever — required because the ID
324
+ is baked into immutable machine code. ID 0 means "unassigned"; the 16-bit
325
+ space can overflow (65535 ids), after which affected fast paths are not
326
+ emitted.
327
+
328
+ `GetByIdImpl` (a ~350-line class in `JitEmitter-property.cpp`) emits the
329
+ interpreter's
330
+ cache-hit protocol inline, in up to three tiers:
331
+
332
+ 1. **Object specialization** — if at JIT time the cache entry has
333
+ `numGoodChanges == 1` and a positive match, the entry's HC and slot are
334
+ baked into the code: compare the object's HC `lazyJITId` against the
335
+ 16-bit immediate, load the fixed slot directly. (Valid because a
336
+ non-dictionary HiddenClass's layout is immutable and the ID-pinning via
337
+ `usedHCs` keeps the HC alive.)
338
+ 2. **Parent specialization** — for negMatch entries (property found on the
339
+ prototype): check the object's HC ID, load and null-check the parent,
340
+ check the parent's HC ID, load the baked slot from the parent. When this
341
+ tier is emitted, no generic tier follows.
342
+ 3. **Generic tier** — compare the object's compressed HC pointer against the
343
+ *live* cache entry (base pointer from RO data), load `_slot16`, split
344
+ direct/indirect properties, decode the SmallHermesValue
345
+ (`Emit_sh_shv_decode` shares the multi-case decode tail across load
346
+ sites).
347
+
348
+ Miss → out-of-line call to `_sh_ljs_get_by_id_rjs`/`_sh_ljs_try_get_by_id_rjs`
349
+ with the cache-entry address. Writes have no inline fast path yet (explicit
350
+ TODO): they go through `_jit_put_by_id`, which implements cache-hit,
351
+ cached-add-transition (checking the RuntimeModule `AddPropertyCacheEntry`,
352
+ parent epoch and parent pointer) and falls back to
353
+ `Interpreter::putByIdSlowPath_RJS`.
354
+
355
+ ### Inline allocation
356
+
357
+ `bumpAllocAndUnpoison` emits a young-gen bump allocation against the Hades
358
+ fields baked in `RuntimeOffsets` (`heap_.youngGen_.level_` /
359
+ `effectiveEnd_`), branching to a slow path on overflow; with ASan it also
360
+ calls `__asan_unpoison_memory_region`. `initGCCell` stores kindAndSize (+
361
+ debug alloc id in debug builds). Used by `newObject`,
362
+ `newObjectWithParent`, `newObjectWithBuffer` (paired with
363
+ `_jit_new_empty_object_for_buffer` / interpreter buffer handlers for the
364
+ non-fast cases), environment creation (`createEnvironment`,
365
+ `createFunctionEnvironment` inline-initialize slots to undefined), and
366
+ `alloc2InYoung` allocates object+propstorage pairs. Allocation slow paths
367
+ call the corresponding `_sh_ljs_*`/`_interpreter_*` helpers.
368
+
369
+ Since the JIT stores into freshly allocated young-gen cells before any
370
+ safepoint, those initializing stores need no write barriers (this is also why
371
+ `newObjectWithBuffer` bails to the slow path when the property count exceeds
372
+ `JSObject::maxYoungGenAllocationPropCount()`). Stores into pre-existing
373
+ objects (environments, own slots) are *not* inlined — they call the
374
+ `_sh_ljs_*` helpers, which perform the Hades barriers in C++ (see the TODOs
375
+ about inlining write barriers). The one Hades-specific check emitted inline
376
+ is a weak-root *read* barrier guard: `newObjectWithBuffer` reads the cached
377
+ `HiddenClass` from the RuntimeModule's `objectLiteralHiddenClasses_`
378
+ `WeakRoot`s, and bails to the slow path whenever
379
+ `heap_.ogMarkingBarriers_` is active.
380
+
381
+ ### GC integration
382
+
383
+ The mutator can only observe emitted code at helper-call boundaries; the
384
+ frame slots (zero-initialized, always the canonical location for pointer FRs)
385
+ are the GC roots. Specifics:
386
+
387
+ - Pointer-typed FRs never live in global (callee-saved) registers across
388
+ safepoints; before any helper call all temps are synced to frame/global.
389
+ - `JITContext::markRoots` roots only `usedHCs` (pinned hidden classes).
390
+ - Other GC pointers baked into code must be independently immortal:
391
+ string constants are materialized via `loadConstStringInGpX` only for
392
+ SymbolID-interned strings held alive by the IdentifierTable;
393
+ CodeBlock/RuntimeModule/property caches/builtin table are malloc'd.
394
+ - `HERMESVALUE_VERSION == 2` static asserts appear next to every piece of
395
+ tag-manipulation code; the tag helpers (`emit_sh_ljs_*` in
396
+ `JitEmitter-internal.h`) encode the NaN-boxing scheme
397
+ (48-bit data, tags in the top bits, pointer tags ≥ `HVTag_FirstPointer`,
398
+ extended tags for undefined/null/bool/symbol/empty at bit 47).
399
+ - Compressed-pointer / boxed-double configurations are supported behind
400
+ `HERMESVM_COMPRESSED_POINTERS` / `HERMESVM_BOXED_DOUBLES`
401
+ (`emit_sh_cp_*`, `Emit_sh_shv_decode`); the contiguous-heap requirement in
402
+ Config.h makes decode a simple `add xRuntime`.
403
+
404
+ ### Arithmetic, comparisons and NaN handling
405
+
406
+ The binary/unary arithmetic and comparison emitters share a template
407
+ (`arithBinOp`, `arithUnop`, `compareImpl`, `jCond`, `bitBinOp` +
408
+ DECL_* macro tables in JitEmitter.h) with per-op fast-path callbacks:
409
+
410
+ - Non-number detection exploits NaN-boxing: every boxed (non-double)
411
+ encoding is an unsigned value above `HVTag_First << 48`, i.e. a NaN bit
412
+ pattern, so `fcmp x, x` + `b.ne`, or an `fcmp` of both operands + `b.vs`
413
+ (unordered), routes both boxed values *and* real NaNs to the slow path.
414
+ Real-NaN operands therefore take the slow C call and are handled there —
415
+ slower but correct.
416
+ - The `*N` bytecode forms (`AddN`, `JLessN`...) set `forceNumber`: operands
417
+ are statically known numbers, checks and slow paths are omitted entirely.
418
+ - Comparison condition codes are chosen NaN-aware. On arm64, unordered
419
+ `fcmp` sets N=0,Z=0,C=1,V=1, so: `<`→kMI, `<=`→kLS, `>`→kGT, `>=`→kGE all
420
+ evaluate false on unordered operands (JS semantics), while their negations
421
+ (used by the inverted `JNot*` branch forms) evaluate true. Branch layout
422
+ depends on this: the non-inverted conditional branch may be emitted before
423
+ the `b.vs` slow-path check (safe: false on unordered), the inverted one
424
+ must come after it. This table must be re-derived for x86-64
425
+ (`ucomisd` sets CF/ZF/PF; unordered sets PF and the classic idiom is
426
+ above/below conditions + explicit `jp`).
427
+ - Bit ops (`bitBinOp`) prove both operands are exact int64 doubles
428
+ (`fcvtzs` + `sbfx #0,#63` sign-trick + round-trip `fcmp`), operate on the
429
+ low 32 bits (which is exactly ToInt32 for exact ints; shifts use the
430
+ hardware modulo-32 semantics matching the spec's `& 31`), and re-encode
431
+ via `scvtf`/`ucvtf` (unsigned only for `>>>`).
432
+ - `strictEqualImpl` is a three-tier pipeline: raw 64-bit compare when a side
433
+ is statically Bool/OtherNonPtr; `fcmp` alone when a side is statically
434
+ Number; otherwise `fcmp`, and on unordered a tag-dispatch chain (double
435
+ check → tag compare → object identity / string length-and-flags fast
436
+ reject → deep compare via `_sh_ljs_strict_equal`, which takes operands by
437
+ value and never allocates).
438
+ - `%` marshals both doubles into d0/d1 and calls `_sh_mod_double` — the same
439
+ helper the native backend uses, so fmod corner cases match by
440
+ construction.
441
+
442
+ ### Encoding-limit handling
443
+
444
+ Immediate/displacement limits are handled by choosing the sequence up front:
445
+ helpers like `emit_load_from_base_offset` (and, since the 2026-08 fixes,
446
+ `_loadFrame`/`_storeFrame` and the cache-entry address arithmetic) test the
447
+ value against the encoding — `a64::Utils::isAddSubImm` and friends — and
448
+ pick a multi-instruction fallback when it does not fit. The older
449
+ optimistic-emission idiom, `EXPECT_ERROR(...)` (emit the short form, let the
450
+ custom asmjit error handler swallow the one expected error code, fall back),
451
+ survives at three sites (`loadConstStringInGpX`, `loadParam`, and
452
+ `storeVal` in the object-literal visitor); prefer the up-front check in new
453
+ code — it is what the fallback-fix series converged on, and it is easier to
454
+ port since the predicate is explicit rather than encoded in an error code.
455
+ Unexpected asmjit errors still longjmp out of the compilation and mark the
456
+ function don't-JIT.
457
+
458
+ ### Debugging aids
459
+
460
+ - `-Xdump-jitcode=` bit flags (`DumpJitCode`): code listing (via the asmjit
461
+ logger), compile status, per-instruction error, `brk` insertion,
462
+ entry/exit tracing (`_sh_print_function_entry_exit`).
463
+ - `emitAsserts` (`-Xjit-emit-asserts`): IP invalidation after calls, plus
464
+ `assertPostInstructionInvariants` at compile time (every temp accounted
465
+ for, no dirty FRs).
466
+ - Counters (`JIT_COUNTERS`: NumCall, NumCallSlow) incremented inline when
467
+ enabled.
468
+ - Linux `perf` jitdump + source-comment sidecar via `PerfJitDump`.
469
+ - `utils/jit/jit-dump.sh` / `jit-diff.sh`: capture a canonicalized dump of
470
+ all JIT-emitted code from a `hermes` binary and diff two binaries'
471
+ output, separating comment-only changes from instruction changes. The
472
+ tool of choice for verifying that a refactor did not change emitted
473
+ code — and for A/B-ing arm64 against a future x86-64 backend at the
474
+ "same fast/slow path decisions" level.
475
+
476
+ ### Working on the JIT without arm64 hardware
477
+
478
+ `aarch64/README.md` describes how to cross-compile for aarch64 Linux and
479
+ run the result under `qemu-user`, which compiles *and executes* JIT'ed code
480
+ on an x86-64 host: a host `hermesc`/`shermes` build feeds
481
+ `IMPORT_HOST_COMPILERS`, and `QEMU_RUN_PREFIX` (already wired into lit)
482
+ makes `check-hermes` run target binaries under emulation. `test/jit` passes
483
+ there. Two traps worth knowing even if you never use the setup:
484
+ `HERMESVM_ALLOW_JIT` must be **2**, not 1 — `=1` builds a working JIT but
485
+ leaves the lit feature unset, so the whole JIT suite silently skips while
486
+ reporting success; and ASan cannot be combined with qemu-user, so
487
+ emulation catches logic divergence but not the memory bugs an ASan build on
488
+ real hardware would. arm64 macOS remains a supported (and much faster)
489
+ JIT host — see the Config.h row in the source layout table.
490
+
491
+ ## x86-64 porting notes
492
+
493
+ The x86-64 backend (`lib/VM/JIT/x86-64/`) compiles arithmetic, comparisons,
494
+ branches, bit operations, type assertions, young-gen allocation, environments,
495
+ closures, and calls. Milestone 3 adds young-gen inline allocation (bump-alloc
496
+ with overflow slow path, pulled forward from the spec's milestone 4 because
497
+ environments allocate inline), environment creation and field access (get/load/
498
+ store all forms), closures with captured-environment fast paths, class and
499
+ generator object creation (initialization only), and the full call family
500
+ (Call/Call1-4, CallBuiltin under -fstatic-builtins, Construct/CallWithNewTarget
501
+ (Long), CallRequire) with JIT-to-JIT direct-call fast path; recursive and
502
+ higher-order JS now runs in machine code. Opcode coverage includes LoadParam/
503
+ LoadConst*/Mov/Ret (M1), Add/Sub/Mul/Div/Mod with N variants, Inc/Dec/Negate,
504
+ ToNumber/ToNumeric, all comparisons, all branches, BitAnd/Or/Xor, shifts,
505
+ BitNot, ToInt32/ToUint32, type asserts. Tests live at test/jit/x86-64/ (9 total:
506
+ skeleton, arith, cmp, loops, bitops, type-asserts, closures, calls, callbuiltin);
507
+ test/jit itself is still gated to arm64 (test/jit/lit.local.cfg) during
508
+ bring-up, so the main JIT suite does not exercise this backend yet.
509
+ -Xjit-emit-counters works (NumCall/NumCallSlow). Still declining: property
510
+ access, object/array/string literals and ops, typeof/instanceof/in, switches,
511
+ exceptions/try, iterator resume, for-in, arguments, globals. To build:
512
+
513
+ cmake -B cmake-build-x86jit -G Ninja -DCMAKE_BUILD_TYPE=Debug \
514
+ -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
515
+ -DHERMES_ENABLE_ADDRESS_SANITIZER=ON \
516
+ -DCMAKE_CXX_FLAGS="-O1" -DCMAKE_C_FLAGS="-O1" -DHERMESVM_ALLOW_JIT=2
517
+
518
+ **Free-after-call invariant (read before adding call emitters).** On
519
+ x86-64, every temp-eligible register is caller-saved: all 8 GP temps
520
+ (`kGPTemp1`/`kGPTemp2`) and all 16 xmm registers (`kVecTemp`). Unlike
521
+ arm64, there is no callee-saved temp subset a call can leave alone.
522
+ Emitters must sync AND free all temps around any emitted call, not just
523
+ sync them -- a temp merely synced-but-not-freed still holds a pre-call
524
+ value the callee is free to clobber. Globals survive calls unharmed only
525
+ because they live in the callee-saved GPRs rbx/r12/r13 (`kGPSavedList`),
526
+ never in a temp. One safety net: under `-Xjit-emit-type-asserts`,
527
+ `readFRForAssert` prefers live registers over the frame, so a
528
+ sync-without-free bug that leaves a stale temp registered as an FR's
529
+ location produces a spurious assert trap rather than silently reading
530
+ garbage. That is a deliberate property, not a byproduct, and the
531
+ call-emitting milestone must preserve it.
532
+
533
+ - **asmjit already supports x86-64** and the vendored copy ships the backend
534
+ (`external/asmjit/.../x86`). CMake currently compiles only `arm64/*.cpp`
535
+ when targeting arm64; a parallel `lib/VM/JIT/x86-64/` tree is expected by
536
+ `include/hermes/VM/JIT/JIT.h`.
537
+ - **Arch-independent pieces** usable as-is: DiscoverBB, RuntimeOffsets,
538
+ PerfJitDump, JitHandlers, JitCounters, and the Compiler driver
539
+ (JitCompiler.cpp) -- all now outside `arm64/`. A new backend implements
540
+ the Emitter method surface and adds its branch to `JitCurArch.h`; the
541
+ driver then compiles against it unchanged.
542
+ - **The file split is a map for the arch split.** The `JitEmitter-*.cpp`
543
+ topical boundaries separate the register-file engine (`-regalloc`), the
544
+ shared inline helpers (`-internal.h`), and lifecycle (`JitEmitter.cpp`)
545
+ from the per-instruction emitters. The engine and the driver are the
546
+ pieces worth *sharing* rather than reimplementing — the sync/spill
547
+ invariants are subtle and have already produced bugs; their only real
548
+ arch dependencies are "move reg↔reg" and "load/store a frame slot".
549
+ - **Register budget** is the main design pressure: arm64 gives the JIT 8
550
+ callee-saved GpX globals (x21–x28) + 8 callee-saved VecD (d8–d15) + 16 GP
551
+ temps + 24 vec temps. SysV x86-64 has only 6 callee-saved GPRs total
552
+ (rbx, rbp, r12–r15, minus two for Runtime/Frame → 3–4 usable globals) and
553
+ **no callee-saved XMM registers**, so number FRs cannot live in global vec
554
+ registers across calls. Options: fewer globals + more aggressive
555
+ temp usage, or saving XMMs manually around helper calls. The FR model
556
+ (frame slot + optional global + optional locals) ports unchanged; only
557
+ `kGPSaved`/`kVecSaved`/`kGPTemp`/`kVecTemp*` and the class split need
558
+ rethinking.
559
+ - **Two-address arithmetic and flags**: the emitter callbacks in the
560
+ DECL_BINOP/DECL_COMPARE tables take (res, left, right) three-address form;
561
+ x86 needs mov+op sequences. Condition codes: the NaN-aware condition-code
562
+ choices (kMI/kLS for `<`/`<=` on arm64) map to x86 as `ucomisd` with
563
+ swapped operands and the above/above-equal (unsigned) conditions, which
564
+ are false on unordered (CF=1), unlike below/below-equal;
565
+ every DECL_COMPARE/DECL_JCOND entry must be re-derived, including inverted
566
+ forms.
567
+ - **movk-style tag manipulation** (`emit_sh_ljs_object` etc.) needs x86
568
+ equivalents (mov imm64 + or/and, or bit-manipulation via BMI where
569
+ available); the 48-bit-shift tag tests (`asr #47`/`cmn`) become
570
+ `sar $47` + `cmp`.
571
+ - **setjmp/longjmp exception protocol** and the whole SHJmpBuf/catch-table
572
+ design are arch-independent (SHJmpBuf size differs).
573
+ - **Runtime calls are mov-imm64 + `call reg`** — the thunk machinery was
574
+ measured, disabled, and deleted (see "Making calls to the runtime"); do
575
+ not resurrect it for x86 without new measurements.
576
+ - **Reserve a non-allocated scratch GPR** (r11, optionally r10) mirroring
577
+ x16/x17's role: call-target/IP materialization, encoding fallbacks, and
578
+ emitted-code instrumentation all need scratch that must not perturb the
579
+ allocator. Decide this before the temp allocator's register set is fixed.
580
+ - **IP materialization** (`getBytecodeIP`) and pc-relative RO data (`adr`)
581
+ become RIP-relative `lea`.
582
+
583
+ ## Appendix: findings from the 2026-08-15 review
584
+
585
+ The whole JIT was reviewed (all of `lib/VM/JIT/**`) while producing this
586
+ document. Findings below are ordered by severity; each was verified against
587
+ the actual code, not just pattern-matched. Line numbers refer to the
588
+ `x86-jit` branch base (`origin/static_h` @ 14112ce36).
589
+
590
+ **Runtime verification pass (2026-08-15, arm64 macOS).** The original review
591
+ was done by reading code on an x86-64 host, where the JIT cannot run. Findings
592
+ 1-6, 8 and 19 have since been re-tested by actually executing the JIT on
593
+ arm64 macOS (ASan+Debug, `-DHERMESVM_ALLOW_JIT=2`, `-Xjit=force` / `-Xjit=on
594
+ -Xjit-threshold=1`). Each finding carries a **Status** line below. The
595
+ code-level claims held up in every case; three *reachability* claims (2, 3
596
+ and 6) did not. Encoding failures show up as a whole-function JIT bail (use
597
+ `-Xdump-jitcode=2` for compile status and `-Xjit-crash-on-error` to turn the
598
+ silent bail into a hard stop). 7 and 9-14 cannot be constructed from JS under
599
+ current invariants and stay unverified; 15 is Linux `perf` jitdump and cannot
600
+ be exercised on an arm64 macOS host at all.
601
+
602
+ Note when testing: the tests under `test/jit` are gated on the lit feature
603
+ `jit_enabled == "2"`, i.e. they are silently skipped as "Unsupported" unless
604
+ the build is configured with `-DHERMESVM_ALLOW_JIT=2`. A `=1` build runs none
605
+ of them.
606
+
607
+ ### High severity
608
+
609
+ 1. **`_jit_call_builtin` never initializes the callee frame's ThisArg slot**
610
+ (`JitHandlers.cpp:479-505`). The interpreter's `implCallBuiltin` writes
611
+ `newFrame.getThisArgRef() = undefined` explicitly
612
+ (`Interpreter-slowpaths.cpp:1000`) because `HBCISel::verifyCall` asserts
613
+ CallBuiltin's `this` argument is a non-register-allocated
614
+ `LiteralUndefined` — the slot is never populated by bytecode. The JIT
615
+ handler writes PreviousFrame/SavedIP/SavedCodeBlock/SHLocals/ArgCount/
616
+ NewTarget/CalleeClosureOrCB but not ThisArg, and the emitter deliberately
617
+ skips it ("CallBuiltin internally sets 'this'", `JitEmitter.cpp:6535`).
618
+ Any builtin that reads `this` — e.g. `Array.from`, whose step 1 uses
619
+ `this` as the constructor — observes whatever value the caller's frame
620
+ happened to hold in that slot. Observable semantic divergence from the
621
+ interpreter (not memory-unsafe: the slot always holds a valid rooted
622
+ value). One-line fix in the handler.
623
+
624
+ **Status: CONFIRMED, reproduced.** Every call in a function shares the one
625
+ outgoing ThisArg slot at the fixed index `nRegs +
626
+ StackFrameLayout::ThisArg` (see the `#ifndef NDEBUG` loop at
627
+ `JitEmitter.cpp:6537`), so a *preceding ordinary call* in the same function
628
+ deterministically leaves its `this` behind for the builtin to find. A
629
+ function that calls `Ctor.method()` and then `Array.from(arr)` returns a
630
+ `Ctor` instance under the JIT and an `Array` under the interpreter,
631
+ because `arrayFrom` reaches `isConstructor(C)` → `Construct(C)`
632
+ (`Array.cpp:5317-5321`). Fixed by writing `getThisArgRef() = undefined` in
633
+ the handler; JIT and interpreter output then match.
634
+
635
+ The "not memory-unsafe" note understates the impact: the consequence is
636
+ that a builtin invokes a constructor chosen by whatever the caller last
637
+ used as a receiver, i.e. user JS runs where the spec says `Array.from`
638
+ allocates a plain array. Worth rating above "semantic divergence".
639
+
640
+ The same defect exists outside the JIT: `_sh_ljs_call_builtin`
641
+ (`lib/VM/StaticH.cpp`) omits the same slot, and the SH backend lowers
642
+ CallBuiltin's `this` to an `ImplicitMovInst` that emits no code, so nothing
643
+ writes it there either. That one is the more serious of the two — the AOT
644
+ path ships on every architecture, while the JIT is opt-in and arm64-only.
645
+ Reproduced with `shermes -fno-inline -fstatic-builtins -exec` using the
646
+ same script; fixed alongside.
647
+
648
+ 2. **Compile-time null deref in `GetByIdImpl::emitParentSpecialization`**
649
+ (`JitEmitter.cpp:5163-5170`). The first `initHCLazyIDMayAlloc(...)` call
650
+ is a GC safepoint (it may create/grow the `usedHCs` ArrayStorage); the
651
+ argument of the *second* call re-reads `cacheEntry->clazz`, a
652
+ `WeakRoot<HiddenClass>` that the GC may have cleared during that
653
+ safepoint. `initHCLazyIDMayAlloc` dereferenced its argument unchecked
654
+ → SIGSEGV during JIT compilation. Near-deterministic under
655
+ `HERMESVM_SANITIZE_HANDLES` when the cached class is dead (but see the
656
+ Status below — it is not). The caller's null checks all happen before the
657
+ first safepoint; `emitObjectSpecialization` is safe by ordering. Fix:
658
+ re-check for null after the first call, or make `initHCLazyIDMayAlloc`
659
+ null-tolerant.
660
+
661
+ *Both remedies have since been applied: the callee now returns 0 for a
662
+ null class, which covers every call site including the two that were
663
+ safe only by ordering, and the call site re-reads the WeakRoot to keep
664
+ the safepoint visible where it matters. Line numbers in this item refer
665
+ to the pre-fix revision.*
666
+
667
+ **Status: CONFIRMED as a crash, but the reachability claim below it was
668
+ wrong.** The unguarded deref is lethal: with a full collection forced at
669
+ that safepoint (which the safepoint is permitted to perform), a script
670
+ whose cache entry is a live negMatch with `numGoodChanges == 1` dies with
671
+ `SEGV in Emitter::initHCLazyIDMayAlloc ← getByIdImpl ←
672
+ Compiler::dispatch`. Re-checking `cacheEntry->clazz` after the first call
673
+ fixes it; compilation then bails to the slow path, which is safe because
674
+ `emitFastPath()` is immediately followed by `a.bind(slowPathLab)`
675
+ (`JitEmitter.cpp:4925-4926`), so an early return falls through into the
676
+ helper call.
677
+
678
+ However, "near-deterministic under `HERMESVM_SANITIZE_HANDLES`" does not
679
+ hold. 400 independent natural attempts under 100% handle sanitization
680
+ (`-gc-sanitize-handles=1.0`) entered `emitParentSpecialization` 400 times
681
+ and hit the window **zero** times. The reason is structural: `HiddenClass`
682
+ is allocated `LongLived::Yes` (`HiddenClass.cpp:222`), so it lives in the
683
+ old generation and its `WeakRoot` is cleared only by a *completed OG
684
+ marking cycle*. The allocation inside `initHCLazyIDMayAlloc` triggers a
685
+ young-gen collection, which never clears it. Handle sanitization perturbs
686
+ YG behaviour, not OG marking completion, so it does not help reproduce
687
+ this at all. The bug is a genuine latent crash that requires a concurrent
688
+ Hades OG cycle to complete at that one allocation — rare, not
689
+ sanitizer-reproducible.
690
+
691
+ ### Medium severity
692
+
693
+ 3. **`throwIfThisInitialized` misses the in-try temp sync**
694
+ (`JitEmitter.cpp:4555-4582`; self-acknowledged TODO at 4560, since
695
+ replaced by the fix — line numbers refer to the pre-fix revision). Every
696
+ other throwing emitter syncs temps when `isInTry()`. If
697
+ `ThrowIfThisInitialized` throws inside a try (double `super()` call in a
698
+ try), the longjmp lands in a same-function catch handler that reads FRs
699
+ from the frame — and observes stale values for any FR updated only in a
700
+ temp since BB entry. (Functions with try have no global regs, so the
701
+ temp→frame sync is exactly what is missing.)
702
+
703
+ **Status: omission is real, but NOT observable — belongs in the
704
+ latent/hardening bucket, not Medium.** No such stale FR can exist at that
705
+ point. `callImpl` performs `syncAllFRTempExcept(FR())` +
706
+ `freeAllFRTempExcept({})` before every call
707
+ (`JitEmitter.cpp:6388-6389`), and `ThrowIfThisInitialized` is *always*
708
+ emitted immediately after the super call: there is exactly one IRGen site
709
+ (`ESTreeIRGen-legacy-class.cpp:748`), sequenced between the super call and
710
+ the `StoreFrameInst` that publishes `this`. The call — a full sync point —
711
+ therefore always sits between any user computation and the check. Tested
712
+ with double `super()` straight-line, `super()` in a loop, three
713
+ independent live values, a value derived from `this`, and a branchy shape:
714
+ across all 7 emitted check sites the only FRs written in the window are
715
+ `SelectObject`/`Mov` of the compiler's `this` temps, which are dead on the
716
+ throwing path (the handler's first act is `Catch rN`, and `Mov r0, r5`
717
+ comes after the check). Interpreter and JIT output are identical in every
718
+ shape.
719
+
720
+ Still worth fixing as hardening, because the only thing keeping it safe is
721
+ instruction ordering the JIT does not control: if BCGen ever sank a pure
722
+ computation past the super call into that window, the bug would become
723
+ live. Fixed by adding the `isInTry()`-guarded sync (sync only, no free —
724
+ see "Sync-only vs. sync-and-free" above).
725
+
726
+ 4. **`newObjectWithBuffer` string-literal store lacks the displacement
727
+ fallback** (`JitEmitter.cpp:~3318`). `visitStringID` calls
728
+ `emit_store_shv` bare, while the adjacent `storeVal` wraps the same
729
+ store in `EXPECT_ERROR` with a register-offset fallback. An object
730
+ literal with a string value past indirect slot ~4090 raises an
731
+ unexpected asmjit error and the whole function silently fails to JIT.
732
+
733
+ **Status: CONFIRMED.** An object literal of 4200 string-valued
734
+ properties fails with `InvalidDisplacement: stur x3, [x1, 32768]`,
735
+ just past the 32760 ceiling of the scaled unsigned offset. The same
736
+ literal with number values compiles successfully, since those go
737
+ through `storeVal` and take its fallback -- a clean A/B for the
738
+ missing fallback. The young-gen prop-count bail at the top of
739
+ `newObjectWithBuffer` does not fire first, so the path is reachable.
740
+ The function silently falls back to the interpreter, so results stay
741
+ correct. **FIXED** by routing the string store through the same
742
+ fallback `storeVal` uses.
743
+
744
+ ### Low severity (graceful whole-function JIT bail, or defensive)
745
+
746
+ 5. **`loadFromEnvironment` unencodable LDR offset** for slots ≥ ~4092
747
+ (`JitEmitter.cpp:4000-4004`; `LoadFromEnvironmentL` carries a UInt16
748
+ slot). Compilation of the function is abandoned.
749
+
750
+ **Status: CONFIRMED.** `LoadFromEnvironmentL r0, r0, $4199` fails
751
+ with `InvalidDisplacement: ldur x1, [x1, 33624]`. Note when building
752
+ a repro: the obvious one, a closure reading thousands of captured
753
+ variables, hits finding 19 below first, because such a function also
754
+ needs thousands of frame registers. Decouple them with one
755
+ never-called closure that captures the variables and a second, tiny
756
+ closure that reads only the highest slot.
757
+
758
+ **FIXED** by routing the load through `emit_load_from_base_offset`,
759
+ which already picks a multi-instruction sequence when the
760
+ displacement does not encode. `storeToEnvironment` was never
761
+ affected: it passes the slot to a runtime helper in `w3`.
762
+ 6. **`createThis` unencodable ADD immediate** on HV64 builds
763
+ (`JitEmitter.cpp:4260-4262`): `SHReadPropertyCacheEntry` is 24 bytes, so
764
+ `24 * cacheIdx` stops encoding at cacheIdx ≥ 171 (uint8 range goes to
765
+ 254). Compilation abandoned.
766
+
767
+ **Status: CONFIRMED, but mis-scoped in two ways.** The failure is
768
+ real: `InvalidImmediate: add x3, x3, 4104`, which is `24 * 171`, one
769
+ step past the 4095 ceiling of the 12-bit ADD immediate.
770
+
771
+ It is not specific to `createThis`. Five sites do the same
772
+ `24 * cacheIdx` arithmetic (`createThis`, the `getByIdImpl` slow
773
+ path, `JitEmitter.cpp:5325`, and two `Mem` offsets at 633 and 5134),
774
+ and `GetById` reaches the ceiling first simply because it is far
775
+ more common -- the observed failure was emitting
776
+ `GetByIdShort r2, r1, $171, $87`.
777
+
778
+ The trigger is also cheaper than "171 call sites" suggests. Cache
779
+ indices are allocated per property *name*
780
+ (`propertyReadCacheIndexForId_`, `ISel.cpp:255`), not per site, so
781
+ 200 `new Ctor()` sites all share index 1. What is needed is 171
782
+ distinct property names in one function, which is plausible in
783
+ generated deserializers or large configuration readers. That makes
784
+ it more reachable than "Low severity" implies.
785
+
786
+ **FIXED** at all three bare-`add` sites via a helper that splits the
787
+ immediate. The two `Mem`-offset sites were already safe, since
788
+ `emit_load_from_base_offset` picks a multi-instruction sequence.
789
+ 7. **`loadParam` int32 overflow** (`JitEmitter.cpp:2381-2385`): absurd
790
+ `LoadParamLong` indexes (≥2^28) hit signed-overflow UB / `hermes_fatal`
791
+ at compile time, where emitting the slow-path `undefined` would be
792
+ correct.
793
+
794
+ **Status: FIXED, not verified.** The offset is now computed in 64
795
+ bits, and an index too large to encode branches unconditionally to
796
+ the slow path, which yields `undefined`. Not reachable from JS at
797
+ any source size, so there is no test: `LoadParamLong` would need an
798
+ operand above 2^28, meaning a function with 268 million parameters.
799
+ 8. **String-switch fixup runs after the memory-limit bail**
800
+ (`JIT.cpp:214-232` vs. the `usedSize > memoryLimit` nullptr return at
801
+ 314-322): writes `nullptr + labelOffset` into the RuntimeModule's
802
+ `jitCodeTarget` tables. Latent today (code never installed, JIT then
803
+ disabled) but UB and a trap if the JIT is ever re-enabled. Skip the
804
+ fixup when compilation returned null.
805
+
806
+ **Status: CONFIRMED.** With `-Xjit-memory-limit` tuned so the
807
+ enclosing function compiles but the switch-bearing function does
808
+ not, the fixup loop runs with `res == nullptr` and writes 12
809
+ `jitCodeTarget` entries derived from a null base. Latent exactly as
810
+ described: the code is never installed and the JIT disables itself,
811
+ so nothing dereferences them in that run. **FIXED** by skipping the
812
+ fixup when compilation returned null.
813
+ 9. **`initHCLazyIDMayAlloc` assigns the permanent ID before the pin
814
+ succeeds** and discards `push_back`'s status (`JitEmitter.cpp:1733-1751`).
815
+ Unreachable today (ID cap ≪ ArrayStorage max), but the "id != 0 ⟹
816
+ pinned" invariant is enforced only by luck.
817
+
818
+ **Status: FIXED.** The class is pushed onto `usedHCs` first and the
819
+ id assigned only if that succeeded; on failure the pending OOM is
820
+ swallowed and 0 returned, which every caller already handles as "no
821
+ id available". Since `push_back` can allocate and therefore move
822
+ objects, `setLazyJITId` now goes through the pinned handle rather
823
+ than the raw argument — a detail worth carrying into the port. Still
824
+ unreachable, for the reason above; the invariant no longer rests on
825
+ it.
826
+
827
+ ### Latent / hardening (no constructible failure under current invariants)
828
+
829
+ 10. **`newTypedObjectWithBuffer` missing `syncToFrame(frParent)`**
830
+ (`JitEmitter.cpp:3458-3462`), unlike every sibling that passes an FR's
831
+ frame address (cf. `newObjectWithBufferAndParent`, 3424-3427).
832
+ Currently unobservable: only Number/NonPtr-class FRs have global regs
833
+ (the stale-frame precondition), and every value a NonPtr parent FR can
834
+ hold — stale or fresh — `dyn_vmcast`s to the same null parent handle in
835
+ the handler. Should be added for uniformity.
836
+
837
+ **Status: FIXED, not verified.** The sibling's exact sequence is now
838
+ used, comment included. Unobservable for the reason above, so there
839
+ is no test.
840
+ 11. **`stringSwitchImm` missing `syncToFrame(frInput)`**
841
+ (`JitEmitter.cpp:5751-5755`); the handler reads the frame slot.
842
+ Currently protected by three unrelated invariants (no global regs for
843
+ string-capable FRs; zero-filled frame; non-string ⇒ default case is
844
+ also correct).
845
+
846
+ **Status: FIXED, not verified.** The sync is now emitted. No test:
847
+ each of the three invariants independently prevents an observable
848
+ failure, so no input can distinguish the two versions.
849
+ 12. **64-bit store into the 32-bit `ArrayStorageSmall::size`**
850
+ (`JitEmitter.cpp:3214-3220`, `newObjectWithBuffer`): overwrites 4 bytes
851
+ past the field; masked because every indirect slot (incl. slot 0) is
852
+ subsequently written before any safepoint. Should be `str wTmp`.
853
+
854
+ **Status: FIXED, not verified.** Now `str` of the `w` register. No
855
+ test: the four bytes clobbered are the start of `storage[0]`, which
856
+ the emitter overwrites before anything can observe it, so the two
857
+ versions are indistinguishable from JS.
858
+ 13. **Degenerate TypeOfIs masks** (`JitEmitter.cpp:5500-5552`, 5329-5343):
859
+ an all-bits (or empty) `TypeOfIsTypes` mask emits no checks and leaves
860
+ the `typeOfIs` result register uninitialized / `jmpTypeOfIs` never
861
+ jumps. Presumably compiler-folded before reaching bytecode; deserves an
862
+ assert.
863
+
864
+ **Status: FIXED, not verified.** Handled rather than asserted, which
865
+ is better than the remedy this item asked for. Both degenerate masks
866
+ make the result independent of the input: an empty mask matches
867
+ nothing, and an all-bits mask inverts to empty and matches
868
+ everything. `typeOfIs` emits the corresponding constant and
869
+ `jmpTypeOfIs` emits an unconditional branch, in both cases skipping
870
+ the per-tag checks entirely. No test: a degenerate mask cannot be
871
+ produced from JS, since the compiler folds such a comparison to a
872
+ constant long before bytecode.
873
+ 14. **`createClosure`/`createGenerator` clobber argument registers before
874
+ `freeAllFRTempExcept`** (`JitEmitter.cpp:4069-4086`, 4143-4175) —
875
+ benign today, violates the local-reg invariant across a window.
876
+
877
+ **Status: FIXED, not verified.** The free now happens before the
878
+ argument registers are written, which is the order every other
879
+ call-emitting site uses. No test: the window closes before anything
880
+ consults the allocator, so no input distinguishes the two versions.
881
+ Exercised with `-Xjit-emit-asserts`, whose
882
+ `assertPostInstructionInvariants` check passes either way.
883
+ 15. **`PerfJitDump` carries `debugEntries_` from a failed compile into the
884
+ next function's debug record** (`PerfJitDump.cpp:195-260`) — wrong line
885
+ attribution in `perf report` after any compile failure.
886
+
887
+ **Status: FIXED, not verified and not verifiable on this host.**
888
+ `debugEntries_` is consumed by `writeDebugInfoRecord`, reached only
889
+ through `writeCodeLoadRecord`, which a failed compilation never
890
+ calls. A `discardPendingCodeComments()` entry point now clears them,
891
+ called from both failure paths in `compileCodeBlock`: the
892
+ memory-limit bail and the longjmp error path.
893
+
894
+ This is the one item that cannot be exercised on arm64 macOS at all.
895
+ `PerfJitDump.cpp` sits behind `HERMES_ENABLE_PERF_PROF`, which
896
+ Config.h sets only on Linux and Android, and the file includes
897
+ `<elf.h>`. The no-op stub and the two call sites do compile here;
898
+ the real implementation was checked by extracting the added method
899
+ into a scratch translation unit against the Linux branch of the
900
+ header, which confirms the signatures agree but not that it
901
+ behaves correctly. Someone should run it under `perf` on Linux.
902
+ 16. Cosmetic: `fastArrayLoad` has a dead duplicate `syncAllFRTempExcept`
903
+ (3582-3583); slow-path debug comments print uninitialized `frInput2`
904
+ (bitNot, 6836) / `frInput1` (loadThisNS, 4337); `storeToEnvironment`
905
+ always logs "StoreNPToEnvironment" (4014); the comment at line 89 says
906
+ pointer tags start at 0xfc while `HVTag_FirstPointer` is −3 (0xfd) —
907
+ the emitted code uses the enum and is correct.
908
+
909
+ **Status: all FIXED.** 0xfc is `HVTag_Unused` (or `HVTag_RawHV32`
910
+ under boxed doubles); `HVTag_First` is 0xf9 and `HVTag_FirstPointer`
911
+ is the fifth, 0xfd. The dead duplicate was the weaker of the two
912
+ syncs, so removing it changes nothing. No tests: none of these
913
+ affect emitted code.
914
+
915
+ ### Found later, while reviewing the fixes
916
+
917
+ These are not from the original sweep. They turned up in the review of
918
+ the fixes for 1-3 and are recorded here because they live in the same
919
+ code and the port would otherwise inherit them.
920
+
921
+ 17. **A bailed parent specialization left the site with no inline cache
922
+ at all.** `emitFastPath` returned unconditionally after
923
+ `emitParentSpecialization`, on the reasoning that nothing useful
924
+ follows one. That holds when the specialization is emitted, but the
925
+ function has three silent bail-outs (no lazy id for the object
926
+ class, the parent class WeakRoot cleared, no lazy id for the parent
927
+ class), each emitting nothing — so the caller's return skipped the
928
+ generic tier too, and the site compiled to an object tag check, a
929
+ hidden class load, and then the slow-path helper on every
930
+ execution. Not a correctness bug; the slow path was always reached.
931
+
932
+ It is not a rare shape either: `initHCLazyIDMayAlloc` returns 0
933
+ once `prevHCId` reaches `kHCIdOverflow`, and that counter is never
934
+ reset for the lifetime of the `JITContext`, so once a program has
935
+ interned 65535 hidden classes, *every* parent-specialization site
936
+ compiled from then on degrades permanently.
937
+
938
+ **Status: FIXED.** `emitParentSpecialization` reports whether it
939
+ emitted anything and the caller skips the generic tier only when it
940
+ did. All three bail-outs happen before the first instruction is
941
+ emitted, which is now a stated precondition. Worth keeping in mind
942
+ for the port: the "return early after the specialized tier" shape
943
+ is a natural thing to copy, and it is only correct when the tier
944
+ actually emitted something.
945
+
946
+ 18. **`JITNumGetByIdSpec` counted attempts, not emissions.** The
947
+ counter was incremented before calling either specialization
948
+ emitter, so every silent bail inflated a statistic described as
949
+ "number of GetById specialized fast paths emitted". This one has
950
+ teeth because `test/jit/getbyid-fast.js` asserts on its exact
951
+ value, so an inflating bail could mask a specialization that had
952
+ stopped being emitted. **Status: FIXED** — both emitters report
953
+ whether they emitted, and the counter follows that.
954
+
955
+ 19. **`_loadFrame` / `_storeFrame` do not check the frame offset**
956
+ (`JitEmitter.h:955-968`, both carrying `// FIXME: check if the
957
+ offset fits`). The frame slot offset is `(index + FirstLocal) * 8`,
958
+ so a function with more than about 4090 frame registers cannot
959
+ encode its own frame accesses and fails to JIT.
960
+
961
+ Found while verifying 4-6, not in the original sweep. It is the
962
+ most general member of that family: 4, 5 and 6 are each one
963
+ emitter's missing fallback, whereas this one covers every frame
964
+ register access in the backend. It surfaces first for any test that
965
+ tries to build a large environment, since the closure that captures
966
+ N variables also needs N frame registers -- which is what makes the
967
+ repro for finding 5 awkward.
968
+
969
+ Reproduced as `InvalidDisplacement: stur x2, [x20, 33648]` while
970
+ emitting `LoadFromEnvironment` in a function with ~4200 registers.
971
+ Graceful, like the rest of the family: the function silently falls
972
+ back to the interpreter.
973
+
974
+ **FIXED.** Both helpers now check the offset and fall back to a
975
+ register offset materialized in x16, which sits outside the
976
+ register allocator. Note that the paired-store path in
977
+ `syncAllFRTempExcept` already guarded itself with `isStpGpXImm`, so
978
+ the codebase knew about this class of problem; the single-access
979
+ path just never got the same treatment.
980
+
981
+ ### Verified-sound design points (checked, not bugs)
982
+
983
+ - The NaN condition-code table (see "Arithmetic" section) is correct in all
984
+ invert × slow-path combinations, including boxed-value routing via
985
+ `b.vs` placement.
986
+ - `DiscoverBB` covers every Addr8/Addr32 operand in BytecodeList.def, plus
987
+ Catch, both switch table forms, and exception-handler targets.
988
+ - `JITContext::markRoots` rooting only `usedHCs` is sufficient: emitted
989
+ code never bakes a raw GC pointer (strings are re-loaded through the
990
+ IdentifierTable lookup vector at run time; HCs are compared by pinned
991
+ lazy IDs; caches/tables are C++ memory).
992
+ - `_jit_find_catch_target`'s frame-walk for the faulting IP, the jmpbuf
993
+ push/pop pairing, and the `hasTry_ ⇒ RegClass::Other` interaction are all
994
+ consistent.
995
+ - The prologue stack math keeps sp 16-aligned for every save-count parity;
996
+ the prohibitInvoke `ldur` of NewTarget before the register-stack check
997
+ reads caller-written, always-valid memory.
998
+ - `_jit_put_by_id` and `_jit_new_empty_object_for_buffer` follow the GC
999
+ handle rules (values pinned via frame slots before safepoints).