diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index cef21517..f847e524 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -5,6 +5,11 @@ name: lint
# fills the gitignored wasm payloads from the published npm tarballs. Lint
# stays its own fast job so a style break is visible in seconds, not after a
# 450MB payload fetch.
+#
+# This fork lints only the JavaScript it changes relative to upstream
+# (monteslu/romdev main, from the merge base). Errors in upstream's own files
+# are upstream's to fix; fixing them here would spread the fork's diff over
+# files it does not otherwise touch and conflict on every upstream merge.
on:
push:
@@ -19,12 +24,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
+ with:
+ fetch-depth: 0 # the merge base with upstream
- uses: actions/setup-node@v4
with:
node-version: 24 # repo engines floor is >=24
cache: npm
+ - name: Check workspace pins
+ run: node scripts/check-pins.mjs
+
# --ignore-scripts skips romdevtools' postinstall (it expects bundled wasm,
# absent in CI). We DO install workspace deps (not --workspaces=false) so
# the pure-JS tests get romdevtools' runtime deps (zod, pngjs). The core/
@@ -33,5 +43,10 @@ jobs:
- name: Install deps
run: npm ci --ignore-scripts
- - name: ESLint
- run: npm run lint
+ - name: ESLint (files this fork changes)
+ run: |
+ git fetch --no-tags https://github.com/monteslu/romdev.git main
+ base=$(git merge-base HEAD FETCH_HEAD)
+ mapfile -t files < <(git diff --name-only --diff-filter=ACMR "$base" HEAD -- '*.js' '*.mjs' '*.cjs')
+ echo "linting ${#files[@]} file(s) changed since $(git rev-parse --short "$base")"
+ if [ ${#files[@]} -gt 0 ]; then npx eslint --no-warn-ignored "${files[@]}"; fi
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 6b360004..06143332 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -57,6 +57,9 @@ jobs:
# --ignore-scripts skips romdevtools' postinstall (SDL prebuilt fetch for
# the playtest window; no window opens in CI and the runtime self-heals).
+ - name: Check workspace pins
+ run: node scripts/check-pins.mjs
+
- name: Install deps
run: npm ci --ignore-scripts
@@ -73,6 +76,44 @@ jobs:
ROMDEV_NO_GL: "1"
run: npm test --workspace=romdevtools 2>&1 | tee /tmp/test-output.txt
+ # The decomp packages' own suites. Each runs even when an earlier one
+ # failed, so one red package never hides another's result. Their inputs
+ # that a clean checkout cannot have skip with a stated reason, never fail
+ # opaquely:
+ # - upstream corpora read from the dev box: m2c's e2e/visualize cases
+ # ($M2C_SRC, else ~/.romdev/tools/m2c), permuter's job corpus
+ # ($ROMDEV_PERMUTER_CORPUS, else ~/.romdev/decomp/*/jobs), splat's
+ # Python reference-tree differential ($ROMDEV_SPLAT_PROJECT/CONFIG/REF)
+ # and pycparser's upstream c_files not shipped with the fork;
+ # - gitignored WASM payloads, filled from npm by the step above:
+ # romdev-rabbitizer's wasm/ (rabbitizer + every spimdisasm test that
+ # decodes), romdev-toolchain-mips-gcc (pycparser's use_cpp cases,
+ # permuter's compile/score cases) and romdev-toolchain-ido (permuter's
+ # import and permuter@home cases).
+ - name: Test romdev-pycparser
+ if: ${{ !cancelled() }}
+ run: npm test --workspace=romdev-pycparser 2>&1 | tee /tmp/test-output-pycparser.txt
+
+ - name: Test romdev-rabbitizer
+ if: ${{ !cancelled() }}
+ run: npm test --workspace=romdev-rabbitizer 2>&1 | tee /tmp/test-output-rabbitizer.txt
+
+ - name: Test romdev-spimdisasm
+ if: ${{ !cancelled() }}
+ run: npm test --workspace=romdev-spimdisasm 2>&1 | tee /tmp/test-output-spimdisasm.txt
+
+ - name: Test romdev-splat
+ if: ${{ !cancelled() }}
+ run: npm test --workspace=romdev-splat 2>&1 | tee /tmp/test-output-splat.txt
+
+ - name: Test romdev-m2c
+ if: ${{ !cancelled() }}
+ run: npm test --workspace=romdev-m2c 2>&1 | tee /tmp/test-output-m2c.txt
+
+ - name: Test romdev-permuter
+ if: ${{ !cancelled() }}
+ run: npm test --workspace=romdev-permuter 2>&1 | tee /tmp/test-output-permuter.txt
+
# A green badge that silently covers nothing is the same failure class as
# a tool returning ok:true on a black frame: the signal reports success
# while meaning nothing. So SAY what this run could not test, in the job
@@ -81,7 +122,9 @@ jobs:
- name: Report what this run could NOT cover
if: always()
run: |
- skipped=$(grep -c '^# SKIP' /tmp/test-output.txt 2>/dev/null || echo 0)
+ # node --test's spec reporter ends each run with "ℹ skipped N".
+ count() { { grep -hE '^ℹ skipped [0-9]+' "$@" 2>/dev/null || true; } | awk '{s += $3} END {print s + 0}'; }
+ skipped=$(count /tmp/test-output.txt)
{
echo "### Coverage gaps in this run"
echo
@@ -93,7 +136,17 @@ jobs:
echo "- \`test/roms/nestest.nes\` is commercial content and ships in no tarball,"
echo " so the tests needing it skip themselves by design."
echo
- echo "Total skipped in this run: **${skipped}**"
+ echo "Total skipped in the romdevtools suite: **${skipped}**"
+ echo
+ echo "#### Decomp packages"
+ echo
+ echo "| package | skipped | reasons |"
+ echo "|---|---|---|"
+ for p in pycparser rabbitizer spimdisasm splat m2c permuter; do
+ f=/tmp/test-output-$p.txt
+ reasons=$({ grep -hE '^ *﹣ .* # ' "$f" 2>/dev/null || true; } | sed 's/.* # //' | sort | uniq -c | sort -rn | awk '{n=$1; $1=""; printf "%s x%s
", substr($0, 2), n}')
+ echo "| romdev-$p | $(count "$f") | ${reasons:-none} |"
+ done
echo
echo "A green check here means everything runnable passed - not that"
echo "everything was run."
diff --git a/NOTICE b/NOTICE
index 7c779248..24a17428 100644
--- a/NOTICE
+++ b/NOTICE
@@ -1,99 +1,598 @@
-romdev - third-party component inventory
-========================================
-
-TL;DR - Games you build with romdev are YOURS, including to sell commercially.
-A built ROM contains only your code + permissive runtime libraries, compiled by
-toolchains with runtime exceptions. The non-commercial caveat below applies ONLY
-to redistributing the romdev tool bundle (which contains two non-commercial
-emulator cores) - never to the games you make with it.
-
-romdev's own code is MIT (see LICENSE). It bundles and redistributes
-third-party emulator cores, compiler toolchains, and game runtime libraries,
-each under its own license. This file inventories them.
-
-Two kinds of bundled component, governed differently:
-
- • COMPILERS / TOOLCHAINS produce the user's ROM. Several are GPL/LGPL, but
- compilers carry a RUNTIME EXCEPTION: the license of the compiler does NOT
- extend to its output. A game compiled with GPL gcc/cc65/sdcc is the
- author's own work, freely licensable. The GPL obligation falls on US (we
- redistribute the compiler binary) - satisfied by shipping the build recipe
- + pinned upstream source so anyone can reproduce the binary (see
- packages/romdev/scripts/ and BUILDING.md).
-
- • EMULATOR CORES never touch the user's ROM - they are a dev instrument
- (run + observe). Their license governs only OUR redistribution of the core
- binary. Most are GPL (OSI open source, source available upstream). Two are
- NON-COMMERCIAL (see below), which is why romdev as a whole is distributed
- as SOURCE-AVAILABLE / FREE FOR NON-COMMERCIAL USE rather than OSI open
- source. romdev's own code is MIT and the game runtime libraries are
- permissive, so games you BUILD with romdev are unencumbered (see below);
- the non-commercial terms apply only to redistributing the bundled core
- binaries themselves.
-
-
-NON-COMMERCIAL COMPONENTS (why romdev is "free for non-commercial use")
------------------------------------------------------------------------
-These two cores are under custom NON-COMMERCIAL licenses. They forbid
-commercial redistribution of the core, so a distribution of romdev that
-bundles them is free for non-commercial use and is not labeled OSI open
-source. (Your code is MIT; your built games are unencumbered - this affects
-only redistribution of these emulator binaries.)
-
- snes9x SNES core non-commercial (snes9x license)
- genesis_plus_gx Genesis/SMS/GG core non-commercial (Genesis Plus GX license)
+romdevtools - licence statement and third-party inventory
+==========================================================
+
+This file is the licence of the romdevtools npm package (package.json:
+"SEE LICENSE IN NOTICE"). It has three parts:
+
+ 1. romdev's own code is MIT. The full text is in LICENSE.
+
+ 2. Third-party components. romdevtools contains some third-party code
+ itself (listed under "Third-party code inside romdevtools"), and it
+ depends on separate npm packages (romdev-core-*, romdev-platform-*,
+ romdev-toolchain-*, romdev-analysis*, and the decompilation ports) that
+ redistribute emulator cores, compiler toolchains and tools, each under
+ its own licence. This file lists all of them. Each component's own
+ licence governs that component.
+
+ 3. Recompiled carts. The static recompiler (disasm({target:'recompile'}),
+ emit 'wasmcart' or 'sync32') builds code ported from a reference
+ emulator into every cart it makes. A recompiled cart carries that
+ emulator's licence: GPL-2.0 for NES and GB/GBC, MPL-2.0 for GBA, and
+ non-commercial for SMS/GG, Genesis and SNES. It also contains the code
+ of the game it was recompiled from. See "Recompiled carts" below.
+
+In short:
+
+ - Games you COMPILE with romdev from your own source are yours, including
+ to sell commercially. A compiled ROM contains only your code plus
+ permissive runtime libraries, built by toolchains whose licences do not
+ extend to their output.
+ - RECOMPILED carts are not unencumbered (part 3).
+ - The non-commercial terms of two emulator cores apply to redistributing
+ the romdev tool bundle that contains them (and to recompiled carts built
+ from their code), never to games you compile.
+
+This section describes what each licence says; it is not legal advice.
+
+
+How the kinds of component are governed
+---------------------------------------
+
+ COMPILERS / TOOLCHAINS produce the user's ROM. Several are GPL or LGPL, but
+ their licences do not reach the compiled output: gcc's runtime library
+ carries the GCC Runtime Library Exception, SDCC's runtime libraries carry a
+ linking exception, and the other assemblers and linkers place no
+ conditions on what they produce. A game compiled with GPL gcc, cc65 or
+ sdcc is the author's own work, freely licensable. The GPL obligation falls
+ on romdev as the redistributor of the compiler binaries. It is met by
+ publishing the build recipes, romdev's patches and the pinned upstream
+ sources in the source repository (https://github.com/monteslu/romdev):
+ see packages/romdevtools/scripts/BUILD_MAP.md (which recipe builds which
+ package) and packages/romdevtools/scripts/versions.json (every upstream
+ URL and pinned commit). The recipes and patches are not in the npm
+ tarballs.
+
+ EMULATOR CORES are a development instrument: running a game on a core puts
+ none of the core's code into the game. A core's licence governs the
+ redistribution of the core binary. Most are GPL. Two are non-commercial
+ (below), which is why a romdev distribution that bundles them is free for
+ non-commercial use rather than OSI open source.
+
+ THE STATIC RECOMPILER is the exception: it copies code ported from the
+ reference cores into its output. Every recompiled cart carries the licence
+ of the core it was ported from (see "Recompiled carts").
+
+
+Non-commercial components
+-------------------------
+These two cores are under custom non-commercial licences that forbid
+commercial redistribution of the core. Your own code and the games you
+compile are unencumbered; a cart the recompiler builds for SMS/GG,
+Genesis or SNES contains code from these cores and is non-commercial.
+
+ snes9x SNES snes9x licence (non-commercial)
+ genesis_plus_gx Genesis / SMS / GG Genesis Plus GX licence
+ (non-commercial)
+
+romdevtools itself ships source derived from both (the recompiler backends
+under src/analysis/recompile/), under their terms. Their licence texts are in
+LICENSES/ in this package.
+
+
+Third-party code inside romdevtools
+-----------------------------------
+Everything in this package not listed here is romdev's own code (MIT).
+
+ src/analysis/recompile/ recompiler backends: code ported or generated
+ from fceumm, gambatte, mGBA, Genesis Plus GX,
+ snes9x, ares and musl. Each backend directory's
+ NOTICE.txt lists the ported files; licences in
+ "Recompiled carts" and LICENSES/.
+ src/decomp/asm-processor.js
+ JS port of asm-processor
+ (https://github.com/simonlindholm/asm-processor),
+ public domain (Unlicense).
+ src/decomp/maspsx.js JS port of maspsx (https://github.com/mkst/maspsx),
+ MIT, Copyright (c) 2023 Mark Street.
+ src/decomp/workbench/ JS port of n64-decomp-workbench 0.8.0
+ (https://github.com/akratch/n64-decomp-workbench)
+ and its bundled data (field guide, compiler-law
+ notes, skills, fingerprints), CC0-1.0.
+ src/git/wildmatch.js port of git's wildmatch.c (Rich Salz, Wayne
+ Davison), public domain.
+ src/platforms/*/lib/ game runtime libraries, shipped as source (see
+ "Game runtime / SDK libraries").
Emulator cores
--------------
- fceumm NES GPL-2.0
- gambatte GB / GBC GPL-2.0
- genesis_plus_gx Genesis / SMS / GG non-commercial ⚠ (see above)
- snes9x SNES non-commercial ⚠ (see above)
- mgba GBA MPL-2.0
- vice (x64) C64 GPL-2.0 (see "C64 ROMs" below)
- stella2014 Atari 2600 GPL-2.0
- prosystem Atari 7800 GPL-2.0
- handy Atari Lynx zlib
-
-C64 ROMs - free replacements, not Commodore's
-----------------------------------------------
- Upstream vice-libretro compiles Commodore's KERNAL, BASIC and CHARGEN ROMs
- into the core (USE_EMBEDDED). Those images are "Copyright C by Commodore
- Business Machines" per VICE's own README; the GPL covers VICE's code, not
- them. romdev builds VICE with that define disabled and redistributes none of
- them.
-
- In their place romdev-core-vice bundles MEGA65 Open ROMs (GPL-3.0 /
- LGPL-3.0), a clean-room KERNAL/BASIC/CHARGEN, so the C64 works out of the
- box. Licences ship alongside the images in that package's roms/ directory.
- Set ROMDEV_C64_ROM_DIR to use original ROMs you own instead.
-
-Compiler toolchains (runtime exception - does not encumber compiled ROMs)
---------------------------------------------------------------------------
- cc65 NES/C64/2600/7800/Lynx zlib
- sdcc GB/GBC/SMS/GG GPL-2.0 (runtime libs: GPL + linking exception)
- arm-none-eabi-gcc GBA GPL-3.0 (GCC Runtime Library Exception)
- m68k-elf-gcc Genesis (C) GPL-3.0 (GCC Runtime Library Exception)
- binutils (gcc toolchains) GPL-3.0
- newlib (gcc toolchains) BSD-style (mixed permissive)
- asar SNES (asm) LGPL-3.0
- dasm Atari 2600 (asm) GPL-2.0
- vasm (m68k) Genesis (asm) free for any use (vasm license)
- rgbds GB/GBC (asm) MIT
- tcc816 SNES (C) LGPL-2.1
- wla-dx SNES (asm) GPL-2.0
-
-Game runtime / SDK libraries (linked into the user's game; shipped as source)
-------------------------------------------------------------------------------
- SGDK Genesis C engine MIT
- PVSnesLib SNES C library MIT
- libtonc / libgba GBA C libraries public domain / zlib-style
- maxmod / mmutil GBA music ISC
- hUGEDriver GB/GBC music MIT-style (see LICENSE-HUGEDRIVER)
- FamiTone2 NES music permissive (see LICENSE-FAMITONE)
-
-Full license texts for the bundled SDK libraries live alongside their source
-under packages/romdev/src/platforms/*/lib/. Emulator-core and compiler license
-texts travel with their upstream source, which is fetched at build time from
-the pinned commits recorded in packages/romdev/scripts/versions.json.
+Each core is built to WebAssembly from its upstream source (at the commit
+pinned in versions.json in the source repository, where one is pinned),
+with romdev's patch, and shipped in the package named. 18 cores in 18 packages.
+
+ Core Platform Licence Package
+ ---------------- ------------------- ----------------- ------------------------
+ fceumm NES GPL-2.0 romdev-core-fceumm
+ https://github.com/libretro/libretro-fceumm
+ gambatte GB / GBC GPL-2.0 romdev-core-gambatte
+ https://github.com/libretro/gambatte-libretro
+ genesis_plus_gx Genesis / SMS / GG non-commercial romdev-core-gpgx
+ https://github.com/libretro/genesis-plus-gx
+ snes9x SNES non-commercial romdev-platform-snes
+ https://github.com/libretro/snes9x
+ (with ares's chip cores, ISC; see below)
+ bsnes SNES (accuracy GPL-3.0 (libco, romdev-core-bsnes
+ reference for the nall: ISC)
+ firmware chips)
+ https://github.com/libretro/bsnes
+ A separate core, linked into nothing else.
+ mGBA GBA MPL-2.0 romdev-platform-gba
+ https://github.com/libretro/mgba
+ stella2014 Atari 2600 GPL-2.0 romdev-platform-atari2600
+ https://github.com/libretro/stella2014-libretro
+ ProSystem Atari 7800 GPL-2.0 romdev-core-prosystem
+ https://github.com/libretro/prosystem-libretro
+ Handy Atari Lynx zlib romdev-core-handy
+ https://github.com/libretro/libretro-handy
+ VICE (x64) C64 GPL-2.0 romdev-core-vice
+ https://github.com/libretro/vice-libretro
+ (see "Firmware and BIOS" for the C64 ROMs)
+ Geargrafx PC Engine / TG-16 GPL-3.0 romdev-core-geargrafx
+ https://github.com/drhelius/Geargrafx
+ blueMSX MSX / MSX2 blueMSX licence romdev-core-bluemsx
+ https://github.com/libretro/blueMSX-libretro
+ (zlib-style; some sound-chip files from openMSX and fMSX-SDL
+ are GPL, per upstream license.txt)
+ (with C-BIOS, BSD-style; see "Firmware and BIOS")
+ GameTank GameTank MIT romdev-core-gametank
+ https://github.com/monteslu/gametank-libretro (libretro core), built on
+ GameTankEmulator (https://github.com/clydeshaffer/GameTankEmulator,
+ MIT, Copyright 2020 Clyde Shaffer) and its mos6502 core (MIT,
+ Copyright 2017 Gianluca Ghettini)
+ FAKE-08 PICO-8 carts MIT romdev-core-fake08
+ https://github.com/jtothebell/fake-08 (with z8lua, MIT)
+ A clean-room PICO-8 player; not Lexaloffle's PICO-8.
+ ParaLLEl-N64 N64 GPL-2.0 romdev-core-parallel-n64
+ https://github.com/libretro/parallel-n64
+ Built with the glide64 GPU renderer (GL).
+ Beetle PSX HW PlayStation GPL-2.0 romdev-core-beetle-psx-hw
+ https://github.com/libretro/beetle-psx-libretro (a Mednafen PSX fork),
+ GLES3 hardware renderer, with OpenBIOS embedded (see "Firmware and
+ BIOS")
+ Flycast Dreamcast GPL-2.0 romdev-core-flycast
+ https://github.com/flyinghead/flycast, with its reios HLE BIOS
+ s32core sync32 MIT romdev-core-s32core
+ First-party interpreter for sync32, an open RP2350-based console.
+
+The SNES coprocessor code from ares
+-----------------------------------
+ The firmware-running SNES coprocessors (the ST010/ST011 NEC uPD96050 and the
+ ST018 ARM) are compiled from ares (https://github.com/ares-emulator/ares, at
+ the commit pinned in versions.json, cores.ares): its processor cores
+ ares/component/processor/upd96050 and arm7tdmi, the Super Famicom driver
+ files ares/sfc/coprocessor/necdsp/memory.cpp and armdsp/memory.cpp and
+ io.cpp, and the nall headers they use, with romdev's glue (MIT) restating
+ the rest of those drivers and ares's thread clock. That code is compiled
+ into:
+ - recompiled SNES carts built with options.firmware (ST011 / ST018): the
+ units in src/analysis/recompile/wat/snes/ares-chips.json in this
+ package;
+ - romdev's snes9x core (romdev-platform-snes), used when st011.rom /
+ st018.rom is in the system directory.
+ ares is under the ISC license, a permissive license whose only condition is
+ keeping its notice, so it can sit with snes9x's non-commercial license and
+ with romdev's MIT code. A recompiled cart (in its licence entry's notices)
+ or a snes9x core build that contains it carries this notice:
+
+ ares
+
+ Copyright (c) 2004-2025 ares team, Near et al
+
+ Permission to use, copy, modify, and/or distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+ A recompiled SNES cart's machine follows snes9x and carries snes9x's own
+ chip units, so those parts of a cart stay under snes9x's non-commercial
+ license; the ares code adds no condition of its own. No bsnes (GPL-3.0)
+ code is compiled into snes9x or into a cart: bsnes ships only as its own
+ core, romdev-core-bsnes.
+
+
+Firmware and BIOS
+-----------------
+romdev ships no console manufacturer's BIOS or firmware. Where a system
+needs one, romdev uses a free replacement or its own code, or the user
+supplies the image.
+
+ C64 MEGA65 Open ROMs (https://github.com/MEGA65/open-roms),
+ GPL-3.0 / LGPL-3.0, a clean-room KERNAL, BASIC and CHARGEN,
+ in romdev-core-vice roms/ with their licence files. Upstream
+ vice-libretro compiles Commodore's ROMs into the core; romdev
+ builds VICE with that disabled and redistributes none of them.
+ Set ROMDEV_C64_ROM_DIR to use original ROMs you own instead.
+ MSX C-BIOS (https://cbios.sourceforge.net), BSD-style licence, in
+ romdev-core-bluemsx bios/ (licence in each cbios.txt).
+ PlayStation OpenBIOS from PCSX-Redux (https://github.com/grumpycoders/
+ pcsx-redux), MIT, embedded in romdev-core-beetle-psx-hw.
+ Dreamcast Flycast's reios HLE BIOS (part of Flycast, GPL-2.0).
+ GBA mGBA's own HLE BIOS (part of mGBA, MPL-2.0).
+ N64 build({platform:'n64'}) adds romdev's own minimal IPL3 boot
+ stub (MIT) to the ROM it produces.
+ SNES The SPC700 boot program in recompiled SNES carts and in
+ romdev's SNES path is romdev's own code (MIT), written from
+ the documented behaviour of the console's boot ROM.
+ Coprocessor firmware is supplied by the user and never ships
+ with romdev: the ST010/ST011 and ST018 programs (for
+ recompiled carts through options.firmware; for the snes9x and
+ bsnes cores as st011.rom / st018.rom in the system directory),
+ and likewise the DSP-1 data ROM, which a DSP-1 cart needs
+ supplied as firmware.
+ PICO-8 FAKE-08 needs no BIOS.
+
+
+Analysis engines
+----------------
+ Rizin (CFG, xrefs, functions) LGPL-3.0 romdev-analysis
+ https://github.com/rizinorg/rizin
+ Ghidra decompiler and SLEIGH Apache-2.0 romdev-analysis-decompiler
+ https://github.com/NationalSecurityAgency/ghidra, built via rz-ghidra
+ (https://github.com/rizinorg/rz-ghidra, LGPL-3.0), plus the SLEIGH
+ specs GhidraBoy (SM83, Apache-2.0), ghidra-snes (65816, MIT) and
+ Ghidra_HuC6280 (HuC6280, Apache-2.0). Each package's NOTICE has the
+ full attribution.
+
+
+Compiler toolchains (their licences do not encumber compiled ROMs)
+-------------------------------------------------------------------
+ Toolchain Used for Licence Package
+ ------------------------ ---------------------- ---------------- ---------------------------
+ cc65 NES, 2600, 7800, C64, zlib romdev-toolchain-cc65
+ Lynx, PC Engine,
+ GameTank
+ SDCC 4.4.0 GB/GBC, SMS/GG, MSX GPL-2.0 (runtime romdev-toolchain-sdcc
+ libs: GPL with a
+ linking exception)
+ binutils 2.42, z80-elf Z80/SM83 disassembly GPL-3.0 romdev-toolchain-sdcc
+ and reassembly
+ RGBDS GB/GBC (asm) MIT romdev-toolchain-rgbds
+ m68k-elf gcc 14.2.0, Genesis (C and asm) GPL-3.0 with the romdev-toolchain-m68k-gcc
+ binutils 2.42, newlib GCC Runtime
+ 4.4.0 Library Exception;
+ newlib BSD-style
+ sjasm (from SGDK) Genesis Z80 driver asm zlib romdev-toolchain-m68k-gcc
+ bintos (from SGDK) Z80 blob embedding MIT romdev-toolchain-m68k-gcc
+ asar SNES (asm) LGPL-3.0 romdev-platform-snes
+ tcc816 (alekmaul/tcc) SNES (C) LGPL-2.1 romdev-platform-snes
+ wla-dx (wla-65816, SNES (asm, link) GPL-2.0 romdev-platform-snes
+ wlalink)
+ dasm Atari 2600 (asm) GPL-2.0 romdev-platform-atari2600
+ arm-none-eabi gcc 14.2.0, GBA, sync32 (C) GPL-3.0 with the romdev-platform-gba
+ binutils 2.42, newlib GCC Runtime
+ 4.4.0 Library Exception;
+ newlib BSD-style
+ mips-elf gcc 14.2.0, N64, PS1 (C) GPL-3.0 with the romdev-toolchain-mips-gcc
+ binutils 2.42, newlib GCC Runtime
+ 4.4.0 Library Exception;
+ newlib BSD-style
+ mips-linux-gnu binutils N64 decomp builds GPL-3.0 romdev-toolchain-mips-gcc
+ 2.46
+ armips N64 decomp RSP MIT romdev-toolchain-mips-gcc
+ microcode
+ sh-elf gcc 14.2.0, Dreamcast (C) GPL-3.0 with the romdev-toolchain-sh-gcc
+ binutils 2.42, newlib GCC Runtime
+ 4.4.0 Library Exception;
+ newlib BSD-style
+ mips-linux-gnu gcc 14.2.0 N64 decomp data TUs, GPL-3.0; glibc's romdev-toolchain-decomp-gcc
+ .s and linker-script stdc-predef.h
+ preprocessing LGPL-2.1
+ KMC gcc 2.7.2 + N64 decomp (N64 SDK GPL-2.0 romdev-toolchain-decomp-gcc
+ binutils 2.6 as compiler)
+ EGCS 1.1.2 (gcc 2.91.66) N64 decomp (iQue GPL-2.0 romdev-toolchain-decomp-gcc
+ + binutils 2.9.5 as builds)
+ gcc 2.6.3 (PS1 recipe of PS1 decomp GPL-2.0 romdev-toolchain-decomp-gcc
+ decompals/old-gcc)
+ slinky-cli 0.5.0, decomp builds (linker MIT romdev-toolchain-decomp-gcc
+ pigment64 0.6.3, scripts, textures,
+ crunch64 compression)
+ raw-deflate (zlib 1.3.1) decomp builds zlib romdev-toolchain-decomp-gcc
+ A PS1 decomp project's PS1 decomp setup AGPL-3.0 romdev-toolchain-decomp-gcc
+ own setup tools (string (Go runtime:
+ encoder, disc extractor, BSD-3-Clause)
+ asset tool)
+
+ Upstream sources: gcc, binutils and newlib from https://gnu.org and
+ https://sourceware.org/newlib; cc65 https://github.com/cc65/cc65; SDCC
+ https://sdcc.sourceforge.net; RGBDS https://github.com/gbdev/rgbds; SGDK
+ https://github.com/Stephane-D/SGDK; asar https://github.com/RPGHacker/asar;
+ tcc816 https://github.com/alekmaul/tcc; wla-dx https://github.com/vhelin/wla-dx;
+ dasm https://github.com/dasm-assembler/dasm; armips
+ https://github.com/Kingcom/armips; the decomp compilers and tools from
+ https://github.com/decompals (mips-gcc-2.7.2, mips-binutils-2.6,
+ mips-gcc-egcs-2.91.66, mips-binutils-egcs-2.9.5, old-gcc, slinky,
+ pigment64, crunch64). The exact versions and commits are in versions.json
+ in the source repository.
+
+ The PS1 decomp projects' assembly post-processor, maspsx, is ported to JS
+ inside romdevtools (see "Third-party code inside romdevtools").
+
+IDO (not shipped)
+-----------------
+ SGI's IDO 5.3 and 7.1 C compilers, which many N64 decompilation projects
+ build with, are proprietary. romdev does not ship them, and no romdev npm
+ package contains them. romdev-toolchain-ido is a private package in the
+ source repository that npm will not publish. To use IDO, build it yourself
+ from a checkout with packages/romdevtools/scripts/build-ido.sh (it
+ statically recompiles the IRIX programs with the pinned ido-static-recomp,
+ https://github.com/decompals/ido-static-recomp, MIT, and compiles the
+ result to WebAssembly), or set ROMDEV_IDO_DIR to a directory holding your
+ own build (its 5.3/ and 7.1/ folders). The IRIX programs remain the
+ property of their owners.
+
+
+Game runtime / SDK libraries (linked into the user's game)
+-----------------------------------------------------------
+ SGDK Genesis C engine MIT romdev-toolchain-m68k-gcc
+ PVSnesLib SNES C library MIT romdevtools
+ libgba 0.5.4 GBA C library LGPL with static- romdev-platform-gba
+ linking exceptions
+ libtonc 1.4.5 GBA C library MIT romdev-platform-gba
+ devkitPro crt0 GBA start-up code MPL-2.0 romdev-platform-gba
+ maxmod GBA music ISC romdev-platform-gba
+ hUGEDriver GB/GBC music public domain romdevtools
+ FamiTone2 NES music public domain romdevtools
+ cc65 runtime 6502 targets zlib romdev-toolchain-cc65,
+ romdevtools (cc65-src/)
+ SDCC runtime Z80 / SM83 targets GPL with a romdev-toolchain-sdcc
+ linking exception
+ libgcc gcc targets (incl. GPL-3.0 with the the gcc toolchain
+ sync32's ARMv8-M GCC Runtime packages,
+ build) Library Exception romdev-platform-sync32
+ newlib gcc targets BSD-style (mixed) the gcc toolchain packages
+
+ Notes for games that link these:
+ - libgba's licence says static linking does not make your game a
+ derivative work, but asks that a program identify its use of libgba
+ (for example: "based in part on the work of the devkitpro project").
+ - The devkitPro crt0 is MPL-2.0: you may ship a game that contains it
+ under any licence; the MPL applies only to that file's source.
+ - libtonc is MIT: a game that links it should carry its copyright and
+ permission notice (libtonc/LICENSE) in its credits or documentation.
+ - Licence texts ship beside the libraries (LICENSE-HUGEDRIVER,
+ LICENSE-FAMITONE, pvsneslib/LICENSE, sgdk/LICENSE and COPYING.RUNTIME,
+ maxmod/LICENSE-MAXMOD, libgba/LICENSE, libtonc/LICENSE).
+
+ Upstreams: SGDK https://github.com/Stephane-D/SGDK; PVSnesLib
+ https://github.com/alekmaul/pvsneslib; libgba
+ https://github.com/devkitPro/libgba; libtonc
+ https://github.com/devkitPro/libtonc; maxmod
+ https://github.com/devkitPro/maxmod; hUGEDriver
+ https://github.com/SuperDisk/hUGEDriver.
+
+
+Decompilation tools (development instruments; they never touch a built ROM)
+-----------------------------------------------------------------------------
+JS ports, each in its own package with its own LICENSE and NOTICE.
+romdevtools only calls them; their output is the user's work.
+
+ Package Port of (upstream) Licence
+ ----------------- ---------------------------------------- ---------------
+ romdev-splat splat 0.37.1 (and 0.34.1 behaviour) MIT
+ https://github.com/ethteck/splat,
+ with n64img 0.3.3, pypng's writer, zlib
+ romdev-spimdisasm spimdisasm 1.42.4, 1.39.3, 1.35.0 MIT, plus
+ https://github.com/Decompollaborate/ PSF-2.0 for
+ spimdisasm tables and
+ algorithms
+ derived from
+ CPython
+ romdev-rabbitizer rabbitizer 1.16.2, 1.14.3, 1.13.0 (C MIT
+ library built to WASM, JS binding)
+ https://github.com/Decompollaborate/rabbitizer
+ romdev-m2c m2c at 1d1c4454 GPL-3.0
+ https://github.com/matt-kempster/m2c (kept in its own
+ package)
+ romdev-permuter decomp-permuter at 41bd0bfc MIT
+ https://github.com/simonlindholm/decomp-permuter
+ romdev-pycparser pycparser 2.23 as vendored by m2c and BSD-3-Clause
+ decomp-permuter, with PLY 3.10
+ https://github.com/eliben/pycparser
+
+ Graphviz (WASM) used only by romdev-m2c for --visualize SVG output, via
+ the @viz-js/viz npm package (MIT wrapper); Graphviz is
+ EPL-1.0 and runs as a separate program.
+
+ Also inside romdevtools: the asm-processor, maspsx and
+ n64-decomp-workbench ports (see "Third-party code inside romdevtools").
+
+
+Audio tool ports
+----------------
+ romdev-famitone FamiTone2's text2data (Shiru) public domain
+ (the port is MIT)
+ romdev-maxmod devkitPro mmutil (Mukunda Johnson) ISC (the port
+ is MIT)
+ romdev-xgm2 SGDK's xgm2tool MIT
+
+
+Recompiled carts (WAT and native backends)
+------------------------------------------
+ disasm({target:'recompile', emit:'wasmcart'}) turns a ROM into a wasmcart
+ (backends: src/analysis/recompile/wat// in this package), and
+ emit:'sync32' turns a Genesis ROM into a sync32 .s32
+ (src/analysis/recompile/native/genesis/). A recompiled cart does not run on
+ an emulator: so that it matches its reference core frame for frame, the
+ backend builds the core's machine model INTO the cart, from code ported by
+ hand from the core's source or generated mechanically from it. Every cart
+ a backend builds contains that code, so the cart is under that code's
+ licence.
+
+ romdev's own parts of those directories (the CPU instruction lowerers, the
+ dispatch and layout code, the WAT assembler, the packer) are MIT, and each
+ backend directory's NOTICE.txt lists which files are ported. In a built
+ cart the two are combined, so the cart as a whole follows this table.
+ Commits are short here; the full ones are in every cart's licence entry
+ (and in versions.json in the source repository).
+
+ NES (wat/nes)
+ from fceumm: PPU, APU, CPU timing, mappers, frame loop
+ https://github.com/libretro/libretro-fceumm @ 3a84a6fd
+ licence GPL-2.0-or-later
+ means sharing the cart requires offering its complete corresponding
+ source under the GPL.
+
+ Game Boy / Game Boy Color (wat/gb)
+ from gambatte: PPU, APU, MBCs, timers, CPU timing; blipper resampler
+ https://github.com/libretro/gambatte-libretro @ 3262c2aa
+ licence GPL-2.0-only AND MIT (blipper)
+ means sharing the cart requires offering its complete corresponding
+ source under the GPL; the MIT notice travels in the cart.
+
+ GBA (wat/gba)
+ from mGBA 0.11: ARM7TDMI, bus, scheduler, DMA, timers, video, audio,
+ GPIO/RTC, its HLE BIOS; musl's sin/cos (Emscripten 4.0.18,
+ with the FreeBSD msun notice of the files they come from)
+ https://github.com/libretro/mgba @ 6dce57ee
+ licence MPL-2.0 AND MIT (musl)
+ means file-level copyleft: sharing the cart requires making the source
+ of the MPL-covered files available; the MIT and msun notices
+ travel in the cart.
+
+ Master System / Game Gear (wat/sms)
+ from Genesis Plus GX: VDP, I/O, frame order, SN76489 PSG, blip_buf
+ https://github.com/libretro/genesis-plus-gx @ 162c3439
+ licence Genesis Plus GX licence (non-commercial) AND LGPL-2.1-or-later
+ (blip_buf, Shay Green)
+ means no commercial distribution: the cart may not be sold or used in
+ a commercial product or activity; the blip_buf part's source
+ must be offered.
+
+ Genesis / Mega Drive (wat/genesis, and native/genesis for sync32)
+ from Genesis Plus GX: VDP, memory map, Z80 bus, YM2612 (from MAME's
+ fm.c), PSG, blip_buf, frame loop; its Musashi 68000 core 3.32
+ and MAME z80.c 3.9 opcode handlers, evaluated into the cart;
+ SVP carts also get svp.c / ssp16.c (notaz). The sync32 backend
+ vendors the upstream C files (runtime/gpgx/, see UPSTREAM.txt).
+ https://github.com/libretro/genesis-plus-gx @ 162c3439
+ licence Genesis Plus GX licence AND Musashi licence AND z80.c licence
+ (all non-commercial) AND LGPL-2.1-or-later (blip_buf); SVP carts
+ add the SVP code's licence (free for non-commercial use only)
+ means no commercial distribution; Musashi's notice must stay in every
+ binary (the cart carries it); the blip_buf part's source must be
+ offered.
+
+ SNES (wat/snes)
+ from snes9x: memory map and ROM loading, CPU timing, DMA/HDMA, PPU,
+ SPC700 (its 64-byte boot ROM is romdev's own, MIT, see "SNES boot
+ ROM and chip data"), the coprocessors (SA-1, SuperFX from
+ fxinst.cpp, S-DD1, CX4, SPC7110, DSP-1..4, ST010/011/018 HLE,
+ OBC1, S-RTC, BS-X, MSU-1; no chip data ROM: a DSP-1, DSP-3 or
+ ST010 cart is built with the user's, options.firmware), and the
+ S-DSP from snes_spc (Shay Green)
+ https://github.com/libretro/snes9x @ 185488cd
+ SPC7110 carts: spc7110emu/dec (byuu and neviksti, ISC-style)
+ CX4 carts: musl's sin/cos/atan (MIT)
+ ST011 / ST018 carts built with options.firmware: ares (ISC,
+ https://github.com/ares-emulator/ares @ 4cb8d92b, see above)
+ The SPC700 boot program is romdev's own (see "Firmware and
+ BIOS"). Coprocessor firmware, including the DSP-1 data ROM, is
+ supplied by the user and is not part of romdev.
+ licence snes9x licence (non-commercial) AND LGPL-2.1-or-later (S-DSP),
+ plus ISC / MIT for those chips
+ means no commercial distribution; snes9x's licence text must go with
+ every copy (the cart carries it); the S-DSP part's source must
+ be offered.
+
+ The cart says this itself. Its romdev.recompile custom section (for a
+ sync32 .s32, the metadata in rd_meta.c) has a `licence` entry:
+ spdx the SPDX expression above, e.g. "GPL-2.0-or-later"
+ terms one plain line per licence
+ upstream [{name, url, commit, spdx}] of each transplanted component
+ source the romdevtools version and directory holding the ported
+ code: that package, at that version, is where the
+ corresponding source of the emulator code is
+ licenceTexts where the full licence texts are (romdevtools LICENSES/)
+ romCode the reminder about the game's own code (below)
+ notices verbatim, the notices that must travel with every copy
+ (the non-commercial licences, Musashi, snes9x, and the
+ MIT / ISC notices); the standard GPL, LGPL and MPL texts
+ are named by SPDX id and found in LICENSES/
+ The entry depends only on the platform, the cart's chips and the romdev
+ version, so the same inputs still build a byte-identical cart.
+
+ The game inside. A cart recompiled from someone else's game also contains
+ that game's code (and any BIOS, firmware, MSU-1 data or add-on images built
+ into it). It can only be shared with the game owner's permission, whatever
+ the emulator licences allow.
+
+ blip_buf and snes_spc are LGPL-2.1 libraries inside non-commercial cores;
+ the carts combine them the same way the upstream cores do. If you plan to
+ distribute recompiled carts, read the licences in LICENSES/.
+
+
+Bundled data (cheat database, used by cheats({op:'lookup'|'apply'|'make'}))
+-----------------------------------------------------------------------------
+ The cheat database ships in the romdev_game_codes package (index/), a
+ pre-parsed, per-platform index built from the community-aggregated
+ RetroArch / libretro-database cheat collection (the same data RetroArch,
+ RetroDECK and Batocera ship). These codes are an aggregation assembled over
+ years from Game Genie / Pro Action Replay code books and community cheat
+ dumps; the collection has no single uniform license and individual codes
+ carry no stated provenance. romdev redistributes a pre-parsed form (game
+ name to decoded address/value entries) rather than the raw .cht files, and
+ uses it only as a read/inspect aid and for non-destructive cheat
+ application. It is not linked into any built game and does not affect the
+ license of games you make. Source:
+ https://github.com/libretro/libretro-database (cht/). The index is rebuilt
+ from a local .cht tree with packages/romdevtools/scripts/build-cheat-index.mjs
+ in the source repository.
+
+SNES boot ROM and chip data - romdev's own, or the user's
+--------------------------------------------------------
+ The SPC700 sound CPU starts from a 64-byte boot ROM (the IPL) that runs the
+ upload protocol over ports $2140-$2143. Upstream snes9x and bsnes embed
+ Nintendo's. romdev uses its own instead: a clean-room reimplementation
+ written from the public description of the protocol and of the state it
+ hands over (romdevtools scripts/spc700-ipl/ipl.asm, MIT), assembled with
+ asar. Its port timing was matched by measuring the ports from outside
+ only, so a program uploads on the same SPC700 cycles as on the console.
+ The snes9x core, the bsnes core and every recompiled SNES cart run it; the
+ builds replace the upstream array (scripts/spc700-ipl/install-ipl.mjs).
+
+ romdev ships no chip firmware, chip data ROM or boot ROM. snes9x embeds the
+ DSP-1 data ROM (and a sine table taken from it), the DSP-3 data ROM and the
+ ST010's data ROM tables; bsnes embeds the DSP-1 data ROM, the ST010 tables,
+ the Cx4 data ROM and the Super Game Boy boot ROMs. romdev builds both with
+ those tables emptied (scripts/recompile-gen/snes9x-chips/hle-data.mjs,
+ scripts/patches/bsnes/strip-firmware.mjs) and takes the user's files
+ instead: snes9x reads dsp1b.data.rom, dsp3.data.rom or st010.data.rom from
+ its system directory, a recompiled cart is built with the same file
+ (options.firmware), and bsnes reads each chip's firmware (and sgb_boot.bin /
+ sgb2_boot.bin) from its system directory. Without the file such a cart is
+ refused with the file and its size named; bsnes runs a Cx4 cart with its
+ high-level emulation when cx4.data.rom is absent.
+
+
+Where the licence texts and sources are
+---------------------------------------
+ - romdev's own licence: LICENSE in this package.
+ - Licences of the emulator code the recompiler carries into carts:
+ LICENSES/ in this package (copied verbatim from the pinned upstream
+ sources; LICENSES/README.txt maps each file to its origin).
+ - SDK library licences: beside each library (see "Game runtime / SDK
+ libraries").
+ - The decompilation ports: LICENSE and NOTICE in each package.
+ - Emulator-core and compiler licence texts travel with their upstream
+ source, fetched at build time from the pinned commits. The recipes,
+ patches and pins are in the source repository,
+ https://github.com/monteslu/romdev, under packages/romdevtools/scripts/
+ (BUILD_MAP.md maps each recipe to the package it builds; versions.json
+ holds every upstream URL, commit and licence).
diff --git a/README.md b/README.md
index b878e2b3..b811af0e 100644
--- a/README.md
+++ b/README.md
@@ -1,155 +1,125 @@
# romdev
-**Vibe-code real retro games.** One command, and your coding agent can make actual working ROMs for NES, SNES, Game Boy, Genesis, Atari, Commodore 64, and more - that run on RetroArch, native emulators, flash carts, and real hardware. No SDK installs. No emulator setup. No PATH fiddling. No "this only works on Linux."
+romdev is a tool server that lets a coding agent (or you) build, run, debug, reverse-engineer and recompile retro console games. It covers 19 consoles and computers from the Atari 2600 to the Dreamcast, plus PICO-8 and two native WebAssembly game runtimes. Every compiler, emulator core and analysis engine ships as WebAssembly through npm, so there is nothing else to install.
```
npx romdevtools
```
-That's the whole setup. Everything - emulators, assemblers, C compilers, starter libraries, example projects, hardware reference docs - ships as bundled WebAssembly and data via npm. Same on Linux, Windows, and macOS (Node 24+).
+That starts the server on `http://127.0.0.1:7331`. It works the same on Linux, Windows and macOS (Node 24 or newer). The output is a standard ROM (`.nes`, `.gb`, `.md`, `.sfc`, `.gba`, ...) that runs in other emulators, on flash carts and on real hardware.
-## Features
+## What it does
-You (or your coding assistant, over [MCP](https://modelcontextprotocol.io/) / plain HTTP) get a tool surface for the full homebrew loop:
+romdev exposes 38 tools over MCP and plain HTTP. Each tool is a verb with an operation axis, such as `memory({op:'search'})` or `disasm({target:'cfg'})`.
-- **Building** - bundled per-platform toolchains (cc65, SDCC, RGBDS, asar, vasm, SGDK, PVSnesLib, libtonc, ...) compiled to WebAssembly. The agent writes source, compiles it, and gets a real ROM.
-- **Asset conversion** - turn external art and audio into native data without leaving the server: PNG → platform tiles/tilemaps (`convertImageToTiles`, `imageToTilemap` - row-major or hardware sprite order), PNG quantize-to-palette, sprite-sheet/Aseprite/GIF loaders, and audio importers (`pcmToBrr` for SNES, `wavToXgm2Pcm` for Genesis XGM2 PCM). Path-in, native-data-out.
-- **Running** - load the ROM into an emulated console (libretro cores as WASM) and step through it frame by frame.
-- **Seeing** - capture the framebuffer as a PNG and hand it to the agent.
-- **Driving** - emit controller input, run input scripts, replay sequences.
-- **Inspecting** - read CPU/video/save RAM, watch memory, disassemble, inspect sprites/palettes/tilemaps, read CPU + sound-chip state.
-- **Reverse-engineering & romhacking** - a full RE toolkit for modifying existing games: iterative value search (`memory({op:'search'})` → `memory({op:'searchNext'})`, the Cheat-Engine loop), `memory({op:'classify'})` (is this "table" really ASCII?), `breakpoint({on:'write'})` (the exact instruction that wrote a byte), `memory({op:'readCart'})` (confirm a patch is live in the running image), `input({op:'navigate'})` (drive menus by screen-change), `watch({on:'dma'})` (Genesis: which ROM offset a graphic was DMA'd from), a bundled cheat database as a free labeled RAM map, `disasm({target:'accessScan'})` (bound every instruction that can reach a RAM byte, indexed bases included), `disasm({target:'script'})` (decode in-game script interpreters from a declarative grammar), and a cross-platform [ROM-hacking playbook](packages/romdevtools/src/platforms/_guides/ROMHACKING_PLAYBOOK.md) (`platform({op:'doc', platform:'romhacking', name:'playbook'})`).
-- **Structural analysis & decompilation** - an open-source RE engine (Rizin + Ghidra, compiled to WebAssembly) covering **all 18 platforms** (incl. the 3D consoles' MIPS R3000/R4300 + SH-4): `disasm({target:'functions'})` (auto-detected function list, ranked real-code-first with a `looksLikeData` flag), `disasm({target:'cfg'})` (control-flow graph), `disasm({target:'xrefs'})` (deep cross-references following the analysis graph), **`disasm({target:'reachable', entries})`** (the CLOSED SET of basic blocks reachable from one or more entry points, following BOTH halves of every call - the callee AND the return site, which is what a recompiler, decompiler or coverage tool actually needs; computed jumps are not followed and the response says so, pointing at the live jumptable resolver below), `symbols({op:'analyze'})` (one-shot structural map), and `disasm({target:'decompile'})` (Ghidra C-like pseudocode, with hardware-register MMIO named and 6502 SLEIGH clutter folded to readable C - quality excellent on GBA/Genesis, good on Game Boy/Z80, rough on the 6502 family; on N64/PS1/Dreamcast the image is analyzed at its TRUE load address so calls and globals resolve, and an N64 splat project's segment map gives overlay-exact mapping with provenance). And the differentiator no static tool has: **live computed-jumptable recovery** - `breakpoint({on:'jumptable'})` runs the emulator to resolve the `JMP (table,X)` / RTS-trick dispatchers (game-state machines, script/battle VMs) that static analysis collapses to `(*_IRQ)()`. Understand *how* a routine works before you touch it; no $3,000 IDA license, no install.
-- **Saving/restoring** - named save states for try-this-then-undo workflows.
-- **Active Bezels** - an executable companion to a specific ROM (a `.ab` package) that runs once per emulated frame, reads the core's live memory, and renders the complete final scene: a map, a HUD, reconstructed world graphics, around or over the game. `loadMedia({useActiveBezel:true})` picks up the same-basename sidecar (`Game.nes` → `Game.ab`) and makes the composite the presented and captured picture. romdev is where a package gets **verified**, not just played: one can load cleanly, tick without trapping, emit perfectly valid draw commands, and still be completely wrong about the game - so `frame({op:'screenshot', source:'both'})` returns the composite and the raw core framebuffer for the *same* frame, alongside the three geometries (core framebuffer / intended display aspect / bezel scene) that are easy to conflate. Compare those against the guest's own memory reads and you are checking the package's *interpretation*, not merely that it drew something.
-- **Matching decompilation (N64 proven)** - `decomp({op})` runs the function-level *generate → compile → compare → refine* loop against a registered [splat](https://github.com/ethteck/splat) project's **own** compiler (IDO 5.3 via ido-static-recomp, or MIPS GCC) and build: `import` (ROM sha1 verified, toolchain fingerprinted, the exact per-file compile command captured from `make`), `plan` (payoff-ordered queue + batches over the call graph), `generate` (m2c with the translation unit's real type context), **`compare`** (the candidate compiled *inside* its TU with the TU's flags; one aggregate verdict from strict instruction+relocation equality, ROM-linked words, the function's own jump tables/literals, and the rest of the TU unchanged - a check that could not run is `unknown`/`error`, never `exact`), `search` (bounded decomp-permuter jobs), `integrate` (reviewable patch; apply + full-ROM byte verify, auto-revert on mismatch), `types` (evidence → proposed structs), `progress` (code bytes per object, asm/C/library kept apart), and the runtime side - `trace` (real PC breaks: arguments at entry, return value at `ra`), `coverage` (instruction-exact via the core's PC bitmap, per function and basic block), `overlays`/`symbolize` (which overlay is resident, by bytes in RAM), `smoke` (base vs rebuilt ROM, decoded pixels + registers). Ghidra's `disasm({target:'decompile'})` stays the *understanding* tool and now loads N64/PS1/Dreamcast segments at their true addresses. Start with `platform({op:'doc', platform:'n64', name:'decomp'})`.
-- **Native game runtimes (not just emulation)** - the same run/see/drive/debug loop works on two *native* game formats, not only libretro cores: **wasmcart** (`.wasc` - WASM games compiled from any language; created 2026) and **jsgame** (`.jsgame` - JavaScript canvas/WebGL games; created 2024). `loadMedia({platform:'wasmcart'|'jsgame'})` → `frame({op:'step'|'screenshot'})` → `input` - screenshots, scripted input, and deterministic frame-stepping over the exact same tools. wasmcart carts add a deterministic-replay path (`loadMedia({deterministicSeed})` - same seed + same input = identical frames), a debug-event timeline (`wasm({op:'events'})`), and an absolute pointer (`input({op:'pointer', x, y, left, right})`) for mouse-UI carts a gamepad vocabulary can't drive. Plus V8/WASM introspection an emulator can't give (peek the cart's WASM heap + exports; the JS game's globals). GL carts (wasm imports from the `gl` module) render headless on an **offscreen WebGL2 context** - screenshots and frame hashes show the real GPU draws, no window needed (wasmcart 0.6.0+; older installs fall back to stubbed GL, reported in `status.gl`) - and when a human is playing, `loadMedia({presentWindow:true})` gives the cart its own context so the playtest window presents by GPU blit + swap instead of round-tripping every frame through the CPU (measured `convertMs` 3.52 → 0 on a 1080p 3D cart); captures stay byte-identical to the headless path either way. `pack({target:'wasc'|'jsgame'})` zips a source dir into the distributable archive (the "build" step - romdev doesn't compile the WASM; you bring your own). Emulator-only tools (memory regions, cpuState, disasm) report *not-applicable* for these kinds via a capability descriptor.
-
-The deliverable is **the ROM**, not the tool: a standard, hardware-valid `.nes`/`.gba`/`.md`/... that runs anywhere ROMs run. The bundled WASM cores are the *dev instrument* (build → observe → iterate), not the distribution runtime.
+- **Building.** Per-platform toolchains (cc65, SDCC, RGBDS, asar, gcc and binutils for m68k/ARM/MIPS/SH, SGDK, PVSnesLib, libtonc and more) compiled to WebAssembly. Fork a working example game with `examples({op:'fork'})`, then `build({output:'run'})` builds, loads, runs and screenshots it in one call. Output ROMs get the checksums and headers real hardware needs.
+- **Assets.** `encodeArt` turns PNGs into tiles, tilemaps and palettes; `importArt` reads Aseprite/LibreSprite, Tiled, GIF and TexturePacker files; `sprites({op:'capture'})` lifts a multi-sprite character from a running game; `encodeAudio` produces SNES BRR, Genesis XGM2, GBA maxmod soundbanks, NES FamiTone2 data and note tables for the other sound chips.
+- **Running and inspecting.** libretro emulator cores as WebAssembly: step frames, take screenshots, drive input, read and write memory, inspect sprites, palettes, tilemaps, CPU and sound-chip state, save and restore states. `frame({op:'verify'})` reports whether a game is rendering without needing to look at the picture.
+- **Reverse engineering.** Value search, write/read/execution breakpoints, single-stepping, coverage traces, byte-exact rebuildable disassembly (`disasm({target:'project'})` and `build({output:'reassemble'})`), a bundled cheat database as a labeled RAM map, ROM patching with re-injection of compressed assets, custom-font text tools, and a [romhacking playbook](packages/romdevtools/src/platforms/_guides/ROMHACKING_PLAYBOOK.md).
+- **Analysis and decompilation.** Rizin and Ghidra compiled to WebAssembly: function detection, control-flow graphs, cross-references, reachable-block sets and C pseudocode on 18 platforms, including the MIPS and SH-4 3D consoles. `breakpoint({on:'jumptable'})` resolves computed-jump dispatchers by running the game.
+- **Static recompilation.** `disasm({target:'recompile', emit:'wasmcart'})` recompiles a whole NES, SNES (including its coprocessor carts), Game Boy, Game Boy Color, GBA, Master System, Game Gear or Genesis ROM into a wasmcart. `frame({op:'verifyRecompile'})` checks the result against the reference emulator core frame by frame (pixels, memory, audio, must-fail controls); `findDiverge`, `fuzzRecompile` and `traceInstructions` locate differences down to the instruction. A Genesis ROM can also be built as a native cart for the sync32 console.
+- **Matching decompilation.** `decomp({op})` drives a splat-based N64 or PlayStation decomp project: generate candidate C with m2c, compile it with the project's original compiler, compare per instruction, search with the permuter, and integrate with a full-ROM byte check. Everything runs as JavaScript and WebAssembly in process; no Python, make or host compiler. IDO, SGI's compiler, is proprietary and not distributed; build it once with `packages/romdevtools/scripts/build-ido.sh` from this repository or point `ROMDEV_IDO_DIR` at your own build. KMC gcc 2.7.2, EGCS 1.1.2, PS1 gcc 2.6.3 and mips-linux-gnu gcc 14 ship as WebAssembly.
+- **Native runtimes.** wasmcart (`.wasc`, WebAssembly games written in any language, with GL and WebGPU rendering) and jsgame (JavaScript canvas and WebGL games) run through the same load, step, screenshot and input loop, with cart introspection through `wasm({op})`.
+- **Active Bezels.** `.ab` companion packages that read a game's memory every frame and draw a composite scene (maps, HUDs). romdev returns the composite and the raw core frame for the same frame so a bezel can be checked against the game.
+- **A human in the loop.** `playtest()` opens an SDL window with gamepad support on the running game while the agent keeps working; `host({op:'play'})` shows a session on the `/livestream` page.
```
-your agent <--MCP--> romdev server <-> WASM libretro core <-> your game
- |
- +-> WASM homebrew toolchain (cc65, SDCC, SGDK, ...)
+your agent <--MCP / HTTP--> romdev server <-> WASM libretro core <-> your game
+ |
+ +-> WASM toolchains, Rizin/Ghidra, recompiler
```
-## Who is it for?
-
-- **Homebrew developers** who want a tighter loop than reload-the-emulator-by-hand - build, run, inspect, and patch real ROMs from one tool surface, drive it from your editor's AI, a TUI, the Inspector, or your own scripts.
-- **Anyone making a retro game with an AI's help**, no prior homebrew experience needed. Run `npx romdevtools`, point your coding assistant at it, and describe the game you want.
-- **Reverse-engineers and romhackers** - disassembly, control-flow graphs, a decompiler, live memory search, and write-breakpoints across all 18 systems, no $3,000 IDA license.
-
-Every capability is exposed as a tool, so a coding agent can drive the whole loop end-to-end - but the tools are just as usable by hand. The agent is the interface, not a requirement.
-
-## Supported systems - pick your platform
-
-Nineteen consoles/computers, oldest → newest - sixteen 2D systems (including the open-hardware GameTank and sync32) plus three 3D consoles (N64, PlayStation, Dreamcast) - plus the **PICO-8** fantasy console and the two **native game runtimes** (wasmcart, jsgame), each its own tier after the 3D consoles. They vary enormously in how hard a game is to make and how hard an existing game is to hack. **Build** = write code → compile → run. **Hack** = modify an existing commercial ROM (find data → patch → reinsert). A system can be easy on one and hard on the other. (Difficulty is rated *as it feels through romdev today* - see the note under the table; it gets easier as the tooling improves.)
-
-| System | Year | Languages (toolkit) | Build a game | Romhack a game | Best for |
-|---|---|---|---|---|---|
-| **Atari 2600** | 1977 | 6502 asm (dasm) | 🔴 Hardest | 🟠 Hard | The deep end. "Race the beam": no framebuffer, 128 B RAM, every scanline cycle-counted. Iconic, brutal, deeply rewarding. |
-| **Commodore 64** | 1982 | C / 6502 asm (cc65) | 🟢 Easy | - | 40 years of docs, weird but forgiving hardware. A great first 8-bit target. |
-| **MSX / MSX2** | 1983 | C / Z80 asm (SDCC) | 🟢 Easy | - | Z80 + the same TMS9918/V9938 VDP family as the Master System. Boots cartridge homebrew on the open C-BIOS (no proprietary ROM). Big international library. |
-| **NES / Famicom** | 1983 | C / 6502 asm (cc65) | 🔴 Hard | 🟡 Medium | "Everyone knows the NES" - but the PPU is unforgiving (OAM/NMI timing, CHR-RAM traps, silent black screens). Hacking is friendlier: lots of games store data plainly; the disassembler is mapper-aware. |
-| **Sega Master System** | 1985 | C / Z80 asm (SDCC) | 🟢 Easy | 🟡 Medium | Simple Z80 + VDP. Near-identical twin of the Game Gear. |
-| **PC Engine / TurboGrafx-16** | 1987 | C / HuC6280 asm (cc65) | 🟡 Medium | - | HuC6280 (65C02 superset) + the HuC6270 VDC. cc65 has no sprite library, so romdev ships a direct-register helper lib; 9-bit GRB color, 64 hardware sprites. HuCards boot with no BIOS. |
-| **Atari 7800** | 1986 | C / 6502 asm (cc65) | 🔴 Hard | 🟠 Hard | MARIA display-list graphics (~100 sprites, little flicker) but a unique model with sparse docs. |
-| **Sega Genesis / Mega Drive** | 1988 | C (SGDK) / 68000 asm (vasm) | 🟡 Medium | 🟢 Easy | SGDK is a real C engine (high productivity) with a big API + sharp edges. **Easiest system to hack:** flat 16 MB 68000 addressing, no bank-switching, near-ASCII text in many games. |
-| **Game Boy** | 1989 | C / SM83 asm (SDCC / RGBDS) | 🟢 Easy | 🟢 Easy | The recommended starting point. Simple hardware, mature C tooling; games often store data uncompressed → easy to hack too. |
-| **Atari Lynx** | 1989 | C / 6502 asm (cc65) | 🟡 Medium | - | Color handheld; Suzy/Mikey display-list sprite engine is its own thing + a tiny community = few references. |
-| **Game Gear** | 1990 | C / Z80 asm (SDCC) | 🟢 Easy | 🟡 Medium | Same Mode-4 VDP as the Master System; only the visible window differs. |
-| **Super Nintendo (SNES)** | 1990 | C (PVSnesLib) / 65816 asm (asar) | 🟡 Medium | 🟡 Medium | PVSnesLib works but is quirky (many "looks right, renders nothing" traps). Big ROMs often skip compression → medium to hack. |
-| **Game Boy Color** | 1998 | C / SM83 asm (SDCC / RGBDS) | 🟢 Easy | 🟢 Easy | The Game Boy with a real color palette - same easy tooling, plus CGB color. |
-| **Game Boy Advance** | 2001 | C (libtonc / libgba) | 🟡 Medium | - | 32-bit ARM, comfortable C with the well-documented Tonc library - but a big machine (IRQ/DMA/video modes = lots of surface to learn). |
-| **GameTank** | 2024 | C / 6502 asm (cc65) | 🟡 Medium | - | Clyde Shaffer's **open-hardware** W65C02S console - a 128×128 framebuffer drawn by a hardware blitter + a second 65C02 audio coprocessor. Full Tier-1 (build/run/cpuState/watchpoints/audioDebug/cart). Open docs + a clean SDK make it a friendly modern 8-bit target; ships ~July 2026. |
-| **sync32** | 2026 | C (arm-none-eabi, Cortex-M33) | 🟢 Easy | - | An RP2350 console with a **flat framebuffer and a function-pointer ABI** - no PPU, no tilemap, no banking, no scanline timing. A game is `game_main(api)` drawing into a byte array, so it is the gentlest build target here despite being the newest hardware. Build/run/cpuState/memory/palette are wired; there is no romhack column because there are no commercial ROMs. |
-
-The three **3D consoles** are a newer, distinct tier - they compile + boot + render on the **real GPU**, but they're at a different maturity than the 2D lineup: no genre scaffolds yet, and their renderable starting points come from open GPU SDKs (libdragon / PSn00bSDK) rather than romdev's own helper libs. Build = bare C that drives the GPU; Hack = code analysis works (disasm/decompile), data-romhack tooling is minimal.
-
-| System | Year | Languages (toolkit) | Build a game | Romhack a game | Best for |
-|---|---|---|---|---|---|
-| **Nintendo 64** | 1996 | C (mips-elf-gcc) | 🟠 Hard | - | MIPS R4300 + the RDP/RSP. Renders on glide64 through the GPU; bare C drives a GBI display list (or use libdragon). The 3D end of the pool. |
-| **Sony PlayStation** | 1994 | C (mips-elf-gcc) | 🟠 Hard | - | MIPS R3000. Renders on Beetle PSX HW through the GPU; OpenBIOS embedded (no Sony firmware). Bare C writes the GP0/GP1 ports, or link PSn00bSDK. |
-| **Sega Dreamcast** | 1998 | C (sh-elf-gcc) | 🟠 Hard | - | SH-4 + PowerVR2. Boots an ELF on Flycast's reios HLE; the bundled `dc.h` brings up a 640×480 framebuffer. No KallistiOS yet (bare-metal C). |
-
-The **PICO-8** fantasy console is its own tier again - not a hardware machine but a Lua VM ([FAKE-08](https://github.com/jtothebell/fake-08), MIT, no BIOS). It runs `.p8` (Lua source) and `.p8.png` (cart-in-a-PNG) carts at 128×128 with sound, and it's the **friendliest build target on the whole list**: the "code" is plain Lua, so `build({platform:'pico8', source: lua})` just packages a runnable `.p8` (no compiler, no linker, no crt0). Because it's a VM, there's no machine code to disassemble - `disasm({target:'source'})` hands back the cart's Lua directly, and `memory({region:'system_ram'})` reads its 64 KB address space. Thousands of freely-shareable community carts run as-is.
+The tools work just as well called by hand or from scripts.
-| System | Year | Language (toolkit) | Build a game | "Hack" a cart | Best for |
-|---|---|---|---|---|---|
-| **PICO-8** | 2015 | Lua (FAKE-08) | 🟢 Easiest | 🟢 Easy | The gentlest on-ramp: Lua carts are plain text, so "build" is packaging and "hack" is editing source. Huge community library. |
+## Supported systems
-The two **native game runtimes** are the newest tier - not emulated hardware but native game formats driven through the *same* run/see/drive/debug loop (`loadMedia` → `frame` → `input` → `playtest`). Here romdev is the **harness, not the compiler**: you bring your own toolchain, `pack({target:'wasc'|'jsgame'})` packages the distributable, and the deliverable is the exact artifact you debugged. Emulator-only tools (cpuState, disasm, memory regions) report *not-applicable* via a capability descriptor; in their place you get WASM/V8 introspection an emulator can't offer.
+**Build** is writing a new game; **Hack** is modifying an existing one. Ratings describe how much friction to expect with romdev's current examples and libraries, not the hardware in the abstract. A dash means there is no romhack tooling beyond code analysis for that system yet.
-| System | Year | Language (toolkit) | Build a game | "Hack" a cart | Best for |
+| System | Year | Languages (toolkit) | Build | Hack | Notes |
|---|---|---|---|---|---|
-| **wasmcart** | 2026 | any language that targets WASM - C, C++, Rust, Zig, mruby, ... (`wc_cart.h` ABI) | 🟢 Easy | - | Ship the same `.wasc` you debugged. The harness adds deterministic replay (`loadMedia({deterministicSeed})`), a debug-event timeline (`wasm({op:'events'})`), named debug state, absolute pointer input for mouse-UI carts, conformance verdicts ("won't load, why"), regression goldens - and GL carts render headless on an offscreen WebGL2 context, so screenshots show the real GPU draws. |
-| **jsgame** | 2024 | JavaScript (canvas / WebGL2) | 🟢 Easy | - | The web-game developer's on-ramp: run a JS canvas/WebGL game like a cart - screenshots, scripted input, deterministic frame-stepping - plus V8 introspection (read the game's live globals). |
-
-**Difficulty legend:** 🟢 Easy · 🟡 Medium · 🟠 Hard · 🔴 Hardest. **Build** ratings come from an agent that actually shipped games across the lineup; **Hack** ratings are for text/data edits (a `-` means no romhack data yet - it's CPU-and-game-dependent, and any game using custom compression jumps to Hard regardless of system).
-
-The **RE analysis engine** (control-flow graphs, cross-references, function detection, and a Ghidra decompiler) works on **all 18 systems** - including the 3D consoles' MIPS R3000/R4300 and SH-4 - regardless of the Hack rating above; the rating reflects how hard the *data* is to edit, not whether the *code* can be analyzed. Decompiler readability tracks the CPU: excellent on the 32-bit ARM (GBA) and 68000 (Genesis), good on the MIPS/SH-4 3D CPUs and Z80, down to rough on the 8-bit 6502 family. (The byte-exact *rebuildable-project* disassembler - `disasm({target:'project'})` - covers the 15 classic platforms, and **`build({output:'reassemble'})` rebuilds any of them into a byte-identical ROM in one call**; the 3D consoles get analysis/decompile, not full reassembly yet.)
-
-> **These ratings reflect difficulty *with romdev's current tooling* - not an abstract take on the hardware.** The biggest predictor of how hard a platform feels here isn't its raw hardware but the quality of its scaffolds, snippets, and SDK integration. Good tooling moves a platform a whole tier: the Atari 2600 is the hardest hardware on the list, yet a thick, hardware-verified snippet shelf made it *hard-but-shippable*; the same agent that found NES "hard" shipped on the C-and-SDK platforms in a single pass. **These numbers drift toward easier over time** as scaffolds, footgun fixes, and richer runtimes land. Treat the column as "expect roughly this much friction today," not "this system is permanently this hard."
-
-**If you just want to ship something fast:** Game Boy, Game Boy Color, Master System, Game Gear, or C64. **If you want a challenge / iconic constraint:** NES or Atari 2600. **If you want to modify a classic game:** Genesis or Game Boy (their data is usually uncompressed). The harder systems are very doable but take more iterations - worth choosing deliberately.
-
-## Each platform ships a real SDK + sound + scaffolds
-
-Every 2D platform has a working core, ready-made starter projects, and **5 genre scaffolds** - shmup / platformer / puzzle / sports / racing - plus a music demo. That now includes the Atari 2600 (all five, match-3 board and all), the open-hardware GameTank, and sync32. The 3D consoles are the exception: N64 and PlayStation ship the five, Dreamcast ships starter projects only. PC Engine and MSX *also* ship a hardware helper library and sprite/music example projects alongside their genre scaffolds; Genesis adds a `two_plane_parallax` scaffold (hardware scroll, no per-frame tilemap writes). Each platform has a sound API, per-platform `MENTAL_MODEL.md` + `TROUBLESHOOTING.md` docs (readable in-session via `platform({op:'doc'})`), and debug helpers. Scaffold a project in one call with `scaffold({op:'project'})` (or `scaffold({op:'game'})` for the genre-shaped baselines). Every scaffold builds with zero warnings and renders visible content (checked via `frame({op:'verify'})`).
-
-| Platform | Core | Compiler / SDK | Sound | Music engine |
-|---|---|---|---|---|
-| NES | fceumm | cc65 | `sound_play_tone/noise` (APU) | FamiTone2 |
-| Game Boy | gambatte | SDCC (sm83) / RGBDS | `sound_play_tone/noise` (DMG APU) | hUGEDriver |
-| Game Boy Color | gambatte (CGB) | SDCC / RGBDS | APU + CGB color | hUGEDriver |
-| SNES | snes9x | PVSnesLib (C) / asar (asm) | `sfx_play` (SPC700 + BRR) | SPC700 engine |
-| Genesis | genesis_plus_gx | SGDK (m68k-gcc) / vasm (asm) | `sfx_*` PSG | XGM2 via SGDK |
-| SMS | genesis_plus_gx | SDCC (z80) | `sfx_*` SN76489 PSG | 3-voice PSG tracker |
-| Game Gear | genesis_plus_gx | SDCC (z80) | `sfx_*` (same PSG) | PSG tracker |
-| C64 | vice_x64 | cc65 | `sfx_*` SID (ADSR) | 3-voice SID sequencer |
-| GBA | mGBA | libtonc / libgba (arm-gcc) | `sfx_*` libtonc | maxmod |
-| Atari Lynx | handy | cc65 | `sfx_*` MIKEY 4-voice | cc65 lynx audio |
-| Atari 2600 | stella2014 | dasm (asm) | (asm) | 2-voice 6507 chiptune |
-| Atari 7800 | prosystem | cc65 | `sfx_*` TIA | 2-voice TIA tracker |
-| PC Engine | geargrafx | cc65 | `psg_tone` (HuC6280 PSG, 6 ch) | hand-authored PSG |
-| MSX / MSX2 | blueMSX | SDCC (z80) | `msx_psg_tone` (AY-3-8910) | hand-authored PSG |
-| Nintendo 64 | parallel_n64 (glide64, **GPU**) | mips-gcc (C) | AI / RSP | - |
-| PlayStation | beetle_psx_hw (**GPU**) | mips-gcc (C; PSn00bSDK) | SPU | - |
-| Dreamcast | flycast (**GPU**) | sh-gcc (C) | AICA | - |
-| wasmcart | CartHost (native WASM host - no emulator; GL carts on an offscreen WebGL2 context) | bring-your-own WASM toolchain (`wc_cart.h`) | 48 kHz PCM ring (`wc_audio` / `wc_pcm_mixer`) | - |
-| jsgame | rungame (native V8 host - no emulator) | JavaScript (canvas / WebGL2) | game's own WebAudio graph (not captured in-harness yet) | - |
-
-(The two native-runtime rows are the harness tier: no scaffolds and no bundled compiler - `pack({target:'wasc'|'jsgame'})` packages a source dir you built with your own toolchain.)
-
-The `platformer` scaffold side-scrolls (hardware camera + per-platform column streaming) on every platform except NES and the Atari 2600 - both single-screen, since neither has hardware background scroll.
-
-The three 3D consoles (N64 / PlayStation / Dreamcast) render on the **real GPU** through [`native-gles`](https://github.com/monteslu/native-gles) - headless OpenGL/EGL, no browser, no software rasterizer - one engine across all three. PlayStation embeds [OpenBIOS](https://github.com/grumpycoders/pcsx-redux) (MIT, region-free), so no proprietary firmware ships. These don't ship genre scaffolds yet; their renderable starting points come from the open GPU SDKs - [libdragon](https://github.com/DragonMinded/libdragon) (Unlicense) for N64, [PSn00bSDK](https://github.com/Lameguy64/PSn00bSDK) (MPL) for PlayStation - which emit the real GPU geometry the GL cores render. (The 2D consoles' software libs render to a CPU framebuffer the GL cores don't scan out.)
-
-## How it's packaged
-
-`romdev` is a small **monorepo** of npm packages. The thing you install is `romdevtools`; it hard-depends on a set of `romdev-*` binary packages that carry the WebAssembly:
-
-- **[`romdevtools`](./packages/romdevtools)** - the tool server (HTTP routes + Agent Skill + MCP), all generic tools, scaffolds, runtime/library source, debug helpers, and the `romdevtools` / `romdev-mcp` (alias) / `romdevtools-cli` binaries. The fast-churning layer; ships **zero wasm**.
-- **`romdev-core-*`** (12) - shared emulator cores: `fceumm`, `gambatte`, `gpgx`, `vice`, `handy`, `prosystem`, `geargrafx` (PC Engine), `bluemsx` (MSX), `gametank` (GameTank), and the GPU cores `parallel-n64` (N64), `beetle-psx-hw` (PlayStation), `flycast` (Dreamcast).
-- **[`romdev-core-host`](./packages/romdev-core-host)** + **[`romdev-core-runner`](./packages/romdev-core-runner)** (2) - the ISOMORPHIC libretro host runtime (paths under Node, factory + bytes in a browser/worker, one implementation) and the SDL "play it in a window" tier on top of it, published standalone so SDKs, web IDEs, and tools can run cores without the server. The server consumes the same host.
-- **`romdev-platform-*`** (3) - self-contained platform bundles where the core + compiler are used by no one else: `snes`, `gba`, `atari2600`.
-- **`romdev-toolchain-*`** (7) - shared compilers: `cc65`, `sdcc`, `m68k-gcc`, `vasm`, `rgbds`, `mips-gcc` (N64/PS1 C), `sh-gcc` (Dreamcast C).
-- **`romdev-analysis*`** (2) - the RE engine: `romdev-analysis` (Rizin → WASM) + `romdev-analysis-decompiler` (Ghidra decompiler + SLEIGH specs → WASM).
-- **`romdev_game_codes`** (1) - the bundled game-code / cheat database (~30 MB of pre-parsed cheats for thousands of known ROMs across 13 platforms). Split out so the main package stays small and the DB grows on its own cadence; lazy-loaded one platform at a time.
-
-`romdevtools` resolves each core/compiler from its package lazily - a toolchain's WASM is only loaded into memory the first time you build for that platform, so booting the server is fast and a session only pays for the platforms it actually uses. WASM is a **build output**: it ships via the npm packages, not committed to this git repo (which holds the source, recipes, and version pins). See [packages/romdevtools/BUILDING.md](./packages/romdevtools/BUILDING.md) for the platform × core × toolchain matrix and how the wasm is built (a pinned Emscripten container).
+| Atari 2600 | 1977 | 6502 asm (dasm) | Hardest | Hard | No framebuffer, 128 bytes of RAM, every scanline cycle-counted. |
+| Commodore 64 | 1982 | C / 6502 asm (cc65) | Easy | - | Forgiving hardware and decades of documentation. Boots on the MEGA65 Open ROMs. |
+| MSX / MSX2 | 1983 | C / Z80 asm (SDCC) | Easy | - | Z80 with the TMS9918/V9938 VDP family. Runs on the open C-BIOS. |
+| NES / Famicom | 1983 | C / 6502 asm (cc65) | Hard | Medium | The PPU is unforgiving (OAM/NMI timing, CHR-RAM). Many games store data plainly; the disassembler is mapper-aware. |
+| Master System | 1985 | C / Z80 asm (SDCC) | Easy | Medium | Simple Z80 and VDP; near twin of the Game Gear. |
+| Atari 7800 | 1986 | C / 6502 asm (cc65) | Hard | Hard | MARIA display-list graphics with sparse documentation. |
+| PC Engine / TurboGrafx-16 | 1987 | C / HuC6280 asm (cc65) | Medium | - | romdev ships a direct-register helper library; HuCards need no BIOS. |
+| Genesis / Mega Drive | 1988 | C (SGDK) / 68000 asm (Motorola syntax, GNU as) | Medium | Easy | Flat 68000 addressing and no bank switching make it the easiest to hack. |
+| Game Boy | 1989 | C / SM83 asm (SDCC, RGBDS) | Easy | Easy | The recommended starting point. |
+| Atari Lynx | 1989 | C / 6502 asm (cc65) | Medium | - | Suzy/Mikey sprite engine with few references. |
+| Game Gear | 1990 | C / Z80 asm (SDCC) | Easy | Medium | Master System VDP with a smaller window and 12-bit colour. |
+| Super Nintendo | 1990 | C (PVSnesLib) / 65816 asm (asar) | Medium | Medium | PVSnesLib has "renders nothing" traps; the mental model lists them. |
+| Game Boy Color | 1998 | C / SM83 asm (SDCC, RGBDS) | Easy | Easy | The Game Boy toolchain plus CGB colour. |
+| Game Boy Advance | 2001 | C (libtonc, libgba) | Medium | - | 32-bit ARM with a large hardware surface. |
+| GameTank | 2024 | C / 6502 asm (cc65) | Medium | - | An open-hardware W65C02S console: a 128x128 framebuffer drawn by a blitter, and a second 65C02 for audio. |
+| sync32 | 2026 | C (arm-none-eabi, Cortex-M33) | Easy | - | An open RP2350-based console: a flat framebuffer and a function-pointer ABI, no PPU, tilemap or banking. |
+| Nintendo 64 | 1996 | C (mips-elf-gcc, libdragon) | Hard | - | Rendered on the GPU through parallel-n64's glide64. |
+| PlayStation | 1994 | C (mips-elf-gcc, PSn00bSDK) | Hard | - | Rendered on the GPU through Beetle PSX HW; boots OpenBIOS, no Sony firmware. |
+| Dreamcast | 1998 | C (sh-elf-gcc) | Hard | - | Rendered on the GPU through Flycast with its reios HLE BIOS; bare-metal C. |
+| PICO-8 | 2015 | Lua (FAKE-08) | Easiest | Easy | Carts are Lua source, so building is packaging and hacking is editing. |
+| wasmcart | 2026 | Any language that targets WebAssembly | Easy | - | You bring the compiler; romdev runs, inspects and packs the cart. Carts need wasmcart ABI v4. |
+| jsgame | 2024 | JavaScript (canvas, WebGL2) | Easy | - | JavaScript games run like carts, with V8 introspection. |
+
+The Rizin/Ghidra analysis engine works on all 19 systems except sync32, whatever the Hack rating; the rating is about editing data, not analysing code. Decompiler output is most readable on ARM (GBA) and 68000 (Genesis), good on Z80 and the MIPS/SH-4 consoles, and rough on the 6502 family. Byte-exact rebuildable disassembly covers the 15 classic 2D systems.
+
+To ship something quickly, start with Game Boy, Game Boy Color, Master System, Game Gear, C64 or PICO-8. To modify an existing game, Genesis and Game Boy are the gentlest.
+
+## Examples, sound and docs per platform
+
+Every classic platform ships starter projects, a sound API, a music demo on that platform's usual engine, and five genre examples (shmup, platformer, puzzle, sports, racing); the Atari 2600 has four (no puzzle). GameTank, sync32, PICO-8, N64, PlayStation and Dreamcast ship genre examples too. Fork one with `examples({op:'fork', example:'nes/platformer', name, path})`. The platformer side-scrolls with a hardware camera on every platform except NES and the Atari 2600. Each platform has a mental model and troubleshooting guide readable in session with `platform({op:'doc', platform, name})`.
+
+| Platform | Core | Compiler / SDK | Music engine |
+|---|---|---|---|
+| NES | fceumm | cc65 | FamiTone2 |
+| Game Boy / Color | gambatte | SDCC, RGBDS | hUGEDriver |
+| SNES | snes9x (bsnes as an alternate) | PVSnesLib, asar | SPC700 driver |
+| Genesis | genesis_plus_gx | SGDK (m68k gcc), 68000 asm (m68k GNU as) | XGM2 |
+| Master System / Game Gear | genesis_plus_gx | SDCC | PSG tracker |
+| C64 | VICE x64 | cc65 | SID sequencer |
+| GBA | mGBA | libtonc, libgba (arm gcc) | maxmod |
+| Atari Lynx | handy | cc65 | Lynx audio |
+| Atari 2600 | stella2014 | dasm | 2-voice TIA |
+| Atari 7800 | prosystem | cc65 | 2-voice TIA tracker |
+| PC Engine | geargrafx | cc65 | HuC6280 PSG |
+| MSX / MSX2 | blueMSX | SDCC | AY-3-8910 PSG |
+| GameTank | GameTank core | cc65 | ACP audio coprocessor |
+| sync32 | s32core | arm-none-eabi gcc | game-side software synth |
+| Nintendo 64 | parallel-n64 (glide64, GPU) | mips gcc | - |
+| PlayStation | Beetle PSX HW (GPU) | mips gcc, PSn00bSDK | - |
+| Dreamcast | Flycast (GPU) | sh gcc | - |
+| PICO-8 | FAKE-08 | Lua | built in |
+| wasmcart | wasmcart host (no emulator) | your own | 48 kHz PCM ring |
+| jsgame | rungame (no emulator) | your own | WebAudio |
+
+The 3D consoles render on the GPU through [native-gles](https://github.com/monteslu/native-gles) (headless OpenGL ES, no browser).
+
+## Packages
+
+The package you install is `romdevtools`. It depends on `romdev-*` packages that carry the WebAssembly binaries, so each one can be versioned and reused separately. A platform's binaries load the first time you use that platform.
+
+| Package group | Packages |
+|---|---|
+| Server | [`romdevtools`](./packages/romdevtools): the tool server (MCP, HTTP, Agent Skill), examples, libraries, docs. Bins: `romdevtools`, `romdevtools-cli`, `romdev-mcp` (alias). |
+| Emulator cores (15) | `romdev-core-fceumm`, `-gambatte`, `-gpgx`, `-vice`, `-handy`, `-prosystem`, `-geargrafx`, `-bluemsx`, `-gametank`, `-bsnes`, `-fake08`, `-s32core`, `-parallel-n64`, `-beetle-psx-hw`, `-flycast` |
+| Core runtime (2) | [`romdev-core-host`](./packages/romdev-core-host) (the libretro host, usable without the server) and [`romdev-core-runner`](./packages/romdev-core-runner) (an SDL window over it) |
+| Platform bundles (4) | `romdev-platform-snes`, `-gba`, `-atari2600`, `-sync32`: a core and compiler used by no other platform |
+| Toolchains (7) | `romdev-toolchain-cc65`, `-sdcc`, `-rgbds`, `-m68k-gcc`, `-mips-gcc` (also armips and mips-linux-gnu binutils), `-sh-gcc`, `-decomp-gcc` (KMC, EGCS and PS1 gcc for decomp projects) |
+| Analysis (2) | `romdev-analysis` (Rizin), `romdev-analysis-decompiler` (Ghidra decompiler and SLEIGH specs) |
+| Decomp tools (6) | `romdev-splat`, `romdev-spimdisasm`, `romdev-rabbitizer`, `romdev-m2c`, `romdev-permuter`, `romdev-pycparser`: JavaScript and WebAssembly ports of the community decomp tools |
+| Audio (4) | `romdev-famitone`, `romdev-maxmod`, `romdev-xgm2`, `romdev-audio-resampler` |
+| Data (1) | `romdev_game_codes`: the cheat database used as a labeled RAM and code map, loaded one platform at a time |
+
+`romdev-toolchain-ido` is private and never published; see "Matching decompilation" above.
+
+The WebAssembly binaries are build outputs shipped through npm; this repository holds the sources, build scripts, patches and version pins. [packages/romdevtools/scripts/BUILD_MAP.md](./packages/romdevtools/scripts/BUILD_MAP.md) maps each binary to the script that builds it.
## Connect
-Boot the server (it stays in the foreground - `Ctrl-C` to stop):
-
```bash
-npx romdevtools # tool server on http://127.0.0.1:7331/mcp
+npx romdevtools # MCP on http://127.0.0.1:7331/mcp
```
-The first run downloads the cores/toolchains; later runs start instantly from the npm cache. An **optional observer** for watching tool calls live is at `http://127.0.0.1:7331/livestream` - purely for humans, no agent needs it.
-
-Then register `http://127.0.0.1:7331/mcp` (streamable-HTTP transport) with your agent:
+The first run downloads the packages; later runs start from the npm cache. `PORT` and `HOST` change the bind address. `http://127.0.0.1:7331/livestream` shows tool calls and running sessions live for a human watching.
### Claude Code
@@ -159,8 +129,6 @@ claude mcp add --transport http romdev http://127.0.0.1:7331/mcp
### opencode
-Add it to `opencode.json` (the `type` must be `"remote"` for an HTTP server):
-
```json
{
"$schema": "https://opencode.ai/config.json",
@@ -176,52 +144,52 @@ Add it to `opencode.json` (the `type` must be `"remote"` for an HTTP server):
### Codex CLI
-Either run `codex mcp add romdev --url http://127.0.0.1:7331/mcp`, or add the table to `~/.codex/config.toml`:
+```bash
+codex mcp add romdev --url http://127.0.0.1:7331/mcp
+```
+
+or in `~/.codex/config.toml`:
```toml
[mcp_servers.romdev]
url = "http://127.0.0.1:7331/mcp"
```
-In a Codex session, `/mcp` lists the connected servers and their tools.
-
-### Any other MCP client
+### Other MCP clients and plain HTTP
-It's a standard **streamable-HTTP** MCP server - point any MCP-capable client at `http://127.0.0.1:7331/mcp`. Set `PORT` / `HOST` env vars to change the bind address.
+Any streamable-HTTP MCP client can use `http://127.0.0.1:7331/mcp`. Both the session-based protocol (an `initialize` handshake and `Mcp-Session-Id`) and the stateless 2026-07-28 revision are served on that endpoint; on the stateless revision, pass one stable `session` argument on every call so your calls reach the same emulator.
-**Both protocol eras are served on that one endpoint.** Legacy clients (the `initialize` handshake plus `Mcp-Session-Id`) work exactly as before. Clients speaking the stateless **2026-07-28** revision - no handshake, no session id, protocol version and capabilities in each request's `_meta` - are served natively, and `server/discover` advertises what the server supports. That revision has no protocol session to carry your identity, so the server ties your calls to *your* emulator three ways, in this order: a `_meta["dev.romdev/sessionHandle"]` handle; the optional **`session` argument every tool accepts** (the form an agent can produce from inside a tool call - pass one stable slug on every call); or, when a call names nothing, **your keep-alive connection** - the server keys the session to it and each result ends with a `session: ` line you can pass back. Claude Code 2.1.x names nothing, so it gets the connection default and the reminder line. Over plain HTTP the same job is done by the `x-romdev-session` header (send it on every call, and reuse ONE `Mcp-Session-Id` - re-initializing per call is a fresh session even with the header set).
+Without MCP, every tool is an HTTP route: `POST /tool/{name}` with a JSON body and an `x-romdev-session` header. `GET /openapi.json` describes them, `GET /documentation` is a browsable console, and `GET /skills/romdev/SKILL.md` is an Agent Skill generated from the running server.
----
-
-Then just describe what you want:
+Then describe what you want:
```
> Make me a tiny NES game where a sprite moves around the screen.
-[agent: scaffold({op:"game", platform:"nes", genre:"platformer"})]
-[agent: build({output:"run", platform:"nes", path}) → builds, loads, runs, screenshots in one call]
-[agent sees the result, iterates]
+[agent: examples({op:"fork", example:"nes/platformer", name:"mygame", path:"/path/to/mygame"})]
+[agent: build({output:"run", platform:"nes", path:"/path/to/mygame"}) -> builds, loads, runs, screenshots]
+[agent looks at the result and iterates]
```
-`romdev` also doubles as a plain emulator: `romdev-cli play game.gba` opens an SDL window with hot-plug controllers and live fps in the title bar.
+`romdevtools-cli play game.gba` also works as a plain emulator: an SDL window with hot-plugged controllers and live fps in the title bar.
## Development
-This is an npm-workspaces monorepo (Node 24+):
+An npm-workspaces monorepo (Node 24 or newer):
```bash
-git clone git@github.com:monteslu/romdev.git
+git clone https://github.com/monteslu/romdev.git
cd romdev
npm install
-npm test # runs each package's tests
+npm test
```
-The bundled WASM is built from pinned upstream source in a reproducible Emscripten container - see [packages/romdevtools/BUILDING.md](./packages/romdevtools/BUILDING.md). You only need to rebuild it when bumping an upstream version or adding a platform; day-to-day work uses the already-built wasm in the binary packages.
-
-Development workflow notes: [measured decompilation, bounded search and SMS IR](./packages/romdevtools/docs/decomp-throughput.md). These extend existing tools; the notes distinguish implemented behavior, verification limits and deployment requirements.
+The WebAssembly binaries are built from pinned upstream sources in a reproducible Emscripten container; see [BUILD_MAP.md](./packages/romdevtools/scripts/BUILD_MAP.md). You only rebuild them when bumping an upstream or adding a platform. [docs/decomp-throughput.md](./packages/romdevtools/docs/decomp-throughput.md) describes the measured decompilation workflow, bounded permuter search and Z80 IR export.
## License
-romdev's code is **MIT**, and **the games you build are yours - including to
-sell.** Full details + the third-party component inventory: [LICENSE](./LICENSE)
-and [NOTICE](./NOTICE).
+romdev's own code is MIT ([LICENSE](./LICENSE)). The third-party components it bundles keep their own licences, listed in [NOTICE](./NOTICE).
+
+Games you build with romdev are yours, including to sell; the bundled runtime libraries they link are permissively licensed (see NOTICE).
+
+Recompiled carts are different: a cart made by the static recompiler contains code ported from the reference emulator (GPL, MPL or non-commercial terms depending on the platform) as well as the original game's code. Each recompiled cart carries a `licence` entry naming those components, and NOTICE explains the terms.
diff --git a/browser-payloads.json b/browser-payloads.json
index 010a9860..b29ab177 100644
--- a/browser-payloads.json
+++ b/browser-payloads.json
@@ -1,4 +1,4 @@
{
- "release": "browser-payloads-4be2b1a7777a",
- "sha256": "6a05620de4728392867eea07e87c2f6677cb0789197645c7b3559f9b0353c95d"
+ "release": "browser-payloads-6f59c4b0d7a7",
+ "sha256": "2ef2943b9891c0ca98e592dbfd5b6c5ba7ade5544268821b0b3d722ab4e540d7"
}
diff --git a/build-image/Dockerfile b/build-image/Dockerfile
index 95ab964c..3587ed02 100644
--- a/build-image/Dockerfile
+++ b/build-image/Dockerfile
@@ -7,7 +7,7 @@
# bit-reproducible across emcc versions, so a bump is a real change.
#
# Covers the "light" builds: all emulator cores + the cc65/sdcc/asar/dasm/
-# vasm/rgbds toolchains (emcc + a Makefile/cmake). The heavy gcc-family
+# rgbds toolchains (emcc + a Makefile/cmake). The heavy gcc-family
# cross-toolchains (arm-gcc for GBA, m68k-gcc for Genesis-C) need a native
# cross-gcc bootstrap and are NOT covered here yet - follow-up image.
FROM emscripten/emsdk:4.0.18
diff --git a/package-lock.json b/package-lock.json
index 8d23d3b2..99ecc10e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -717,6 +717,18 @@
"@types/node": "*"
}
},
+ "node_modules/@viz-js/viz": {
+ "version": "3.31.0",
+ "resolved": "https://registry.npmjs.org/@viz-js/viz/-/viz-3.31.0.tgz",
+ "integrity": "sha512-r7zlQdRvcwvIpjHGgs+KNWHeE/P5/Dq7k8ZAKaMCbZqomxCBJV78gVuQYaHzFVca+kB0mX0fMW9UFevCOBG50A==",
+ "license": "MIT"
+ },
+ "node_modules/@webgpu/types": {
+ "version": "0.1.72",
+ "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.72.tgz",
+ "integrity": "sha512-0cF7RFM2edNoiIS1ODJp0/Gzv4/xSXhwoR0YCza+OWpJWtn4wmo9DvK91aLlH9+uUnwIriP7ZiC3WitmyhuzBw==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/accepts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -2192,6 +2204,21 @@
"node": ">= 0.8.0"
}
},
+ "node_modules/libsodium": {
+ "version": "0.8.4",
+ "resolved": "https://registry.npmjs.org/libsodium/-/libsodium-0.8.4.tgz",
+ "integrity": "sha512-lMcYaRi0zcs7tarATsQUYC7rstliIXZuoq0c6zXSgNtSNtdvBgkSegjWhpMJAXzKX3SUSwIp7+zEsob+j3LuRw==",
+ "license": "ISC"
+ },
+ "node_modules/libsodium-wrappers": {
+ "version": "0.8.4",
+ "resolved": "https://registry.npmjs.org/libsodium-wrappers/-/libsodium-wrappers-0.8.4.tgz",
+ "integrity": "sha512-mu8aAWucZjTB5O/BtGXtW4e1agy7uHxNYG7zPthmmD1jU43LCDmSWZLN4JhflbdPXj3yDO4lxM1O9hLDgIOXDw==",
+ "license": "ISC",
+ "dependencies": {
+ "libsodium": "^0.8.0"
+ }
+ },
"node_modules/locate-path": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
@@ -2355,6 +2382,23 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
+ "node_modules/native-dawn": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/native-dawn/-/native-dawn-0.1.6.tgz",
+ "integrity": "sha512-1Yl+j3A2e4Zx8brtsIumv2hoaIfeRKsxGH4EuLoGWeVHSi1JACY7SlhSdePgTc3S9eQh+kya0BiG6BHIi5RsiQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "@webgpu/types": "0.1.72",
+ "tar": "7.5.22"
+ },
+ "bin": {
+ "native-dawn": "bin/native-dawn.js"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+ },
"node_modules/native-gles": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/native-gles/-/native-gles-0.6.1.tgz",
@@ -2743,6 +2787,10 @@
"resolved": "packages/romdev-core-bluemsx",
"link": true
},
+ "node_modules/romdev-core-bsnes": {
+ "resolved": "packages/romdev-core-bsnes",
+ "link": true
+ },
"node_modules/romdev-core-fake08": {
"resolved": "packages/romdev-core-fake08",
"link": true
@@ -2803,10 +2851,18 @@
"resolved": "packages/romdev-famitone",
"link": true
},
+ "node_modules/romdev-m2c": {
+ "resolved": "packages/romdev-m2c",
+ "link": true
+ },
"node_modules/romdev-maxmod": {
"resolved": "packages/romdev-maxmod",
"link": true
},
+ "node_modules/romdev-permuter": {
+ "resolved": "packages/romdev-permuter",
+ "link": true
+ },
"node_modules/romdev-platform-atari2600": {
"resolved": "packages/romdev-platform-atari2600",
"link": true
@@ -2823,10 +2879,34 @@
"resolved": "packages/romdev-platform-sync32",
"link": true
},
+ "node_modules/romdev-pycparser": {
+ "resolved": "packages/romdev-pycparser",
+ "link": true
+ },
+ "node_modules/romdev-rabbitizer": {
+ "resolved": "packages/romdev-rabbitizer",
+ "link": true
+ },
+ "node_modules/romdev-spimdisasm": {
+ "resolved": "packages/romdev-spimdisasm",
+ "link": true
+ },
+ "node_modules/romdev-splat": {
+ "resolved": "packages/romdev-splat",
+ "link": true
+ },
"node_modules/romdev-toolchain-cc65": {
"resolved": "packages/romdev-toolchain-cc65",
"link": true
},
+ "node_modules/romdev-toolchain-decomp-gcc": {
+ "resolved": "packages/romdev-toolchain-decomp-gcc",
+ "link": true
+ },
+ "node_modules/romdev-toolchain-ido": {
+ "resolved": "packages/romdev-toolchain-ido",
+ "link": true
+ },
"node_modules/romdev-toolchain-m68k-gcc": {
"resolved": "packages/romdev-toolchain-m68k-gcc",
"link": true
@@ -2847,10 +2927,6 @@
"resolved": "packages/romdev-toolchain-sh-gcc",
"link": true
},
- "node_modules/romdev-toolchain-vasm": {
- "resolved": "packages/romdev-toolchain-vasm",
- "link": true
- },
"node_modules/romdev-xgm2": {
"resolved": "packages/romdev-xgm2",
"link": true
@@ -3520,6 +3596,7 @@
"resolved": "https://registry.npmjs.org/wasmcart/-/wasmcart-0.24.0.tgz",
"integrity": "sha512-dP5slbuNb8Du/VA66Ky3uvEbGlRRRdzgyMhMyngnVV5fX2FXC115s20Qpn9HkOmYdnY3j2/nu99qh+XzbGaNBw==",
"license": "MIT",
+ "optional": true,
"dependencies": {
"@kmamal/sdl": "^0.11.13",
"fflate": "^0.8.3",
@@ -3560,12 +3637,43 @@
}
},
"node_modules/webgl-node": {
- "version": "1.5.1",
- "resolved": "https://registry.npmjs.org/webgl-node/-/webgl-node-1.5.1.tgz",
- "integrity": "sha512-YzLpTxTvTA0vhHeEtDj6vnOdoft7uQdupBxXqHPp2YWqi9EBk/7lcUqyQi6cTM4PygtZf1Omc9tF4ON24Lr55A==",
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/webgl-node/-/webgl-node-1.6.1.tgz",
+ "integrity": "sha512-o5XP8Jb2sobB1zMpohVe0IKUt158oH0VMfPcf2D2o4NWMW6Ieq9Vixxmrb2Hnbc4t2eMl6mQnFPCZ/5k5wiMIA==",
"license": "MIT",
"dependencies": {
- "native-gles": "^0.6.0"
+ "native-gles": "^0.7.1"
+ }
+ },
+ "node_modules/webgl-node/node_modules/native-gles": {
+ "version": "0.7.1",
+ "resolved": "https://registry.npmjs.org/native-gles/-/native-gles-0.7.1.tgz",
+ "integrity": "sha512-2tYkK/pj5uT8gFWCqCwUSGI4cIBaQ/IIgyOoq7Pn4p1nokhViuXEYORpfBn16Jd2sdzG1yR05mTjFysyC6Y+1w==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "tar": "^7.4.3"
+ }
+ },
+ "node_modules/webgpu-node": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/webgpu-node/-/webgpu-node-0.2.0.tgz",
+ "integrity": "sha512-Y1hzzf7kqOWclZSlRpdSQ7VuXufgOm9YJmP9Nja/LZ6SwfsEw5digUljw08Ky9hatPPuH8C7ZPTLxSL40e/gzw==",
+ "license": "MIT",
+ "dependencies": {
+ "@webgpu/types": "0.1.72",
+ "native-dawn": "^0.1.0"
+ },
+ "engines": {
+ "node": ">=22"
+ },
+ "peerDependencies": {
+ "@kmamal/sdl": "^0.11.13"
+ },
+ "peerDependenciesMeta": {
+ "@kmamal/sdl": {
+ "optional": true
+ }
}
},
"node_modules/which": {
@@ -3737,21 +3845,21 @@
}
},
"packages/romdev_game_codes": {
- "version": "0.1.1",
+ "version": "0.1.2",
"license": "MIT",
"engines": {
"node": ">=24"
}
},
"packages/romdev-analysis": {
- "version": "0.2.1",
+ "version": "0.2.2",
"license": "LGPL-3.0-only",
"engines": {
"node": ">=24"
}
},
"packages/romdev-analysis-decompiler": {
- "version": "0.2.1",
+ "version": "0.2.2",
"license": "Apache-2.0",
"engines": {
"node": ">=24"
@@ -3765,19 +3873,26 @@
}
},
"packages/romdev-core-beetle-psx-hw": {
- "version": "0.3.1",
+ "version": "0.3.2",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-bluemsx": {
- "version": "0.9.1",
+ "version": "0.9.2",
"license": "BSD-3-Clause",
"engines": {
"node": ">=24"
}
},
+ "packages/romdev-core-bsnes": {
+ "version": "0.1.0",
+ "license": "GPL-3.0-only",
+ "engines": {
+ "node": ">=24"
+ }
+ },
"packages/romdev-core-fake08": {
"version": "0.1.1",
"license": "MIT",
@@ -3786,56 +3901,56 @@
}
},
"packages/romdev-core-fceumm": {
- "version": "0.15.0",
+ "version": "0.13.2",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-flycast": {
- "version": "0.4.1",
+ "version": "0.4.2",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-gambatte": {
- "version": "0.14.0",
+ "version": "0.12.2",
"license": "GPL-2.0-only",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-gametank": {
- "version": "0.5.1",
+ "version": "0.5.2",
"license": "MIT",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-geargrafx": {
- "version": "0.10.1",
+ "version": "0.10.2",
"license": "GPL-3.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-gpgx": {
- "version": "0.15.1",
+ "version": "0.15.2",
"license": "SEE LICENSE IN README.md",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-handy": {
- "version": "0.9.1",
+ "version": "0.9.2",
"license": "Zlib",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-host": {
- "version": "0.16.0",
+ "version": "0.14.1",
"license": "MIT",
"dependencies": {
"@monteslu/chafa-wasm": "^0.4.0",
@@ -3848,24 +3963,24 @@
}
},
"packages/romdev-core-parallel-n64": {
- "version": "0.3.1",
+ "version": "0.3.2",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-prosystem": {
- "version": "0.10.1",
+ "version": "0.10.2",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-runner": {
- "version": "0.2.18",
+ "version": "0.2.19",
"license": "MIT",
"dependencies": {
- "romdev-core-host": "0.16.0"
+ "romdev-core-host": "0.14.1"
},
"engines": {
"node": ">=24"
@@ -3875,14 +3990,14 @@
}
},
"packages/romdev-core-s32core": {
- "version": "0.2.1",
+ "version": "0.2.2",
"license": "MIT",
"engines": {
"node": ">=24"
}
},
"packages/romdev-core-vice": {
- "version": "0.12.0",
+ "version": "0.12.1",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
@@ -3895,6 +4010,20 @@
"node": ">=24"
}
},
+ "packages/romdev-m2c": {
+ "version": "0.1.0",
+ "license": "GPL-3.0-only",
+ "dependencies": {
+ "@viz-js/viz": "3.31.0",
+ "romdev-pycparser": "0.1.0"
+ },
+ "bin": {
+ "romdev-m2c": "src/cli.js"
+ },
+ "engines": {
+ "node": ">=24"
+ }
+ },
"packages/romdev-maxmod": {
"version": "0.2.1",
"license": "MIT",
@@ -3902,57 +4031,128 @@
"node": ">=24"
}
},
+ "packages/romdev-permuter": {
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "libsodium-wrappers": "0.8.4",
+ "romdev-pycparser": "0.1.0",
+ "romdev-toolchain-mips-gcc": "0.1.3"
+ },
+ "bin": {
+ "romdev-permuter": "bin/permuter.mjs",
+ "romdev-permuter-import": "bin/import.mjs",
+ "romdev-permuter-remote": "bin/remote.mjs",
+ "romdev-permuter-remote-controller": "bin/remote-controller.mjs"
+ },
+ "engines": {
+ "node": ">=24"
+ }
+ },
"packages/romdev-platform-atari2600": {
- "version": "0.10.1",
+ "version": "0.10.2",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-platform-gba": {
- "version": "0.14.0",
- "license": "MPL-2.0",
+ "version": "0.14.1",
+ "license": "SEE LICENSE IN README.md",
"engines": {
"node": ">=24"
}
},
"packages/romdev-platform-snes": {
- "version": "0.12.1",
+ "version": "0.12.2",
"license": "SEE LICENSE IN README.md",
"engines": {
"node": ">=24"
}
},
"packages/romdev-platform-sync32": {
- "version": "0.2.1",
+ "version": "0.2.2",
"license": "MIT",
"engines": {
"node": ">=24"
}
},
+ "packages/romdev-pycparser": {
+ "version": "0.1.0",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=24"
+ }
+ },
+ "packages/romdev-rabbitizer": {
+ "version": "0.1.0",
+ "license": "MIT",
+ "engines": {
+ "node": ">=24"
+ }
+ },
+ "packages/romdev-spimdisasm": {
+ "version": "0.1.0",
+ "license": "MIT AND PSF-2.0",
+ "dependencies": {
+ "romdev-rabbitizer": "0.1.0"
+ },
+ "engines": {
+ "node": ">=24"
+ }
+ },
+ "packages/romdev-splat": {
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "romdev-rabbitizer": "0.1.0",
+ "romdev-spimdisasm": "0.1.0",
+ "yaml": "2.9.0"
+ },
+ "bin": {
+ "romdev-splat": "src/cli.js"
+ },
+ "engines": {
+ "node": ">=24"
+ }
+ },
"packages/romdev-toolchain-cc65": {
- "version": "0.1.4",
+ "version": "0.1.5",
"license": "Zlib",
"engines": {
"node": ">=24"
}
},
+ "packages/romdev-toolchain-decomp-gcc": {
+ "version": "0.1.0",
+ "license": "GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-2.1-or-later AND AGPL-3.0-only AND MIT AND Zlib",
+ "engines": {
+ "node": ">=24"
+ }
+ },
+ "packages/romdev-toolchain-ido": {
+ "version": "0.1.0",
+ "license": "SEE LICENSE IN README.md",
+ "engines": {
+ "node": ">=24"
+ }
+ },
"packages/romdev-toolchain-m68k-gcc": {
- "version": "0.4.1",
+ "version": "0.4.2",
"license": "GPL-3.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-toolchain-mips-gcc": {
- "version": "0.1.2",
+ "version": "0.1.3",
"license": "GPL-3.0-or-later",
"engines": {
"node": ">=24"
}
},
"packages/romdev-toolchain-rgbds": {
- "version": "0.1.2",
+ "version": "0.1.3",
"license": "MIT",
"engines": {
"node": ">=24"
@@ -3966,30 +4166,23 @@
}
},
"packages/romdev-toolchain-sh-gcc": {
- "version": "0.1.2",
+ "version": "0.1.3",
"license": "GPL-3.0-or-later",
"engines": {
"node": ">=24"
}
},
- "packages/romdev-toolchain-vasm": {
- "version": "0.1.2",
- "license": "SEE LICENSE IN README.md",
- "engines": {
- "node": ">=24"
- }
- },
"packages/romdev-xgm2": {
- "version": "0.2.1",
+ "version": "0.2.2",
"license": "MIT",
"engines": {
"node": ">=24"
}
},
"packages/romdevtools": {
- "version": "0.149.1",
+ "version": "0.151.1",
"hasInstallScript": true,
- "license": "MIT",
+ "license": "SEE LICENSE IN NOTICE",
"dependencies": {
"@kmamal/sdl": "^0.11.13",
"@modelcontextprotocol/node": "2.0.0",
@@ -4002,44 +4195,48 @@
"native-gles": "^0.6.1",
"omggif": "^1.0.10",
"pngjs": "^7.0.0",
- "romdev_game_codes": "0.1.1",
- "romdev-analysis": "0.2.1",
- "romdev-analysis-decompiler": "0.2.1",
+ "romdev_game_codes": "0.1.2",
+ "romdev-analysis": "0.2.2",
+ "romdev-analysis-decompiler": "0.2.2",
"romdev-audio-resampler": "0.1.1",
- "romdev-core-beetle-psx-hw": "0.3.1",
- "romdev-core-bluemsx": "0.9.1",
+ "romdev-core-beetle-psx-hw": "0.3.2",
+ "romdev-core-bluemsx": "0.9.2",
+ "romdev-core-bsnes": "0.1.0",
"romdev-core-fake08": "0.1.1",
- "romdev-core-fceumm": "0.14.0",
- "romdev-core-flycast": "0.4.1",
- "romdev-core-gambatte": "0.13.1",
- "romdev-core-gametank": "0.5.1",
- "romdev-core-geargrafx": "0.10.1",
- "romdev-core-gpgx": "0.15.1",
- "romdev-core-handy": "0.9.1",
- "romdev-core-host": "0.16.0",
- "romdev-core-parallel-n64": "0.3.1",
- "romdev-core-prosystem": "0.10.1",
- "romdev-core-runner": "0.2.18",
- "romdev-core-s32core": "0.2.1",
- "romdev-core-vice": "0.12.0",
+ "romdev-core-fceumm": "0.13.2",
+ "romdev-core-flycast": "0.4.2",
+ "romdev-core-gambatte": "0.12.2",
+ "romdev-core-gametank": "0.5.2",
+ "romdev-core-geargrafx": "0.10.2",
+ "romdev-core-gpgx": "0.15.2",
+ "romdev-core-handy": "0.9.2",
+ "romdev-core-host": "0.14.1",
+ "romdev-core-parallel-n64": "0.3.2",
+ "romdev-core-prosystem": "0.10.2",
+ "romdev-core-runner": "0.2.19",
+ "romdev-core-s32core": "0.2.2",
+ "romdev-core-vice": "0.12.1",
"romdev-famitone": "0.2.1",
+ "romdev-m2c": "0.1.0",
"romdev-maxmod": "0.2.1",
- "romdev-platform-atari2600": "0.10.1",
- "romdev-platform-gba": "0.14.0",
- "romdev-platform-snes": "0.12.1",
- "romdev-platform-sync32": "0.2.1",
- "romdev-toolchain-cc65": "0.1.4",
- "romdev-toolchain-m68k-gcc": "0.4.1",
- "romdev-toolchain-mips-gcc": "0.1.2",
- "romdev-toolchain-rgbds": "0.1.2",
+ "romdev-permuter": "0.1.0",
+ "romdev-platform-atari2600": "0.10.2",
+ "romdev-platform-gba": "0.14.1",
+ "romdev-platform-snes": "0.12.2",
+ "romdev-platform-sync32": "0.2.2",
+ "romdev-splat": "0.1.0",
+ "romdev-toolchain-cc65": "0.1.5",
+ "romdev-toolchain-decomp-gcc": "0.1.0",
+ "romdev-toolchain-m68k-gcc": "0.4.2",
+ "romdev-toolchain-mips-gcc": "0.1.3",
+ "romdev-toolchain-rgbds": "0.1.3",
"romdev-toolchain-sdcc": "0.2.3",
- "romdev-toolchain-sh-gcc": "0.1.2",
- "romdev-toolchain-vasm": "0.1.2",
- "romdev-xgm2": "0.2.1",
+ "romdev-toolchain-sh-gcc": "0.1.3",
+ "romdev-xgm2": "0.2.2",
"rungame": "^0.13.0",
"socket.io": "^4.8.3",
"swagger-ui-dist": "^5.17.14",
- "wasmcart": "^0.24.0",
+ "wasmcart": "^0.36.1",
"webgl-node": "^1.5.1",
"yaml": "^2.9.0",
"yauzl": "^3.3.1",
@@ -4056,6 +4253,29 @@
"engines": {
"node": ">=24"
}
+ },
+ "packages/romdevtools/node_modules/wasmcart": {
+ "version": "0.36.1",
+ "resolved": "https://registry.npmjs.org/wasmcart/-/wasmcart-0.36.1.tgz",
+ "integrity": "sha512-bvWv5jFdwWd1Y4lQUq2OfHA9kBzFjj9b1uFwPMLADR0bAtw7q7xq+TSdsJy+Q2UI9qBVOfEa7zEfGqyENAGaeQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@kmamal/sdl": "^0.11.13",
+ "fflate": "^0.8.3",
+ "native-dawn": "^0.1.6",
+ "webgl-node": "^1.6.0",
+ "webgpu-node": "^0.2.0",
+ "yauzl": "^3.2.0",
+ "yazl": "^2.5.1"
+ },
+ "bin": {
+ "wasmcart": "bin/wasmcart.js",
+ "wasmcart-pack": "bin/wasmcart-pack.js",
+ "wasmcart-play": "bin/wasmcart-play.js"
+ },
+ "engines": {
+ "node": ">=22.0.0"
+ }
}
}
}
diff --git a/packages/romdev-analysis-decompiler/README.md b/packages/romdev-analysis-decompiler/README.md
index e4739902..cce7c8ea 100644
--- a/packages/romdev-analysis-decompiler/README.md
+++ b/packages/romdev-analysis-decompiler/README.md
@@ -1,35 +1,42 @@
# romdev-analysis-decompiler
-Ghidra's decompiler - turns machine code into C-like pseudocode - compiled to
-WebAssembly, with SLEIGH processor specifications for all 14 retro CPUs.
+Ghidra's decompiler, which turns machine code into C-like pseudocode, compiled
+to WebAssembly, with SLEIGH processor specifications for the CPUs romdev's
+platforms use.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + compiled SLEIGH `.sla` tables and is resolved by the main
-`romdev` package on demand (powers `disasm({target:'decompile'})`). You normally
-install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and compiled SLEIGH `.sla` tables, and the main
+`romdevtools` package loads it on demand for `disasm({target:'decompile'})`.
+You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
## What's bundled
-- `wasm/decompile.{js,wasm}` - Ghidra's standalone decompiler REPL, built from
- the Ghidra decompiler C++ (no JVM, no libbfd, no rizin) compiled to WASM.
-- `sleigh/*.sla` + `.ldefs`/`.pspec`/`.cspec` - compiled processor tables for
- 6502, 65C02, Z80, SM83, ARM (v4t), 68000, 65816, and HuC6280 - covering all
- 14 romdev platforms.
-
-## CPU → platform coverage
-
-6502 (NES / Atari 2600 / Atari 7800 / C64), 65C02 (Lynx), Z80 (SMS / Game Gear /
-MSX), SM83 (Game Boy / GBC), ARM7TDMI (GBA), 68000 (Genesis), 65816 (SNES),
-HuC6280 (PC Engine). Decompiler quality is excellent on ARM/68000, good on
-SM83/Z80, and rough on the 6502 family (an architecture limitation, not a bug).
-
-## Licensing & attribution
-
-Apache-2.0. This package redistributes **built artifacts only** (`.wasm`, `.sla`);
-the source for each component is fetched on demand at the commit pinned in
-romdev's `scripts/versions.json` and is never vendored here. Full per-component
-attribution - including the Ghidra/NSA base (Apache-2.0), GhidraBoy (Apache-2.0),
-ghidra-snes (MIT), and the HuC6280 spec (Apache-2.0 by derivation) - is in the
-[NOTICE](./NOTICE) file.
-
-**Built by:** `romdevtools/scripts/build-decompiler.sh` (no patch - built clean). See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+- `wasm/decompile.{js,wasm}`: Ghidra's standalone decompiler, built from the
+ Ghidra decompiler C++ (no JVM, no libbfd, no rizin) and compiled to WASM.
+- `sleigh/*.sla` with `.ldefs`/`.pspec`/`.cspec`: compiled processor tables
+ for 6502, 65C02, Z80, SM83, ARM (v4T), 68000, 65816, HuC6280, MIPS32 (both
+ endians) and SH-4.
+
+## CPU to platform coverage
+
+6502 (NES, Atari 2600, Atari 7800, C64), 65C02 (Lynx), Z80 (SMS,
+Game Gear, MSX), SM83 (Game Boy, GBC), ARM7TDMI (GBA), 68000 (Genesis), 65816
+(SNES), HuC6280 (PC Engine), MIPS (N64, PS1) and SH-4 (Dreamcast).
+Pseudocode reads best on ARM and 68000 code, well on SM83 and Z80, and roughly
+on the 6502 family, where 8-bit idioms such as carry-chained 16-bit math do not
+map cleanly to C (a property of the architecture, not a bug).
+
+## Licensing and attribution
+
+Apache-2.0. This package redistributes built artifacts only (`.wasm`, `.sla`).
+The source for each component is fetched at the commit pinned in
+`packages/romdevtools/scripts/versions.json` in the romdev repo and is not
+vendored here. Per-component attribution, including the Ghidra base
+(Apache-2.0), GhidraBoy (Apache-2.0), ghidra-snes (MIT) and the HuC6280 spec
+(Apache-2.0 by derivation), is in the [NOTICE](./NOTICE) file.
+
+**Built by:** `packages/romdevtools/scripts/build-decompiler.sh` (no patches).
+See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-analysis-decompiler/index.js b/packages/romdev-analysis-decompiler/index.js
index f35ad23e..1bf17127 100644
--- a/packages/romdev-analysis-decompiler/index.js
+++ b/packages/romdev-analysis-decompiler/index.js
@@ -1,5 +1,5 @@
// romdev-analysis-decompiler - binary package: Ghidra decompiler (WASM) +
-// SLEIGH specs for all 14 retro CPUs. Driven one-shot via the REPL through
+// SLEIGH specs for the retro CPUs romdev supports. Driven one-shot via the REPL through
// romdev's WASM worker pool. See NOTICE for attribution.
import { fileURLToPath } from "node:url";
import path from "node:path";
diff --git a/packages/romdev-analysis-decompiler/package.json b/packages/romdev-analysis-decompiler/package.json
index f5da41ef..dd990785 100644
--- a/packages/romdev-analysis-decompiler/package.json
+++ b/packages/romdev-analysis-decompiler/package.json
@@ -1,7 +1,7 @@
{
"name": "romdev-analysis-decompiler",
- "version": "0.2.1",
- "description": "Ghidra C++ decompiler (pseudocode) for romdev, compiled to WASM, with SLEIGH specs for all 14 retro CPUs.",
+ "version": "0.2.2",
+ "description": "Ghidra C++ decompiler (pseudocode) for romdev, compiled to WASM, with SLEIGH specs for the retro CPUs romdev supports.",
"type": "module",
"main": "index.js",
"exports": {
diff --git a/packages/romdev-analysis/README.md b/packages/romdev-analysis/README.md
index b7fdd924..3e7c97f1 100644
--- a/packages/romdev-analysis/README.md
+++ b/packages/romdev-analysis/README.md
@@ -1,27 +1,33 @@
# romdev-analysis
-Rizin - reverse-engineering analysis engine (control-flow graphs, cross-
-references, function detection), compiled to WebAssembly.
+Rizin, the reverse-engineering analysis engine (control-flow graphs,
+cross-references, function detection), compiled to WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand for `disasm({target:'functions'|'cfg'|'xrefs'})`. You normally install
+`romdevtools` (`npx romdevtools`), not this package directly.
-## Upstream & license
+## Upstream and license
-Bundles: **rizin** (https://github.com/rizinorg/rizin).
+Bundles: **rizin** v0.8.2 (https://github.com/rizinorg/rizin).
**License:** LGPL-3.0-only
-This package redistributes the upstream binary built to WebAssembly; the source
-and exact pinned commit are recorded in romdev's `scripts/versions.json`, and
-the build recipe is `scripts/build-rizin.sh` + `scripts/patches/rizin-*.patch`.
+This package redistributes the upstream source built to WebAssembly. The
+upstream commit is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
## CPU coverage used by romdev
-6502 (NES / Atari 2600 / Atari 7800 / C64 / Lynx), Z80 (SMS / Game Gear / MSX),
-SM83 (`gb` plugin - Game Boy / GBC), ARM (GBA), M68K (Genesis), 65816 (`snes`
-plugin), SPC700. HuC6280 (PC Engine) analysis arrives with the rz-ghidra
-decompiler package (SLEIGH spec).
-
-**Built by:** `romdevtools/scripts/build-rizin.sh` + patch(es) `rizin-romdev-emscripten.patch`, `rizin-libzip-emscripten.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+6502 (NES, Atari 2600, Atari 7800, C64, Lynx), Z80 (SMS, Game Gear, MSX), SM83
+(the `gb` plugin: Game Boy, GBC), ARM (GBA), M68K (Genesis), 65816 (the `snes`
+plugin), MIPS (N64 big-endian, PS1 little-endian) and SH-4 (Dreamcast). Rizin
+has no HuC6280 plugin, so PC Engine analysis uses the 6502 plugin: function and
+control-flow results are approximate there, while `disasm({target:'decompile'})`
+uses a proper HuC6280 SLEIGH spec from `romdev-analysis-decompiler`.
+
+**Built by:** `packages/romdevtools/scripts/build-rizin.sh` with patches
+`rizin-romdev-emscripten.patch` and `rizin-libzip-emscripten.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-analysis/package.json b/packages/romdev-analysis/package.json
index 58890635..a17620a7 100644
--- a/packages/romdev-analysis/package.json
+++ b/packages/romdev-analysis/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-analysis",
- "version": "0.2.1",
+ "version": "0.2.2",
"description": "Rizin RE analysis engine (CFG, xrefs, function detection) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-beetle-psx-hw/README.md b/packages/romdev-core-beetle-psx-hw/README.md
index 575ba524..d2d401c1 100644
--- a/packages/romdev-core-beetle-psx-hw/README.md
+++ b/packages/romdev-core-beetle-psx-hw/README.md
@@ -1,10 +1,27 @@
# romdev-core-beetle-psx-hw
-[Beetle PSX HW](https://github.com/libretro/beetle-psx-libretro) (Sony PlayStation, a
-mednafen PSX fork) compiled to WebAssembly for romdev, with the **GLES3/WebGL2 hardware
-renderer** so the PS1 GPU renders on the real GPU through native-gles - the same path as
-the glide64 N64 build and Flycast Dreamcast.
-
-Ships with **OpenBIOS embedded** (from [PCSX-Redux](https://github.com/grumpycoders/pcsx-redux),
-MIT-licensed, region-free) - there is no copyrighted Sony BIOS to ship and no BIOS file to
-supply. Built reproducibly by `romdevtools/scripts/build-beetle-psx-hw.sh`.
+[Beetle PSX HW](https://github.com/libretro/beetle-psx-libretro) (Sony
+PlayStation, a fork of mednafen's PSX emulator) compiled to WebAssembly for
+[romdev](https://github.com/monteslu/romdev), with the GLES3/WebGL2 hardware
+renderer, so the PS1 GPU renders on the real GPU through native-gles. That is
+the same path as the N64 (ParaLLEl-N64 with glide64) and Dreamcast (Flycast)
+cores.
+
+It ships with OpenBIOS embedded (from
+[PCSX-Redux](https://github.com/grumpycoders/pcsx-redux), MIT, region-free), so
+there is no Sony BIOS to ship and no BIOS file to supply.
+
+## Use
+
+A binary package: the main `romdevtools` package loads it on demand for
+`loadMedia({platform:'ps1'})`, with `hwRender: true` and the headless GL
+context `romdev-core-host` provides. You normally install `romdevtools`
+(`npx romdevtools`), not this package directly.
+
+## License
+
+GPL-2.0-or-later (Beetle PSX and mednafen). The embedded OpenBIOS is MIT.
+
+**Built by:** `packages/romdevtools/scripts/build-beetle-psx-hw.sh`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-beetle-psx-hw/package.json b/packages/romdev-core-beetle-psx-hw/package.json
index 4a0ab4c0..9ca4b5fb 100644
--- a/packages/romdev-core-beetle-psx-hw/package.json
+++ b/packages/romdev-core-beetle-psx-hw/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-beetle-psx-hw",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "Beetle PSX HW libretro core (Sony PlayStation, GLES3 hardware renderer + embedded OpenBIOS) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-bluemsx/README.md b/packages/romdev-core-bluemsx/README.md
index 23b7f300..a8b2bffd 100644
--- a/packages/romdev-core-bluemsx/README.md
+++ b/packages/romdev-core-bluemsx/README.md
@@ -3,10 +3,30 @@
The [blueMSX](https://github.com/libretro/blueMSX-libretro) MSX / MSX2 libretro
core, compiled to WebAssembly for [romdev](https://github.com/monteslu/romdev).
-Bundles **C-BIOS** (the open-source, BSD-licensed MSX BIOS) so cartridge
-homebrew boots with no proprietary ROM.
+It bundles **C-BIOS** (https://cbios.sourceforge.net), an open-source MSX BIOS,
+in `bios/Machines/`, so cartridge homebrew boots with no proprietary ROM.
+romdev's host points the core at that tree automatically.
-License: BSD-3-Clause (blueMSX core + C-BIOS). Not intended for standalone use;
-loaded by romdev's core registry.
+## Use
-**Built by:** `romdevtools/scripts/build-bluemsx.sh` + patch(es) `bluemsx-romdev-memory-regions.patch`, `bluemsx-emscripten-build.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+A binary package: the main `romdevtools` package loads it on demand for
+`loadMedia({platform:'msx'})`. You normally install `romdevtools`
+(`npx romdevtools`), not this package directly.
+
+## License
+
+- blueMSX: the blueMSX license, a permissive zlib-style license for the code
+ the blueMSX team wrote. Some upstream source files come from other projects
+ under their own terms, including GPL sound-chip code from openMSX and
+ fMSX-SDL; see `license.txt` in the upstream repository.
+- C-BIOS: BSD (2-clause). Its copyright and license text ship beside the ROMs
+ in each machine folder as `cbios.txt`, as its binary-redistribution clause
+ requires.
+
+The upstream commit is pinned in `packages/romdevtools/scripts/versions.json`
+in the romdev repo.
+
+**Built by:** `packages/romdevtools/scripts/build-bluemsx.sh` with patches
+`bluemsx-romdev-memory-regions.patch` and `bluemsx-emscripten-build.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-bluemsx/package.json b/packages/romdev-core-bluemsx/package.json
index c3ffe6d7..4aa7b663 100644
--- a/packages/romdev-core-bluemsx/package.json
+++ b/packages/romdev-core-bluemsx/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-bluemsx",
- "version": "0.9.1",
+ "version": "0.9.2",
"description": "blueMSX libretro core (MSX / MSX2) for romdev, bundled as WASM. Ships C-BIOS (open-source MSX BIOS) so no proprietary ROM is required.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-bsnes/NOTICE b/packages/romdev-core-bsnes/NOTICE
new file mode 100644
index 00000000..ca1c405a
--- /dev/null
+++ b/packages/romdev-core-bsnes/NOTICE
@@ -0,0 +1,30 @@
+romdev-core-bsnes
+=================
+
+wasm/bsnes_libretro.wasm and wasm/bsnes_libretro.js are built from bsnes
+(https://github.com/libretro/bsnes, the libretro port of bsnes by byuu / Near
+and contributors) at the commit pinned in romdevtools/scripts/versions.json
+(cores.bsnes), with romdev's patches (romdevtools/scripts/patches/
+bsnes-romdev.patch, bsnes-romdev-firmware.patch and patches/bsnes/).
+
+bsnes is licensed under the GNU General Public License, version 3
+(GPL-3.0-only; the full text is GPLv3.txt in the bsnes source). libco and nall,
+which bsnes includes, are under the ISC license. The built core is therefore
+distributed under GPL-3.0; its corresponding source is the pinned bsnes commit
+plus the romdev patch and build script named above.
+
+No bsnes code is transplanted elsewhere in romdev: this core is the only
+place bsnes runs. The firmware coprocessors that romdev's snes9x core and its
+recompiled SNES carts run (the uPD96050 for the ST010/ST011, the ARM for the
+ST018) are compiled from ares instead, which is ISC-licensed (see romdev's
+NOTICE). The only file this build shares with that code is romdev's own
+libco backend for WebAssembly (romdevtools/scripts/patches/libco-wasm/, MIT);
+the chip state layout this core writes (patches/bsnes/romdev_bsnes_chipstate.h,
+romdev's own, MIT) is matched field for field by the ares side's own header.
+
+No coprocessor firmware, chip data ROM or boot ROM is included. The SPC700
+boot ROM in this core is romdev's own clean-room reimplementation (romdevtools
+scripts/spc700-ipl/ipl.asm, MIT), not the one bsnes embeds. The DSP-1 data
+ROM, ST010 tables, Cx4 data ROM and Super Game Boy boot ROMs bsnes embeds are
+emptied before it is built (patches/bsnes/strip-firmware.mjs); the chips'
+firmware and the boot ROMs are not part of romdev, a user supplies them.
diff --git a/packages/romdev-core-bsnes/README.md b/packages/romdev-core-bsnes/README.md
new file mode 100644
index 00000000..5e0f2bf3
--- /dev/null
+++ b/packages/romdev-core-bsnes/README.md
@@ -0,0 +1,46 @@
+# romdev-core-bsnes
+
+The [bsnes](https://github.com/libretro/bsnes) SNES libretro core, compiled to
+WebAssembly for [romdev](https://github.com/monteslu/romdev).
+
+romdev's default SNES core is snes9x. bsnes is here as the accuracy reference
+for the SNES coprocessors that run firmware, which snes9x only approximates:
+the ST010/ST011 (a NEC uPD96050) and the ST018 (an ARM). bsnes runs their
+firmware; put `st011.rom` / `st018.rom` (the program ROM followed by the data
+ROM, as the chips are dumped) in the core's system directory. romdev loads it
+with `loadMedia({platform:'snes', core:'bsnes'})` or as the reference of
+`frame({op:'verifyRecompile', referenceCore:'bsnes'})`.
+
+The build differs from upstream in these ways, all in romdev's patches and
+build script:
+
+- libco gets a WebAssembly backend: bsnes runs every chip as a cothread, and
+ the cothreads switch with binaryen's Asyncify inside the module;
+- the libretro target serves memory regions with romdev's SNES region ids
+ (system_ram, video_ram, save_ram, snes_oam, snes_cgram, snes_aram,
+ snes_chipstate) and finds coprocessor firmware in the system directory;
+- the reference defaults are deterministic and accurate: no entropy, the
+ accurate PPU and DSP, no HLE preference;
+- no Nintendo boot ROM or chip data: the SPC700 boot ROM is romdev's own
+ clean-room one (MIT, `scripts/spc700-ipl/`), and the DSP-1 data ROM, the
+ ST010 tables, the Cx4 data ROM and the Super Game Boy boot ROMs upstream
+ embeds are emptied. A DSP-1, DSP-2, DSP-3, DSP-4, ST010 or ST011 cart needs
+ the chip's firmware in the system directory (e.g. `dsp1b.rom`, `st010.rom`,
+ the program ROM then the data ROM) and is refused with the file named
+ without it (DSP-2 and DSP-4 fall back to bsnes's high-level emulation); a
+ Cx4 cart runs bsnes's high-level emulation unless `cx4.data.rom` is there;
+ the Super Game Boy needs `sgb_boot.bin` / `sgb2_boot.bin`.
+
+License: GPL-3.0-only (bsnes; libco and nall are ISC). See NOTICE. Not intended for
+standalone use; loaded by romdev's core registry. This core is a separate
+reference: none of its code is compiled into romdev's snes9x core or into
+recompiled carts (their firmware coprocessors come from ares, ISC).
+
+No coprocessor firmware ships in this package: supply your own dumps, for
+example with `loadMedia({platform:'snes', core:'bsnes', firmware})`, which copies the
+file into the system directory before the ROM loads.
+
+**Built by:** `packages/romdevtools/scripts/build-bsnes.sh` with
+`bsnes-romdev.patch` and `bsnes-romdev-firmware.patch` (plus `patches/bsnes/` and `patches/libco-wasm/`). See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-bsnes/index.js b/packages/romdev-core-bsnes/index.js
new file mode 100644
index 00000000..02a017bc
--- /dev/null
+++ b/packages/romdev-core-bsnes/index.js
@@ -0,0 +1,20 @@
+// romdev-core-bsnes - binary package: the bsnes libretro core (SNES), built
+// by romdevtools/scripts/build-bsnes.sh. Not loadMedia's default SNES core
+// (that is snes9x): romdev's registry lists it in ALT_CORES as the accuracy
+// reference for the coprocessors that run firmware, which a caller names with
+// loadMedia({core:'bsnes'}) or verifyRecompile({referenceCore:'bsnes'}). The
+// ST011 / ST018 need their firmware (st011.rom / st018.rom) in the core's
+// system directory. GPL-3.0.
+import { fileURLToPath } from "node:url";
+import path from "node:path";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const WASM = path.join(__dirname, "wasm");
+
+export const platform = "snes";
+
+export const core = {
+ name: "bsnes",
+ jsPath: path.join(WASM, "bsnes_libretro.js"),
+ wasmPath: path.join(WASM, "bsnes_libretro.wasm"),
+};
diff --git a/packages/romdev-toolchain-vasm/package.json b/packages/romdev-core-bsnes/package.json
similarity index 62%
rename from packages/romdev-toolchain-vasm/package.json
rename to packages/romdev-core-bsnes/package.json
index d8a7a380..e4d90fe8 100644
--- a/packages/romdev-toolchain-vasm/package.json
+++ b/packages/romdev-core-bsnes/package.json
@@ -1,7 +1,7 @@
{
- "name": "romdev-toolchain-vasm",
- "version": "0.1.2",
- "description": "vasm m68k (Motorola syntax) assembler for romdev Genesis dev, bundled as WASM.",
+ "name": "romdev-core-bsnes",
+ "version": "0.1.0",
+ "description": "bsnes libretro core for romdev, bundled as WASM: the SNES accuracy reference for the coprocessors that run firmware (ST010/ST011, ST018).",
"type": "module",
"main": "index.js",
"exports": {
@@ -11,16 +11,17 @@
"files": [
"index.js",
"wasm",
- "README.md"
+ "README.md",
+ "NOTICE"
],
"engines": {
"node": ">=24"
},
- "license": "SEE LICENSE IN README.md",
+ "license": "GPL-3.0-only",
"repository": {
"type": "git",
"url": "git+https://github.com/monteslu/romdev.git",
- "directory": "packages/romdev-toolchain-vasm"
+ "directory": "packages/romdev-core-bsnes"
},
"homepage": "https://github.com/monteslu/romdev#readme",
"bugs": {
diff --git a/packages/romdev-core-fceumm/README.md b/packages/romdev-core-fceumm/README.md
index ccc5df36..a3e0ae8c 100644
--- a/packages/romdev-core-fceumm/README.md
+++ b/packages/romdev-core-fceumm/README.md
@@ -2,19 +2,21 @@
fceumm - NES emulator core (libretro), compiled to WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand. You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
-## Upstream & license
+## Upstream and license
-Bundles: **fceumm**.
+Bundles: **FCE Ultra mappers modified (fceumm)**, https://github.com/libretro/libretro-fceumm.
**License:** GPL-2.0-or-later
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+This package redistributes the upstream source built to WebAssembly. The
+upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
-**Built by:** `romdevtools/scripts/build-fceumm.sh` + patch(es) `fceumm-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-fceumm.sh` with patch(es) `fceumm-romdev-memory-regions.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-fceumm/package.json b/packages/romdev-core-fceumm/package.json
index f2b3f6c3..dc4b00f2 100644
--- a/packages/romdev-core-fceumm/package.json
+++ b/packages/romdev-core-fceumm/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-fceumm",
- "version": "0.15.0",
+ "version": "0.13.2",
"description": "fceumm libretro core (NES) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-flycast/README.md b/packages/romdev-core-flycast/README.md
index 327c9bc6..63247512 100644
--- a/packages/romdev-core-flycast/README.md
+++ b/packages/romdev-core-flycast/README.md
@@ -1,21 +1,35 @@
# romdev-core-flycast
-The [Flycast](https://github.com/flyinghead/flycast) libretro core (Sega Dreamcast)
-compiled to WebAssembly for romdev.
-
-A custom romdev build: single-threaded, with worker-thread creation neutered, threaded
-rendering forced off, and the **reios HLE BIOS** defaulted on - so a raw homebrew `.elf`
-boots directly with no GD-ROM image or firmware. The PowerVR2 renders through WebGL2;
-`flycast_emulate_framebuffer` scans out a direct 2D framebuffer so simple homebrew
-presents without authoring a PowerVR2 tile list.
-
-The SH-4 runs on a **WASM recompiler** (`core/rec-wasm`): each SH-4 basic block is
-emitted as a WebAssembly module at runtime and dispatched via `call_indirect`. That is
-roughly a 4-5x speedup over the interpreter this package shipped through 0.2.0, which
-put heavy commercial titles well under playable. The AICA sound system (ARM7 + DSP)
-is still interpreted - measured at under ~12% of frame time, so it is not currently
-the bottleneck.
-
-Built reproducibly by `romdevtools/scripts/build-flycast.sh` - the recompiler is the
-script's default, so a plain run reproduces this package's wasm byte-for-byte. Set
-`ROMDEV_FLYCAST_INTERP=1` to build the SH-4 interpreter instead.
+The [Flycast](https://github.com/flyinghead/flycast) libretro core (Sega
+Dreamcast) compiled to WebAssembly for [romdev](https://github.com/monteslu/romdev).
+
+A custom romdev build: single-threaded, with worker-thread creation disabled,
+threaded rendering forced off, and the reios HLE BIOS on by default, so a raw
+homebrew `.elf` boots directly with no GD-ROM image or firmware. The PowerVR2
+renders through WebGL2; `flycast_emulate_framebuffer` scans out a direct 2D
+framebuffer so simple homebrew can present without building a PowerVR2 tile
+list.
+
+The SH-4 runs on a WebAssembly recompiler (`core/rec-wasm`): each SH-4 basic
+block is emitted as a WebAssembly module at run time and dispatched through
+`call_indirect`, roughly 4 to 5 times faster than the interpreter earlier
+versions shipped. The AICA sound system (ARM7 and DSP) is still interpreted.
+
+## Use
+
+A binary package: the main `romdevtools` package loads it on demand for
+`loadMedia({platform:'dreamcast'})`, with `hwRender: true` and the headless GL
+context `romdev-core-host` provides. The core is built with NODERAWFS, so disc
+images are read from disk as needed rather than loaded into memory. You
+normally install `romdevtools` (`npx romdevtools`), not this package directly.
+
+## License
+
+GPL-2.0-or-later (Flycast).
+
+**Built by:** `packages/romdevtools/scripts/build-flycast.sh`, which adds the
+recompiler sources from `scripts/patches/flycast-wasm-jit/`. The recompiler is
+the script's default, so a plain run reproduces this package's wasm; set
+`ROMDEV_FLYCAST_INTERP=1` to build the SH-4 interpreter instead. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-flycast/package.json b/packages/romdev-core-flycast/package.json
index 589db596..e509927d 100644
--- a/packages/romdev-core-flycast/package.json
+++ b/packages/romdev-core-flycast/package.json
@@ -1,7 +1,7 @@
{
"name": "romdev-core-flycast",
- "version": "0.4.1",
- "description": "Flycast libretro core (Sega Dreamcast, reios HLE BIOS) for romdev, bundled as WASM \u2014 single-threaded build with the WASM SH-4 recompiler; boots homebrew ELFs and commercial GD-ROM images.",
+ "version": "0.4.2",
+ "description": "Flycast libretro core (Sega Dreamcast, reios HLE BIOS) for romdev, bundled as WASM: a single-threaded build with the WASM SH-4 recompiler; boots homebrew ELFs and commercial GD-ROM images.",
"type": "module",
"main": "index.js",
"exports": {
diff --git a/packages/romdev-core-gambatte/README.md b/packages/romdev-core-gambatte/README.md
index 279d419f..e0db9a34 100644
--- a/packages/romdev-core-gambatte/README.md
+++ b/packages/romdev-core-gambatte/README.md
@@ -2,19 +2,21 @@
gambatte - Game Boy / Game Boy Color emulator core (libretro), as WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand. You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
-## Upstream & license
+## Upstream and license
-Bundles: **gambatte**.
+Bundles: **gambatte**, https://github.com/libretro/gambatte-libretro.
**License:** GPL-2.0-only
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+This package redistributes the upstream source built to WebAssembly. The
+upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
-**Built by:** `romdevtools/scripts/build-gambatte.sh` + patch(es) `gambatte-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-gambatte.sh` with patch(es) `gambatte-romdev-memory-regions.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-gambatte/package.json b/packages/romdev-core-gambatte/package.json
index fb679e5d..82b85fa2 100644
--- a/packages/romdev-core-gambatte/package.json
+++ b/packages/romdev-core-gambatte/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-gambatte",
- "version": "0.15.0",
+ "version": "0.12.2",
"description": "gambatte libretro core (Game Boy / Game Boy Color) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-gametank/README.md b/packages/romdev-core-gametank/README.md
index 7c501242..26154d40 100644
--- a/packages/romdev-core-gametank/README.md
+++ b/packages/romdev-core-gametank/README.md
@@ -1,20 +1,33 @@
# romdev-core-gametank
-gametank - GameTank (Clyde Shaffer's open W65C02S console) emulator core (libretro), as WebAssembly.
+The GameTank libretro core (GameTank: Clyde Shaffer's open-source 8-bit
+console, a WDC 65C02 main CPU with a second 65C02 driving audio), compiled to
+WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand for `loadMedia({platform:'gametank'})`. You normally install
+`romdevtools` (`npx romdevtools`), not this package directly.
-## Upstream & license
+## Upstream and license
-Bundles: **handy**.
+Bundles: **gametank-libretro** (https://github.com/monteslu/gametank-libretro),
+a libretro wrapper around the hardware-emulation units of Clyde Shaffer's
+[GameTankEmulator](https://github.com/clydeshaffer/GameTankEmulator) (CPU,
+blitter, audio coprocessor, bus).
-**License:** Zlib
+**License:** MIT (gametank-libretro and GameTankEmulator, Copyright (c) 2020
+Clyde Shaffer; the vendored mos6502 CPU core is MIT, Copyright (c) 2017
+Gianluca Ghettini).
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+romdev's build adds its shared live-debug instrumentation (write and read
+watchpoints, PC breakpoints, register get/set, coverage) through a small shim
+appended to the core's `libretro.cpp`. This core is built from a local checkout
+of gametank-libretro; it has no pinned commit in
+`packages/romdevtools/scripts/versions.json`.
-**Built by:** `romdevtools/scripts/build-handy.sh` + patch(es) `handy-romdev-watchpoint.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-gametank.sh` (shim:
+`scripts/patches/romdev-snippets/gametank-debug.cpp`). Set `GAMETANK_SRC` to
+the gametank-libretro checkout. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-gametank/package.json b/packages/romdev-core-gametank/package.json
index f9151b9b..93a2aed1 100644
--- a/packages/romdev-core-gametank/package.json
+++ b/packages/romdev-core-gametank/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-gametank",
- "version": "0.5.1",
+ "version": "0.5.2",
"description": "GameTank libretro core (Clyde Shaffer's open W65C02S console) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-geargrafx/README.md b/packages/romdev-core-geargrafx/README.md
index ae6bc519..3f4fb078 100644
--- a/packages/romdev-core-geargrafx/README.md
+++ b/packages/romdev-core-geargrafx/README.md
@@ -1,10 +1,21 @@
# romdev-core-geargrafx
-The [Geargrafx](https://github.com/drhelius/Geargrafx) PC Engine / TurboGrafx-16
-libretro core, compiled to WebAssembly for
+The [Geargrafx](https://github.com/drhelius/Geargrafx) PC Engine /
+TurboGrafx-16 libretro core, compiled to WebAssembly for
[romdev](https://github.com/monteslu/romdev).
-License: GPL-3.0-or-later. Not intended for standalone use; loaded by romdev's
-core registry.
+## Use
-**Built by:** `romdevtools/scripts/build-geargrafx.sh` + patch(es) `geargrafx-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+A binary package: the main `romdevtools` package loads it on demand for
+`loadMedia({platform:'pce'})`. You normally install `romdevtools`
+(`npx romdevtools`), not this package directly.
+
+## License
+
+GPL-3.0-or-later (Geargrafx). The upstream commit is pinned in
+`packages/romdevtools/scripts/versions.json` in the romdev repo.
+
+**Built by:** `packages/romdevtools/scripts/build-geargrafx.sh` with patch
+`geargrafx-romdev-memory-regions.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-geargrafx/package.json b/packages/romdev-core-geargrafx/package.json
index bf48961c..9ed2e80b 100644
--- a/packages/romdev-core-geargrafx/package.json
+++ b/packages/romdev-core-geargrafx/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-geargrafx",
- "version": "0.10.1",
+ "version": "0.10.2",
"description": "Geargrafx libretro core (PC Engine / TurboGrafx-16) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-gpgx/README.md b/packages/romdev-core-gpgx/README.md
index bf51ed95..99a20e00 100644
--- a/packages/romdev-core-gpgx/README.md
+++ b/packages/romdev-core-gpgx/README.md
@@ -2,19 +2,21 @@
Genesis Plus GX - Sega Genesis / Master System / Game Gear emulator core (libretro), as WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand. You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
-## Upstream & license
+## Upstream and license
-Bundles: **Genesis Plus GX**.
+Bundles: **Genesis Plus GX**, https://github.com/libretro/genesis-plus-gx.
-**License:** NON-COMMERCIAL (Genesis Plus GX custom license) - free for non-commercial use; redistribution for profit is not permitted.
+**License:** Genesis Plus GX license (non-commercial): free for non-commercial use; redistribution for profit is not permitted. See the upstream `LICENSE.txt`.
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+This package redistributes the upstream source built to WebAssembly. The
+upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
-**Built by:** `romdevtools/scripts/build-genesis-plus-gx.sh` + patch(es) `genesis-plus-gx-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-genesis-plus-gx.sh` with patch(es) `genesis-plus-gx-romdev-memory-regions.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-gpgx/package.json b/packages/romdev-core-gpgx/package.json
index 2527b3c1..f2a0d102 100644
--- a/packages/romdev-core-gpgx/package.json
+++ b/packages/romdev-core-gpgx/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-gpgx",
- "version": "0.15.1",
+ "version": "0.15.2",
"description": "Genesis Plus GX libretro core (Genesis / Master System / Game Gear) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-handy/README.md b/packages/romdev-core-handy/README.md
index 102d1c8c..af97af7c 100644
--- a/packages/romdev-core-handy/README.md
+++ b/packages/romdev-core-handy/README.md
@@ -2,19 +2,21 @@
handy - Atari Lynx emulator core (libretro), as WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand. You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
-## Upstream & license
+## Upstream and license
-Bundles: **handy**.
+Bundles: **Handy**, https://github.com/libretro/libretro-handy.
**License:** Zlib
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+This package redistributes the upstream source built to WebAssembly. The
+upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
-**Built by:** `romdevtools/scripts/build-handy.sh` + patch(es) `handy-romdev-watchpoint.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-handy.sh` with patch(es) `handy-romdev-watchpoint.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-handy/package.json b/packages/romdev-core-handy/package.json
index 9308d50d..a045b6bf 100644
--- a/packages/romdev-core-handy/package.json
+++ b/packages/romdev-core-handy/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-handy",
- "version": "0.9.1",
+ "version": "0.9.2",
"description": "Handy libretro core (Atari Lynx) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-host/LibretroGL.js b/packages/romdev-core-host/LibretroGL.js
index 3bf741b8..eb964f27 100644
--- a/packages/romdev-core-host/LibretroGL.js
+++ b/packages/romdev-core-host/LibretroGL.js
@@ -59,9 +59,9 @@ export class LibretroGL {
}
/**
- * Load the optional native GL module (lazy). MUST be awaited before the core
- * boots, since the 14 software cores never call this and the module is an
- * optional dependency. Populates the module-level `gl` used by
+ * Load the native GL module (lazy). MUST be awaited before the core
+ * boots. Software-rendered cores never call this, so the module loads only
+ * for HW-render cores. Populates the module-level `gl` used by
* createContext/readbackFrame/destroy.
* @returns {Promise}
*/
diff --git a/packages/romdev-core-host/LibretroHost.js b/packages/romdev-core-host/LibretroHost.js
index c7d79605..964102cf 100644
--- a/packages/romdev-core-host/LibretroHost.js
+++ b/packages/romdev-core-host/LibretroHost.js
@@ -285,7 +285,18 @@ export class LibretroHost {
systemDir: opts.systemDir ?? "/romdev-system",
saveDir: opts.saveDir ?? "/romdev-save",
});
- this.log = opts.log;
+ // The core's error-level log lines (RETRO_LOG_ERROR) are also kept, so a
+ // load the core refuses can say why in the core's own words (a missing
+ // firmware file, named by the core).
+ const userLog = opts.log;
+ this._coreErrors = [];
+ this.log = (level, msg) => {
+ if (level >= 3 && typeof msg === "string" && msg.trim()) {
+ this._coreErrors.push(msg.trim());
+ if (this._coreErrors.length > 8) this._coreErrors.shift();
+ }
+ if (userLog) userLog(level, msg);
+ };
this.status = {
platform: null,
corePath: null,
@@ -307,7 +318,7 @@ export class LibretroHost {
* @param {string} [wasmPath]
* @param {Object} [opts]
* @param {boolean} [opts.hwRender] this core HW-renders (GL) - n64/ps1. Loads the
- * optional native GL stack and creates a headless context BEFORE the core boots
+ * native GL stack and creates a headless context BEFORE the core boots
* (GL calls happen during init/load). The 14 software cores omit this.
*/
/** Infer the platform from a core's js filename stem (e.g.
@@ -748,6 +759,7 @@ export class LibretroHost {
// flag while YIELDING to the JS event loop - the event loop must keep turning so emscripten
// can service the app-thread's pooled-Worker grabs / postMessage wakeups. A blocking call
// would freeze the event loop → the core's threads can't be scheduled → deadlock.
+ this._coreErrors.length = 0;
let ok;
if (this._proxied) {
// Deferred retro_init (see loadCore): now that the system dir is mirrored into the app-thread
@@ -773,7 +785,7 @@ export class LibretroHost {
mod._romdev_proxied_fire_context_reset(this.state.proxiedContextResetPtr);
}
} else {
- ok = mod._retro_load_game(infoPtr);
+ ok = this._withClock(() => mod._retro_load_game(infoPtr));
}
// Free the struct itself. Don't free pathPtr or dataPtr - the core may
@@ -789,6 +801,10 @@ export class LibretroHost {
`The '${platform}' core REFUSED this ${mediaKind || "media"} ` +
`(${data ? data.length + " bytes" : "streamed from disk"}${ext ? `, ${ext}` : ""}, path ${mediaPath}). ` +
`retro_load_game returned false - the bytes reached the core but it would not accept them. ` +
+ // the core's own reason, when it logged one (e.g. a firmware file it needs, by name)
+ (this._coreErrors.some((m) => m.startsWith("romdev:"))
+ ? `The core said: ${this._coreErrors.filter((m) => m.startsWith("romdev:")).join(" ")} `
+ : "") +
`Common causes: (1) wrong platform for this file (a GB ROM loaded as 'nes', etc.) - ` +
`confirm the platform matches the file; (2) a corrupt or TRUNCATED image - re-check the byte length; ` +
`(3) an unsupported mapper/board or a missing/!bad header. ` +
@@ -908,9 +924,9 @@ export class LibretroHost {
// - snes9x defaults to 256×224 but games select 256×239 or
// 512×448 (interlaced) based on PPU regs the ROM sets up.
//
- // The rom-games agent reasonably expected fbWidth/Height after
- // loadMedia to reflect "what screenshot will show me". Step a
- // small number of frames here so the agent sees the ROM-chosen
+ // Callers expect fbWidth/Height after loadMedia to reflect "what
+ // screenshot will show me". Step a small number of frames here so
+ // the caller sees the ROM-chosen
// geometry, not the pre-init default.
//
// 8 frames is generous - Genesis games typically settle their
@@ -920,6 +936,9 @@ export class LibretroHost {
// Proxied cores (PSP) drive frames through the async run path (run_start + poll); the
// synchronous settle loop below uses the blocking sync run, so skip it. PSP geometry is the
// fixed 480×272 av_info already read, so there's no pre-init default to settle past.
+ // A caller that must observe the settle frames themselves (the
+ // instruction differ traces power-on) arms its hooks here.
+ if (typeof args.beforeSettle === "function") args.beforeSettle(this);
if (!args.deterministic && !this.status.paused && !this._proxied) {
// Settle frames are core warm-up, not agent-visible gameplay
// frames - don't increment frameCount. From the agent's POV the
@@ -982,10 +1001,8 @@ export class LibretroHost {
*
* This is what makes host eviction actually reclaim anything. Without it a
* long-lived server accumulates one full core heap per host it has ever
- * created - which is how the server got OOM-killed twice on 2026-08-19
- * (~5.4 GB RSS, 300-500 GB of mapped address space) under a single agent
- * running a 21-gate suite that loads 20+ carts. See
- * internal-romdev/PLAN_mcp_v2_stateless_and_host_lifetime.md.
+ * created, which reached about 5.4 GB RSS (300-500 GB of mapped address
+ * space) under one client running a test suite that loads 20+ carts.
*
* Ordering matters: unload the game, then `retro_deinit` so the core frees
* its own allocations while its heap is still valid, then drop every
@@ -1069,7 +1086,44 @@ export class LibretroHost {
* observes (frameCount is incremented after the frame runs).
* A hook failure never breaks emulation: it is caught and remembered on
* `beforeFrameError`; the callback owner surfaces it. */
+ /**
+ * Pin the wall clock the core reads (Date.now, which emscripten's time()
+ * and clock_gettime call: gambatte's MBC3 RTC, mGBA's GPIO RTC) to a
+ * frame clock, so a verifier can give a recompiled cart the same one:
+ * baseMs + max(0, runs - startRun) * stepMs
+ * where runs counts retro_run calls since the pin was set (0 while the
+ * game loads), in UTC (localtime = gmtime while the core runs). baseMs
+ * should be a whole second. null restores the host
+ * clock. Set it before loadMedia so the load (gambatte's RTC base time)
+ * sees it too.
+ * @param {{baseMs: number, stepMs: number, startRun?: number|(() => number)}|null} pin
+ */
+ setPinnedClock(pin) {
+ this._clockPin = pin ? { baseMs: pin.baseMs, stepMs: pin.stepMs, startRun: pin.startRun ?? 0, runs: 0 } : null;
+ }
+
+ /** @param {() => any} fn run with Date.now pinned (see setPinnedClock) */
+ _withClock(fn) {
+ const pin = this._clockPin;
+ if (!pin) return fn();
+ const start = typeof pin.startRun === "function" ? pin.startRun() : pin.startRun;
+ const t = pin.baseMs + Math.max(0, pin.runs - start) * pin.stepMs;
+ const real = Date.now;
+ Date.now = () => t;
+ // localtime() is emscripten's JS Date getters in the host's zone; a
+ // pinned clock is UTC so the calendar a core computes (mGBA's RTC date
+ // and hour) does not depend on the machine running the verification
+ const env = globalThis.process?.env;
+ const tz = env?.TZ;
+ if (env) env.TZ = "UTC";
+ try { return fn(); } finally {
+ Date.now = real;
+ if (env) { if (tz === undefined) delete env.TZ; else env.TZ = tz; }
+ }
+ }
+
_runCore() {
+ if (this._clockPin) this._clockPin.runs++;
if (this.state.inputOverrides) this.state.inputOverrides.fill(null);
if (this.beforeFrame) {
try {
@@ -1078,8 +1132,10 @@ export class LibretroHost {
this.beforeFrameError = e;
}
}
- if (this._proxied) this.mod._romdev_proxied_run();
- else this.mod._retro_run();
+ this._withClock(() => {
+ if (this._proxied) this.mod._romdev_proxied_run();
+ else this.mod._retro_run();
+ });
}
/**
@@ -1983,7 +2039,7 @@ export class LibretroHost {
if (typeof mod._retro_cheat_set !== "function") {
throw new Error(
"this core build does not expose the cheat interface (retro_cheat_set). " +
- "Rebuild the core with the cheat exports, or apply RAM cheats via writeMemory.",
+ "Rebuild the core with the cheat exports, or apply RAM cheats via memory({op:'write'}).",
);
}
const bytes = encodeCString(String(code));
@@ -2038,7 +2094,7 @@ export class LibretroHost {
*
* The other mirror platforms (NES/GB/GBC/SMS/GG/Genesis) get the SAME
* arm-side canonicalization so arming a mirror-form address matches the
- * canonical-form writer (the common agent mistake). ⚠ Their core hooks
+ * canonical-form writer (the common agent mistake). Their core hooks
* compare RAW bus addresses (only snes9x canonicalizes live accesses), so
* a WRITER that itself uses a mirror form still evades on those platforms
* - fixing that direction needs per-core hook patches (deferred; noted in
@@ -2716,8 +2772,8 @@ export class LibretroHost {
// interrupt raising). Without it, each "frame" of the call runs the
// game's OWN per-frame logic concurrently (VBlank handlers via RAM
// vectors etc.), which can stomp the buffer the driven routine is
- // writing - a real session diffed a CORRECT codec reimplementation
- // against that poisoned output for hours. gpgx (Genesis/SMS/GG) only.
+ // writing, so a CORRECT codec reimplementation can look wrong when
+ // diffed against that output. gpgx (Genesis/SMS/GG) only.
pure = false,
// presetMemory: [{addr, bytes}] CPU-space writes applied before the call
// (codecs that read a global from RAM - a dest stride, a mode flag, etc).
@@ -2787,7 +2843,7 @@ export class LibretroHost {
}
// Set caller-supplied registers.
// regs accepts NAMES ('a','x','y','p','sp',..., per the platform's regNames
- // map) OR raw numeric ids - field report: no 65816 reg-id table meant a
+ // map) OR raw numeric ids; without a 65816 reg-id table a
// caller couldn't preset A without guessing. A name with no mapping, or a
// non-numeric key on a platform without regNames, throws clearly.
for (const [key, val] of Object.entries(regs)) {
@@ -2920,7 +2976,7 @@ export class LibretroHost {
// Use the platform's REAL register file (getCPUState decodes per-core: A/X/Y/
// P/DB/DP on 65816, D0-D7/A0-A7 on m68k, ...). The old _readCallRegs hardcoded
// m68k names {D0,D1,A0,A1,PC,SP}, so on a 65816 core the values came back
- // under WRONG labels - a caller couldn't read A/X/Y/P (field report). Fall
+ // under WRONG labels - a caller couldn't read A/X/Y/P. Fall
// back to the raw m68k-id read only if the per-core decode is unavailable.
try {
const st = getCPUState(this, this._loadArgs?.platform);
@@ -3047,8 +3103,8 @@ export class LibretroHost {
case "snes":
// 65816: A=0,X=1,Y=2,P=3,S=4,DB=5,D=6,PC=16. retBytes DEFAULTS to 3 for a
// JSL/RTL callee; a JSR/RTS callee pushes only 2 (PCL,PCH) - pass
- // callMode:'jsr' to size the sentinel/return-pop to 2 (field report: a
- // plain jsr helper "returned" 1 byte off into vector-stub land). The
+ // callMode:'jsr' to size the sentinel/return-pop to 2 (otherwise a
+ // plain jsr helper "returns" 1 byte off into vector-stub land). The
// 65816 stack is in bank 0; WRAM low mirror. ~3.58MHz / ~6 cyc / 60 ≈ 10k.
return { spReg: 4, pcReg: 16, retBytes: 3, retBigEndian: false, defaultSentinel: 0, ramMask: 0x1FFF, retAdjust: -1, instrPerFrame: 12000,
regNames: { a: 0, x: 1, y: 2, p: 3, s: 4, sp: 4, db: 5, d: 6, dp: 6, pc: 16 },
@@ -3187,6 +3243,106 @@ export class LibretroHost {
}
}
+ // ── instruction trace (free-running, exact) ────────────────────────────────
+ // Every EXECUTED instruction's pc (and the core's clock at dispatch) in
+ // order, recorded by the core while it runs normally. stepInstruction is not
+ // a substitute: it freezes the CPU while the rest of the machine finishes the
+ // frame, so consecutive stepped instructions are a frame apart in machine
+ // time and every interrupt/poll lands somewhere else.
+
+ /** True when this core build records the instruction trace (romdev_trace_*). */
+ traceSupported() {
+ const mod = this.mod;
+ return !!(mod && typeof mod._romdev_trace_set === "function" && typeof mod._romdev_trace_info === "function");
+ }
+
+ /**
+ * Which dispatching CPUs the trace records for the loaded platform: bit 0 =
+ * the main CPU. genesis_plus_gx dispatches its Z80 as cpu 1, which is the
+ * MAIN CPU on SMS / Game Gear.
+ */
+ traceCpuMask() {
+ const p = this.status.platform;
+ return p === "sms" || p === "gg" || p === "sg1000" ? 2 : 1;
+ }
+
+ /**
+ * Arm (restart) or disarm the trace. The count restarts at 0.
+ * `registers:true` adds the core's per-instruction register columns
+ * (traceRegisterNames()) where the core provides them.
+ * @param {{capacity?:number, enabled?:boolean, cpuMask?:number, registers?:boolean}} [o]
+ * @returns {number} the ring capacity allocated (entries)
+ */
+ setTrace({ capacity = 1 << 20, enabled = true, cpuMask, registers = false } = {}) {
+ const mod = this._needMod();
+ if (!this.traceSupported()) throw new Error("this core build does not record an instruction trace (rebuild with romdev_trace_* exports).");
+ if (typeof mod._romdev_trace_regs === "function") mod._romdev_trace_regs(registers ? 1 : 0);
+ return mod._romdev_trace_set(capacity >>> 0, enabled ? 1 : 0, (cpuMask ?? this.traceCpuMask()) >>> 0) >>> 0;
+ }
+
+ /** Names of the register columns this core records with setTrace({registers:true}). */
+ traceRegisterNames() {
+ const p = this.status.platform;
+ if (p === "gba") return [...Array.from({ length: 16 }, (_, i) => `r${i}`), "cpsr"];
+ // gambatte: af (A << 8 | F) is the fifth column; an older build records
+ // four and readTrace keeps only the columns the core wrote
+ if (p === "gb" || p === "gbc") return ["sp", "hl", "bc", "de", "af"];
+ if (p === "nes") return ["a", "x", "y", "s", "p"];
+ // genesis_plus_gx: one filler for both CPUs (17 columns); the 68000's
+ // d0-d7, a0-a7 (a7 = the active stack pointer), sr, or on SMS / Game Gear
+ // the Z80's (r as LD A,R reads it; af2.. = the alternate set; the rest 0).
+ if (p === "genesis" || p === "md") return [...Array.from({ length: 8 }, (_, i) => `d${i}`), ...Array.from({ length: 8 }, (_, i) => `a${i}`), "sr"];
+ if (p === "sms" || p === "gg") return ["af", "bc", "de", "hl", "ix", "iy", "sp", "r", "af2", "bc2", "de2", "hl2", "i"];
+ // snes9x: p = the status byte as PHP pushes it, emulation flag at bit 8.
+ if (p === "snes") return ["a", "x", "y", "s", "d", "db", "p"];
+ return [];
+ }
+
+ /** @returns {{enabled:boolean, capacity:number, count:number, ptr:number, cpuMask:number, words:number, regs:number}} */
+ traceInfo() {
+ const mod = this._needMod();
+ if (!this.traceSupported()) throw new Error("this core build does not record an instruction trace.");
+ const p = mod._malloc(28);
+ try {
+ new Uint32Array(mod.HEAPU8.buffer, p, 7).fill(0);
+ mod._romdev_trace_info(p);
+ const u = new Uint32Array(mod.HEAPU8.buffer, p, 7);
+ return { enabled: !!u[0], capacity: u[1], count: u[2], ptr: u[3], cpuMask: u[4], words: u[5] || 2, regs: u[6] };
+ } finally { mod._free(p); }
+ }
+
+ /**
+ * Read recorded entries [from, to) (indices since setTrace). Entries older
+ * than count - capacity were overwritten; `from` is raised to the oldest
+ * surviving one and `lost` says how many were asked for but gone.
+ * @param {number} [from=0]
+ * @param {number} [to] default: everything recorded so far
+ * `regs` (when the trace was armed with registers) maps each
+ * traceRegisterNames() column to a Uint32Array parallel to `pc`.
+ * @returns {{from:number, to:number, lost:number, pc:Uint32Array, clock:Uint32Array, regs:Record|null}}
+ */
+ readTrace(from = 0, to) {
+ const info = this.traceInfo();
+ const end = Math.min(to ?? info.count, info.count);
+ const oldest = Math.max(0, info.count - info.capacity);
+ const start = Math.max(from, oldest);
+ const n = Math.max(0, end - start);
+ const W = info.words;
+ const pc = new Uint32Array(n), clock = new Uint32Array(n);
+ const names = W > 2 ? this.traceRegisterNames().slice(0, W - 2) : [];
+ const cols = names.map(() => new Uint32Array(n));
+ if (n && info.ptr) {
+ const ring = new Uint32Array(this.mod.HEAPU8.buffer, info.ptr, info.capacity * W);
+ for (let k = 0; k < n; k++) {
+ const i = ((start + k) % info.capacity) * W;
+ pc[k] = ring[i]; clock[k] = ring[i + 1];
+ for (let c = 0; c < cols.length; c++) cols[c][k] = ring[i + 2 + c];
+ }
+ }
+ const regs = names.length ? Object.fromEntries(names.map((nm, c) => [nm, cols[c]])) : null;
+ return { from: start, to: start + n, lost: Math.max(0, Math.min(start, end) - from), pc, clock, regs };
+ }
+
logPCRange(lo, hi, frames) {
const mod = this._needMod();
this._needMedia();
@@ -3363,7 +3519,7 @@ export class LibretroHost {
_emptyRegionError(region) {
const plat = this.status && this.status.platform;
- // SRAM gets an honest, specific answer: empty save_ram almost always means
+ // SRAM gets a specific answer: empty save_ram almost always means
// "this cart/system has no battery save," NOT "the core is broken."
if (region === "save_ram") {
if (["atari2600", "atari7800", "lynx"].includes(plat)) {
@@ -3397,13 +3553,13 @@ export class LibretroHost {
sms: { video_ram: "sms_vram (or sms_cram for palette, sms_vdp_regs for VDP regs)" },
gg: { video_ram: "gg_vram (or gg_cram for the 64-byte 12-bit palette, sms_vdp_regs for VDP regs)" },
snes: { video_ram: "snes_oam (sprite OAM), snes_cgram (palette), snes_aram (SPC700), or snes_fillram (PPU/DMA reg shadow). The libretro generic 'video_ram' id isn't wired in snes9x." },
- genesis: { video_ram: "Genesis VRAM IS exposed via 'video_ram' (gpgx) once a ROM is loaded and a frame has run - if it reads empty, step a frame first (the SAT/sprites need the game to have written VRAM). Palette/scroll/VDP regs are genesis_cram / genesis_vsram / genesis_vdp_regs. For decoded views use inspectSprites / inspectPatternTiles / inspectBackgroundMap / getRenderingContext." },
+ genesis: { video_ram: "Genesis VRAM IS exposed via 'video_ram' (gpgx) once a ROM is loaded and a frame has run - if it reads empty, step a frame first (the SAT/sprites need the game to have written VRAM). Palette/scroll/VDP regs are genesis_cram / genesis_vsram / genesis_vdp_regs. For decoded views use sprites({op:'inspect'}) / tiles({op:'png'}) / background({view:'map'}) / background({view:'renderState'})." },
c64: { video_ram: "c64_color_ram (1 KB) / c64_vic_regs / c64_sid_regs / c64_cia1_regs / c64_cia2_regs. The C64 has no separate VRAM - the VIC-II reads from main system_ram." },
};
const hint = suggestions[plat] && suggestions[plat][region];
if (hint) {
return `memory region '${region}' is empty on platform '${plat}'. Try: ${hint}. ` +
- `Or use inspectPatternTiles / inspectBackgroundMap / inspectSprites / inspectPalette which abstract over per-platform memory layout.`;
+ `Or use tiles({op:'png'}) / background({view:'map'}) / sprites({op:'inspect'}) / palette({source:'live'}), which abstract over per-platform memory layout.`;
}
return `memory region '${region}' is empty (core didn't expose it on platform '${plat || "?"}'). ` +
`If you need raw bytes, see the platform-specific regions in src/host/types.js or the inspect* tools which know the right region per platform.`;
diff --git a/packages/romdev-core-host/README.md b/packages/romdev-core-host/README.md
index 404fa42d..39e00b08 100644
--- a/packages/romdev-core-host/README.md
+++ b/packages/romdev-core-host/README.md
@@ -3,14 +3,14 @@
The [romdev](https://github.com/monteslu/romdev) libretro host runtime,
published standalone: load a `romdev-core-*` emulator core (WASM), run
frames, read the framebuffer / audio / memory, drive input, save and load
-state. This is the SAME host the romdev MCP server runs (the server consumes
-this package too), so there is exactly one host implementation in the
-ecosystem. Bundles NO cores; pass any `romdev-core-*` package.
+state. This is the same host the romdevtools MCP server runs (the server
+consumes this package too), so there is one host implementation. It bundles no
+cores; pass any `romdev-core-*` package.
-**Isomorphic**: the core surface has no top-level `node:` imports and no
-pngjs. Under Node you load cores and ROMs by path; in a browser or worker
-bundle you pass the Emscripten factory + wasm bytes and ROM bytes, and the
-same host runs unchanged (see "Browser / bytes-only use" below).
+The same code runs in Node and in a browser: the core surface has no top-level
+`node:` imports and no pngjs. Under Node you load cores and ROMs by path; in a
+browser or worker bundle you pass the Emscripten factory, the wasm bytes and the
+ROM bytes, and the same host runs unchanged (see "Browser / bytes-only use" below).
```js
import { LibretroHost } from "romdev-core-host";
@@ -83,8 +83,9 @@ write watchpoints, read watches, PC breakpoints, `runUntilPC(addr)` /
(`exportDiskImage`, `importDiskImage`, `putDiskFile`). MSX: the bundled
open C-BIOS system dir resolves automatically. The 3D cores (N64, PS1,
Dreamcast) hardware-render through a headless GL context: pass
-`{ hwRender: true }` to `loadCore` and install the optional `native-gles`
-dependency; the software-rendered cores need neither. native-gles 0.6.0+
+`{ hwRender: true }` to `loadCore`. `native-gles` and `webgl-node` are regular
+dependencies of this package and load lazily, only when a hardware-rendered
+core boots; the software-rendered cores never touch GL. native-gles 0.6.0+
is multi-context: each core owns the context it renders into (created for
it via webgl-node) and re-asserts it before every frame, so several GL
consumers - more cores, an active-bezel compositor, a wasmcart cart - can
@@ -152,21 +153,47 @@ For the full agent tooling surface (MCP server, build toolchains,
disassembly, playtest) see
[`romdevtools`](https://www.npmjs.com/package/romdevtools).
-## 0.13.1 - exact PC coverage bitmap
-
-`pcBitmapSupported()` / `logPCBitmap(lo, hi, frames, {shift})`: on a core
-built with the 0.13.0 shared debug lib (`romdev_covbits_set/get`), run
-`frames` frames recording EVERY executed PC in `[lo, hi)` as one bit per PC -
-O(1) per instruction, no distinct-PC cap - and return `{pcs, distinct, total,
-words, shift, granularityBytes, exact}`. The bit granularity is `1 << shift`
-bytes and defaults to `pcAlignShift()` for the loaded platform: 2 (word) on
-MIPS (n64, ps1, psp), 1 (halfword) on the 68000 / Thumb / SH-4 machines
-(genesis, gba, dreamcast, sync32), 0 (byte) on every byte-addressed CPU (6502,
-Z80, SM83, 65816, HuC6280, W65C02) and when the platform is unknown. The core
-reports the shift it recorded at; `exact` is false only when a caller asked for
-a granularity coarser than the CPU's instruction alignment. `logPCRange` is
-the older 8192-entry distinct ring (`romdev_cov_set/get`), still exported by
-every core. Every romdev core carries the bitmap.
+## Coverage, instruction trace and clock
+
+These are feature-detected like the rest of the debug tier.
+
+**PC coverage.** `pcBitmapSupported()` / `logPCBitmap(lo, hi, frames, {shift})`
+runs `frames` frames and records every executed PC in `[lo, hi)` as one bit,
+with no cap on distinct PCs, returning `{pcs, distinct, total, words, shift,
+granularityBytes, exact}`. The granularity defaults to `pcAlignShift()` for the
+loaded platform: word on MIPS (n64, ps1), halfword on the 68000, Thumb and SH-4
+machines (genesis, gba, dreamcast, sync32), byte on the 8-bit CPUs.
+`logPCRange(lo, hi, frames)` is the older 8192-entry distinct-PC log.
+
+**Instruction trace.** Every executed instruction's PC, and the core's clock at
+dispatch, in order, recorded while the core runs normally (unlike
+`stepInstruction()`, which freezes the CPU while the rest of the machine
+finishes the frame).
+
+- `traceSupported()`: whether the loaded core build records a trace.
+- `traceCpuMask()`: which dispatching CPUs to record for the platform (bit 0 is
+ the main CPU; on SMS and Game Gear the Z80 is cpu 1 in genesis_plus_gx).
+- `setTrace({capacity, enabled, cpuMask, registers})`: arm, restart or disarm
+ the ring; returns the capacity allocated. `registers: true` adds
+ per-instruction register columns where the core provides them.
+- `traceRegisterNames()`: those columns for the platform (NES, GB/GBC, GBA,
+ Genesis, SMS/GG, SNES).
+- `traceInfo()`: `{enabled, capacity, count, cpuMask, ...}`.
+- `readTrace(from, to)`: `{from, to, lost, pc, clock, regs}` as typed arrays;
+ entries already overwritten in the ring are counted in `lost`.
+
+**Pinned clock.** `setPinnedClock({baseMs, stepMs, startRun})` pins the wall
+clock a core reads (for example a cartridge real-time clock) to a frame clock,
+`baseMs + runs * stepMs` in UTC, so two runs see the same time. Set it before
+`loadMedia`; `setPinnedClock(null)` restores the host clock.
+
+**Additional memory regions.** On sync32: `sync32_timing` (0x1A3, per-frame
+cycle counts) and `sync32_profile` (0x1A4, a writable PC-sampling profiler).
+On gambatte: `gb_apu_raw` (the APU's stereo samples before resampling) and
+`gb_lcdlog` (a ring of LCD timing decisions). On mGBA: `gba_audio_raw` (the
+stereo samples before resampling). On Genesis carts with the SVP chip:
+`genesis_svp_dram`, `genesis_svp_iram` and `genesis_svp_ssp` (size 0 on carts
+without it). Region names map to ids through `MemoryRegionToRetro`.
## Deterministic GB/GBC/NES sessions
@@ -179,7 +206,7 @@ slot numbers across gaps. Deterministic input accepts the eight native buttons.
See `romdevtools/scripts/multiplayer/README.md` for the fixed session identities,
frame-boundary restrictions, compiler records, reproducible builds and tests.
-## Logical world observation (0.16.0)
+## Logical world observation
`startWorldObservation({trigger, tick, fields, value: 0xa5})` binds an explicit
ROM publication write on GB/GBC/NES. After updating the world, the engine writes
diff --git a/packages/romdev-core-host/cpu-state.js b/packages/romdev-core-host/cpu-state.js
index 52d0b95c..c4c5baec 100644
--- a/packages/romdev-core-host/cpu-state.js
+++ b/packages/romdev-core-host/cpu-state.js
@@ -352,6 +352,22 @@ function decodeZ80(bytes) {
* @param {string} [cpu] "main" (default) or "spc700" for SNES
* @returns {CPUState | null}
*/
+/** `n` u32 LE words of a region, or null when this core build lacks it. */
+function readU32s(host, region, n) {
+ try {
+ if (!(host.regionSize?.(region) >= n * 4)) return null;
+ const b = host.readMemory(region, 0, n * 4);
+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
+ return Array.from({ length: n }, (_, i) => dv.getUint32(i * 4, true) >>> 0);
+ } catch { return null; }
+}
+
+/** mGBA's master clock (gba_timing), as `coreInternal`, when the core has it. */
+function gbaTiming(host) {
+ const t = readU32s(host, "gba_timing", 4);
+ return t ? { coreInternal: { masterClock: t[0], cpuCycles: t[1], nextEvent: t[2], masterCycles: t[3] } } : {};
+}
+
export function getCPUState(host, platform, cpu = "main") {
if (platform === "n64" || platform === "ps1") {
return decodeMips(host.getMipsRegs?.());
@@ -366,7 +382,10 @@ export function getCPUState(host, platform, cpu = "main") {
if (platform === "snes") {
const state = host.serializeState();
if (cpu === "spc700") return decodeSnes9xSPC(state);
- return decodeSnes9xCPU(state); // 65816
+ const st = decodeSnes9xCPU(state); // 65816
+ const t = readU32s(host, "snes_timing", 5);
+ if (t) st.coreInternal = { ...(st.coreInternal ?? {}), masterClock: t[0], lineCycles: t[1], vCounter: t[2], hMax: t[3], totalFrames: t[4] };
+ return st;
}
if (platform === "genesis") {
if (cpu === "z80") {
@@ -486,6 +505,11 @@ export function getCPUState(host, platform, cpu = "main") {
ime: !!bytes[12],
halted: !!bytes[13],
},
+ // Bytes 14-17 are gambatte's CPU clock (cycleCounter_) on cores built
+ // with it (0 on older builds, where they were reserved).
+ coreInternal: {
+ cycleCounter: (bytes[14] | (bytes[15] << 8) | (bytes[16] << 16) | (bytes[17] << 24)) >>> 0,
+ },
};
}
if (platform === "gba") {
@@ -531,6 +555,7 @@ export function getCPUState(host, platform, cpu = "main") {
spsr: hex32(spsr),
note: "ARM PC is pipeline-prefetched; the executing instruction is at execPc " +
"(PC-8 in ARM, PC-4 in THUMB). Registers are decimal; cpsr/spsr/execPc are hex.",
+ ...gbaTiming(host),
};
}
if (platform === "sync32") {
@@ -564,6 +589,26 @@ export function getCPUState(host, platform, cpu = "main") {
if (bits !== 0) fpu["S" + i] = asFloat(bits);
}
const itstate = u32(49);
+ // Frame timing from the core's deterministic cycle model (sync32_timing,
+ // absent on older core builds): the last frame's work cycles against the
+ // ABI floor. The floor is the console's guarantee (150 MHz-equivalent);
+ // shipping boards clock core 0 at 252 or 315 MHz, so those budgets are
+ // reported too, as context.
+ const tm = readU32s(host, "sync32_timing", 10);
+ const timing = tm && tm[0] === 0x54323353 ? (() => {
+ const floor = tm[2], mhz = tm[3], fc = tm[5];
+ const budget = (m) => Math.round(floor * m / mhz);
+ return {
+ frameCycles: fc,
+ framesPresented: tm[4],
+ totalCycles: tm[6] + tm[7] * 2 ** 32,
+ floorCycles: floor,
+ floorClockMHz: mhz,
+ pctOfFloor: Math.round(fc / floor * 10000) / 100,
+ budgets: { floor150MHz: floor, mhz252: budget(252), mhz315: budget(315) },
+ note: "frameCycles = CPU cycles the cart spent between the previous present() and this one (the vblank wait excluded), from s32core's cycle model; costs are estimates until calibrated on hardware (no flash wait-state or XIP cache model).",
+ };
+ })() : null;
return {
pc: gprs[15],
sp: gprs[13],
@@ -578,6 +623,7 @@ export function getCPUState(host, platform, cpu = "main") {
// touches the FPU stays readable.
...(Object.keys(fpu).length ? { fpu } : {}),
...(itstate ? { itstate: hex32(itstate) } : {}),
+ ...(timing ? { coreInternal: timing } : {}),
note: "Cortex-M33 is always Thumb. PC is the NEXT instruction to execute " +
"(this is an interpreter, so there is no pipeline offset to undo). " +
"Registers are decimal; flags.raw is the packed APSR (N|Z|C|V|Q in bits 4..0). " +
diff --git a/packages/romdev-core-host/dsp-state.js b/packages/romdev-core-host/dsp-state.js
index d8463d63..0d351dad 100644
--- a/packages/romdev-core-host/dsp-state.js
+++ b/packages/romdev-core-host/dsp-state.js
@@ -1,6 +1,6 @@
// SNES S-DSP state introspection.
//
-// Per the rom-games agent's audio-debugging asks: distinguish "voice
+// Purpose: distinguish "voice
// never produced output" (BRR/envelope issue) from "voice produced
// output but mixer muted it" (master volume issue). The data lives in
// the savestate's "SND" block, AFTER the SMP::save_state region. We
@@ -156,7 +156,7 @@ export function decodeSnes9xDSP(state) {
// rather than `kon` / `koff` / `endx` (state names) so callers don't
// mistake the byte for a live interpretation. Field names are still
// memorable (the address IS the canonical DSP register name) but
- // semantically honest about what you're reading.
+ // semantically accurate about what you're reading.
//
// Source: snes9x/src/apu/bapu/dsp/SPC_DSP.h r_* constants; .cpp KON/
// ENDX special-case write handling at lines 285-291.
diff --git a/packages/romdev-core-host/gamegenie.js b/packages/romdev-core-host/gamegenie.js
index bd005e37..3422229f 100644
--- a/packages/romdev-core-host/gamegenie.js
+++ b/packages/romdev-core-host/gamegenie.js
@@ -114,7 +114,7 @@ export function encodeNesGameGenie({ address, value, compare }) {
* (GATKGATX-style spellings) is a mis-published code, not a convention.
* An earlier version left it clear on the strength of that outlier,
* which made every emitted 8-letter code differ from its canonical
- * published spelling by exactly this bit (SLZPLOVS for Contra's
+ * published spelling by exactly this bit (SLZPLOVS for a published
* SLXPLOVS, and so on).
*
* Decoders are forgiving - fceumm branches on length and masks the bit
@@ -433,7 +433,7 @@ export function decodeProActionReplay(code, platform) {
* Returns one of: "game-genie", "pro-action-replay", "gameshark",
* "action-replay", "raw", or "unknown". Per-platform, because the SAME shape
* means different devices on different systems (8 hex = SNES PAR, but on GB =
- * GameShark). This is what lets us be HONEST about device type. */
+ * GameShark). This is what lets the device type be reported accurately. */
export function detectDevice(code, platform) {
const c = code.trim();
if (c.includes(":")) return "raw";
@@ -593,7 +593,7 @@ export function encodeRaw({ address, value, compare }) {
}
// Which physical cheat DEVICE each platform's "native" code is for. This is the
-// honesty layer: we don't call everything "Game Genie" - SNES native is Pro
+// Accuracy layer: do not call everything "Game Genie" - SNES native is Pro
// Action Replay, SMS/GG is Action Replay, GB has both GG (ROM) and GameShark
// (RAM). `nativeDevicesFor` lists them best-first.
export function nativeDevicesFor(platform) {
diff --git a/packages/romdev-core-host/gametank-acp-state.js b/packages/romdev-core-host/gametank-acp-state.js
index 5b2f66ec..50f988b4 100644
--- a/packages/romdev-core-host/gametank-acp-state.js
+++ b/packages/romdev-core-host/gametank-acp-state.js
@@ -26,7 +26,7 @@ export function decodeGameTankAcp(a) {
const clkMult = a[9] & 0xFF;
// "playing" = the audio CPU is running, not muted/resetting, and the DAC isn't
- // parked at the midpoint silence ($80) - a coarse but honest activity signal.
+ // parked at the midpoint silence ($80) - a coarse but real activity signal.
const playing = running && !muted && !resetting && dacReg !== 0x80;
return {
diff --git a/packages/romdev-core-host/glOptionalDep.js b/packages/romdev-core-host/glOptionalDep.js
index 44723aac..6ec07c07 100644
--- a/packages/romdev-core-host/glOptionalDep.js
+++ b/packages/romdev-core-host/glOptionalDep.js
@@ -1,20 +1,20 @@
-// glOptionalDep.js - lazy, optional loader for the native GL stack.
+// glOptionalDep.js - lazy loader for the native GL stack.
//
// The HW-render cores (N64 ParaLLEl, PS1 Beetle-PSX) need a real headless GL
// context. romdev provides it through `native-gles` (EGL/GLES via a prebuilt
// .node) and `webgl-node` (a WebGL2 context object for the minified Emscripten
-// cores). Both are OPTIONAL dependencies: the 14 software-rendered cores never
-// touch them, and a headless user who never boots N64/PS1 doesn't need them
-// installed. We load them lazily and, if absent, throw ONE clear, actionable
-// error instead of a cryptic module-not-found.
+// cores). Both are regular dependencies of this package. They are loaded lazily,
+// only when a HW-render core boots, so the software-rendered cores never load
+// them; if the install is broken, ONE clear, actionable error replaces a cryptic
+// module-not-found.
let _gl = null;
let _webgl = null;
const INSTALL_HINT =
- "N64/PS1 emulation needs the optional native GL module. Install it with:\n" +
- " npm install native-gles webgl-node\n" +
- "(the other 14 platforms are software-rendered and don't require it).";
+ "N64/PS1/Dreamcast emulation needs the native GL modules (native-gles, webgl-node),\n" +
+ "which are dependencies of romdev-core-host but did not load. Reinstall them with:\n" +
+ " npm install native-gles webgl-node";
/**
* Load the `native-gles` default export (the EGL/GLES binding). Cached.
diff --git a/packages/romdev-core-host/gpgx-state.js b/packages/romdev-core-host/gpgx-state.js
index d1ef3601..750d140e 100644
--- a/packages/romdev-core-host/gpgx-state.js
+++ b/packages/romdev-core-host/gpgx-state.js
@@ -252,7 +252,7 @@ export function decodeGenesisPSG(blob) {
//
// gpgx's YM2612 internal struct is large and implementation-private. We
// decode what's safely reachable: the dacen flag + dacout value (DAC sample
-// stream - the "PCM voice" Genesis games like Streets of Rage 2 use). Full
+// stream - the "PCM voice" many Genesis games use). Full
// per-channel envelope state requires walking FM_CH/FM_SLOT internals
// whose layout isn't stable across gpgx versions; that's deferred.
//
diff --git a/packages/romdev-core-host/nes-apu-state.js b/packages/romdev-core-host/nes-apu-state.js
index 391820bf..efe4bebd 100644
--- a/packages/romdev-core-host/nes-apu-state.js
+++ b/packages/romdev-core-host/nes-apu-state.js
@@ -1,6 +1,6 @@
// NES 2A03 APU state introspection.
//
-// Per the rom-games music-analysis asks: give NES titles the same "what is
+// Gives NES titles the same "what is
// each channel playing this frame?" decode that getAudioState already gives
// SNES (dsp) and Genesis (psg/ym2612). Before this, an NES music job had to
// reverse-engineer the game's private sound-driver RAM by hand; now the
diff --git a/packages/romdev-core-host/package.json b/packages/romdev-core-host/package.json
index 8d581ad3..67b8e2b9 100644
--- a/packages/romdev-core-host/package.json
+++ b/packages/romdev-core-host/package.json
@@ -1,7 +1,7 @@
{
"name": "romdev-core-host",
- "version": "0.16.0",
- "description": "The romdev libretro host runtime, now ISOMORPHIC: load a romdev-core-* emulator core from disk (Node) or from a factory + wasm bytes (browser/worker), run frames, read the framebuffer/audio/memory regions as typed arrays, drive input, save/load state. The same hardened host the romdev MCP server uses.",
+ "version": "0.14.1",
+ "description": "The romdev libretro host runtime for Node and the browser: load a romdev-core-* emulator core from disk (Node) or from a factory + wasm bytes (browser/worker), run frames, read the framebuffer/audio/memory regions as typed arrays, drive input, save/load state. The same hardened host the romdev MCP server uses.",
"type": "module",
"main": "index.js",
"exports": {
diff --git a/packages/romdev-core-host/types.js b/packages/romdev-core-host/types.js
index d6db36ef..af925432 100644
--- a/packages/romdev-core-host/types.js
+++ b/packages/romdev-core-host/types.js
@@ -11,21 +11,22 @@
* | "snes_oam" | "snes_cgram" | "snes_aram" | "snes_fillram"
* | "genesis_cram" | "genesis_vsram" | "genesis_vdp_regs"
* | "genesis_z80_ram" | "genesis_m68k" | "genesis_ym2612" | "genesis_psg"
+ * | "genesis_svp_dram" | "genesis_svp_iram" | "genesis_svp_ssp"
* | "md_linepix" | "md_bgpix" | "md_objpix" | "md_pixrgb" | "md_linestate"
* | "sms_linepix" | "sms_bgpix" | "sms_objpix" | "sms_pixrgb" | "sms_linestate"
* | "gg_linepix" | "gg_bgpix" | "gg_objpix" | "gg_pixrgb" | "gg_linestate"
* | "sms_vram" | "sms_cram" | "sms_vdp_regs" | "sms_z80_regs"
- * | "gg_vram" | "gg_cram"
+ * | "gg_vram" | "gg_cram" | "gpgx_blip_deltas"
* | "gb_vram" | "gb_oam" | "gb_io" | "gb_hram"
* | "gb_bgpdata" | "gb_objpdata" | "gb_cpu_regs"
* | "gb_lineregs" | "gb_bgpix" | "gb_sprpix" | "gb_palline"
- * | "gb_bgcol15" | "gb_sprcol15"
+ * | "gb_bgcol15" | "gb_sprcol15" | "gb_lcdlog" | "gb_apu_raw"
* | "a26_tia_regs" | "a26_cpu_regs"
* | "a78_cpu_regs"
* | "c64_color_ram" | "c64_vic_regs" | "c64_sid_regs"
* | "c64_cia1_regs" | "c64_cia2_regs" | "c64_cpu_regs"
- * | "gba_cpu_regs" | "gba_io_regs" | "gba_palette" | "gba_oam" | "gba_iwram"
- * | "sync32_cpu_regs" | "sync32_palette" | "sync32_canvas"
+ * | "gba_cpu_regs" | "gba_io_regs" | "gba_palette" | "gba_oam" | "gba_iwram" | "gba_audio_raw"
+ * | "sync32_cpu_regs" | "sync32_palette" | "sync32_canvas" | "sync32_timing" | "sync32_profile"
* | "lynx_cpu_regs" | "lynx_hw_regs"
* | "pce_vdc_vram" | "pce_vdc_satb" | "pce_vdc_regs"
* | "pce_vce_palette" | "pce_cpu_regs" | "pce_psg_regs"
@@ -102,6 +103,18 @@ export const RetroMemory = {
SNES_CLIPLINES: 0x1B5,
SNES_LP_WORLD: 0x1B6,
SNES_LP_OBJ: 0x1B7,
+ /** 20 bytes, 5 u32 LE: [0] master clock since line 0 (V_Counter*H_Max + Cycles),
+ * [1] CPU.Cycles, [2] CPU.V_Counter, [3] Timings.H_Max, [4] TotalEmulatedFrames. */
+ SNES_TIMING: 0x1B8,
+ /** The active coprocessor's internal state, serialized on read by the same
+ * romdev_chipstate.h the recompiled cart's chip units compile (DSP-3, ST011,
+ * ST018, S-RTC, SPC7110, BS-X); size 0 on any other cart. */
+ SNES_CHIPSTATE: 0x1B9,
+ /** The BS-X's 512KB PSRAM (where the BIOS loads a BS program); BS-X carts only. */
+ SNES_BSX_PSRAM: 0x1BA,
+ // bsnes (romdev-core-bsnes) only: every S-CPU access to a firmware chip
+ // (ST010/ST011/ST018) with the master clock, a ring the cross-check replays
+ SNES_CHIPLOG: 0x1BB,
GENESIS_CRAM: 0x120,
GENESIS_VSRAM: 0x121,
GENESIS_VDP_REGS: 0x122,
@@ -121,6 +134,17 @@ export const RetroMemory = {
SMS_Z80_REGS: 0x133,
GG_VRAM: 0x134,
GG_CRAM: 0x135,
+ /** RDAS per-frame event stream (s32 x 3, rate 0): every blip_add_delta on
+ * the main blip buffer this retro_run as (blip clock time, delta_l, delta_r)
+ * - the FM + PSG input to blip_buf BEFORE band-limited resampling. Shared by
+ * the genesis / sms / gg platforms (all genesis_plus_gx). */
+ GPGX_BLIP_DELTAS: 0x136,
+ /** SVP carts (gpgx cart_hw/svp): the SSP1601 DRAM (128KB of host-order
+ * 16-bit words), its 2KB IRAM and the ssp1601_t state. Absent (size 0)
+ * on a cart without the chip. */
+ GENESIS_SVP_DRAM: 0x137,
+ GENESIS_SVP_IRAM: 0x138,
+ GENESIS_SVP_SSP: 0x139,
GB_VRAM: 0x140,
GB_OAM: 0x141,
GB_IO: 0x142,
@@ -135,6 +159,10 @@ export const RetroMemory = {
GB_PALLINE: 0x14A,
GB_BGCOL15: 0x14B,
GB_SPRCOL15: 0x14C,
+ GB_LCDLOG: 0x14D,
+ /** RDAS per-frame audio stream: every stereo s16 sample frame PSG::fillBuffer
+ * produced this retro_run at 2097152 Hz, BEFORE blipper / the CC resampler. */
+ GB_APU_RAW: 0x14E,
A78_CPU_REGS: 0x150,
A26_TIA_REGS: 0x160,
A26_CPU_REGS: 0x161,
@@ -152,17 +180,36 @@ export const RetroMemory = {
GBA_PALETTE: 0x182,
GBA_OAM: 0x183,
GBA_IWRAM: 0x184,
+ /** 16 bytes, 4 u32 LE: [0] master clock (mTimingCurrentTime), [1] cpu->cycles,
+ * [2] cpu->nextEvent, [3] timing.masterCycles. Assembled on read. */
+ GBA_TIMING: 0x185,
+ /** RDAS per-frame audio stream (src/host/audio-verify.js AUDIO_STREAM): the
+ * stereo s16 samples GBAAudioSample produced this retro_run, at the native
+ * 16777216/sampleInterval Hz, BEFORE libretro's resampler to 65536 Hz. */
+ GBA_AUDIO_RAW: 0x186,
// Lynx (handy): CPU snapshot + the $FC00-$FDFF Suzy/Mikey HW register window
// (sprite regs, LCD control, audio $FD20-$FD3F, palette $FDA0-$FDBF).
LYNX_CPU_REGS: 0x190,
LYNX_HW_REGS: 0x191,
- // sync32 (s32core). The console is monteslu's own, so the core exposes
+ // sync32 (s32core). sync32 is a homebrew-only console, so the core exposes
// exactly what a game DEVELOPER needs to debug their own cart - there are no
// commercial ROMs here to reverse-engineer.
SYNC32_CPU_REGS: 0x1A0, // Cortex-M33: r0-r15, APSR, s0-s31, ITSTATE
SYNC32_PALETTE: 0x1A1, // 256 entries, RGB565
SYNC32_CANVAS: 0x1A2, // the 320x240 8-bit indexed framebuffer
+ /** Frame timing, u32 LE: [0] 'S32T', [1] layout version, [2] ABI floor
+ * cycles per frame, [3] floor clock MHz, [4] frames presented, [5] last
+ * frame's work cycles, [6..7] total cycles lo/hi, [8] history capacity,
+ * [9] frames recorded; [16..] ring of per-frame work cycles, recorded
+ * frame k (1-based) at 16 + (k - 1) % capacity. */
+ SYNC32_TIMING: 0x1A3,
+ /** pc-sampling profiler, u32 LE, WRITABLE control block: [0] 'S32P',
+ * [1] enable, [2] base address, [3] shift, [4] bucket count, [5] active
+ * (core-set), [6] clear request, [7] frames profiled; [16..] buckets of
+ * CPU cycles, bucket (pc - base) >> shift, the last one also collecting
+ * every pc outside the window. The vblank idle snap is excluded. */
+ SYNC32_PROFILE: 0x1A4,
// Sprite sheets 0..31 at 0x1B0+n: 8-bit indices into the palette. sync32 has
// no OAM - a game blits from these with api->sprite() - so the sheets ARE
// the sprite data. Only sheet0 is named here; the rest are reachable by id.
@@ -261,6 +308,10 @@ export const MemoryRegionToRetro = {
snes_cliplines: RetroMemory.SNES_CLIPLINES,
snes_lp_world: RetroMemory.SNES_LP_WORLD,
snes_lp_obj: RetroMemory.SNES_LP_OBJ,
+ snes_timing: RetroMemory.SNES_TIMING,
+ snes_chipstate: RetroMemory.SNES_CHIPSTATE,
+ snes_bsx_psram: RetroMemory.SNES_BSX_PSRAM,
+ snes_chiplog: RetroMemory.SNES_CHIPLOG,
genesis_cram: RetroMemory.GENESIS_CRAM,
genesis_vsram: RetroMemory.GENESIS_VSRAM,
genesis_vdp_regs: RetroMemory.GENESIS_VDP_REGS,
@@ -268,6 +319,9 @@ export const MemoryRegionToRetro = {
genesis_m68k: RetroMemory.GENESIS_M68K,
genesis_ym2612: RetroMemory.GENESIS_YM2612,
genesis_psg: RetroMemory.GENESIS_PSG,
+ genesis_svp_dram: RetroMemory.GENESIS_SVP_DRAM,
+ genesis_svp_iram: RetroMemory.GENESIS_SVP_IRAM,
+ genesis_svp_ssp: RetroMemory.GENESIS_SVP_SSP,
/* gpgx resolved-layer capture (shared line renderer, so the same core
* regions serve genesis/sms/gg; per-platform aliases below). */
md_linepix: RetroMemory.MD_LINEPIX,
@@ -294,6 +348,7 @@ export const MemoryRegionToRetro = {
sms_z80_regs: RetroMemory.SMS_Z80_REGS,
gg_vram: RetroMemory.GG_VRAM,
gg_cram: RetroMemory.GG_CRAM,
+ gpgx_blip_deltas: RetroMemory.GPGX_BLIP_DELTAS,
gb_vram: RetroMemory.GB_VRAM,
gb_oam: RetroMemory.GB_OAM,
gb_io: RetroMemory.GB_IO,
@@ -307,6 +362,8 @@ export const MemoryRegionToRetro = {
gb_palline: RetroMemory.GB_PALLINE,
gb_bgcol15: RetroMemory.GB_BGCOL15,
gb_sprcol15: RetroMemory.GB_SPRCOL15,
+ gb_lcdlog: RetroMemory.GB_LCDLOG,
+ gb_apu_raw: RetroMemory.GB_APU_RAW,
a78_cpu_regs: RetroMemory.A78_CPU_REGS,
a26_tia_regs: RetroMemory.A26_TIA_REGS,
a26_cpu_regs: RetroMemory.A26_CPU_REGS,
@@ -321,9 +378,13 @@ export const MemoryRegionToRetro = {
gba_palette: RetroMemory.GBA_PALETTE,
gba_oam: RetroMemory.GBA_OAM,
gba_iwram: RetroMemory.GBA_IWRAM,
+ gba_timing: RetroMemory.GBA_TIMING,
+ gba_audio_raw: RetroMemory.GBA_AUDIO_RAW,
sync32_cpu_regs: RetroMemory.SYNC32_CPU_REGS,
sync32_palette: RetroMemory.SYNC32_PALETTE,
sync32_canvas: RetroMemory.SYNC32_CANVAS,
+ sync32_timing: RetroMemory.SYNC32_TIMING,
+ sync32_profile: RetroMemory.SYNC32_PROFILE,
sync32_sheet0: RetroMemory.SYNC32_SHEET0,
lynx_cpu_regs: RetroMemory.LYNX_CPU_REGS,
lynx_hw_regs: RetroMemory.LYNX_HW_REGS,
@@ -414,7 +475,7 @@ export const MemoryRegionToRetro = {
* to cartridge; C64 depends on the file kind - a `.d64`/`.g64`/`.d71`/`.d81` is a
* disk, a `.tap` is a tape, a `.crt` is a cartridge, and a bare `.prg`/`.p00` is
* a program injected directly. The extension is passed when known (loadMedia has
- * it) so disk/tape images report honestly in status() and the agent knows a
+ * it) so disk/tape images report accurately in status() and the agent knows a
* writable disk exists for saves.
* @param {string} platform
* @param {string} [ext] lower- or mixed-case file extension incl. dot, e.g. ".d64"
diff --git a/packages/romdev-core-parallel-n64/README.md b/packages/romdev-core-parallel-n64/README.md
index 7cf243cc..2705ccbe 100644
--- a/packages/romdev-core-parallel-n64/README.md
+++ b/packages/romdev-core-parallel-n64/README.md
@@ -1,47 +1,40 @@
# romdev-core-parallel-n64
The [ParaLLEl-N64](https://github.com/libretro/parallel-n64) libretro core
-(Nintendo 64) bundled as WASM for [romdev](https://github.com/monteslu/romdev),
-built **headless-angrylion** (software).
+(Nintendo 64), compiled to WebAssembly for
+[romdev](https://github.com/monteslu/romdev).
-## Why headless-angrylion
+The RDP is rendered on the GPU by **glide64**, ParaLLEl-N64's GL renderer: it
+translates the game's RDP display lists to GLES/WebGL2 calls, and the host
+reads each frame back. The core is loaded with `hwRender: true` and needs the
+headless GL context that `romdev-core-host` provides through `native-gles`, the
+same path as the PS1 (Beetle PSX HW) and Dreamcast (Flycast) cores. romdev
+selects glide64 through a core option.
-The default ParaLLEl-N64 build renders through glide64/GL, which only presents the
-**RDP display-lists** a game issues - it does NOT scan out a raw CPU-written VI
-framebuffer. romdev's N64 homebrew (the bundled software-3D lib) draws directly into
-an RDRAM framebuffer, so it needs a renderer that honors the **Video Interface
-scanout**. This build compiles GL **out**, stubs the inactive video-plugin tables,
-and forces the **angrylion** software RDP - which presents the VI framebuffer via
-`video_cb` (no GL). Loaded with `hwRender: false`.
+A binary package: the main `romdevtools` package loads it on demand for
+`loadMedia({platform:'n64'})`. You normally install `romdevtools`
+(`npx romdevtools`), not this package directly.
## Custom romdev build
-Upstream core plus:
-- `romdev_mips_regs_get` - live R4300 register file (`cpu({op:'read'})`)
-- the live-debug set (`romdev_watchpoint_set` / `romdev_pcbreak_set` /
- `romdev_range_set` / ...) - `breakpoint` + `watch`
-- `romdev_ai_get` - the Audio Interface registers (`getAudioState({chip:'ai'})`)
-- a minimal clean-room **IPL3** wrapper so `build({platform:'n64'})` produces a
- self-booting `.z64` (PI-DMAs the game to RDRAM and jumps in).
-
-Built reproducibly by `scripts/build-parallel-n64.sh` in the romdev repo.
-
-The `.wasm` is gitignored and shipped to npm via the package's `files` allowlist.
-
-License: GPL-2.0-or-later (inherits ParaLLEl-N64's license).
-
-## 0.3.0 - the debug hooks work
-
-Through 0.2.0 `romdev_pcbreak_set` / single-step / the PC coverage log never
-fired on this core: the hook was wired only into the pure interpreter (which
-this wasm build cannot boot - it faults into the exception vector) and a hit
-set `stop = 1`, which ended the emulation loop for good. 0.3.0 hooks the
-CACHED interpreter's instruction loop (the default CPU here; the build is
-NO_LIBCO, single-threaded) and a hit does `retro_return(0); break;` - the
-frame ends with the CPU stopped AT the hit PC and the next `retro_run`
-resumes there. `breakpoint({on:'pc'})`, `frame({op:'stepInstructions'})`,
-`watch({on:'pc'})` and the new exact PC coverage bitmap
-(`romdev_covbits_set/get`, host `logPCBitmap`) are real on N64 now. Measured
-on a commercial ROM: single-step advances 0x80000184 → 0x80000188 → ..., an
-osRecvMesg break hits with a0/a1/ra readable, 5 frames log 759,452 executed
-instructions / 32,140 distinct PCs in 24 ms.
+Upstream core (pinned at commit `1da824e13e725a7144f3245324f43d59623974f8`)
+plus these exports:
+
+- `romdev_mips_regs_get`: the live R4300 register file (`cpu({op:'read'})`).
+- romdev's shared live-debug set (`romdev_watchpoint_set`, `romdev_pcbreak_set`,
+ `romdev_range_set`, the PC coverage log and bitmap, and the rest), hooked
+ into the cached interpreter's instruction loop: `breakpoint`, `watch` and
+ `frame({op:'stepInstructions'})` stop with the CPU at the hit PC.
+- `romdev_ai_get`: the Audio Interface registers
+ (`audioDebug({op:'inspect', chip:'ai'})`).
+
+## Upstream and license
+
+**License:** GPL-2.0-or-later (inherits ParaLLEl-N64's license).
+
+**Built by:** `packages/romdevtools/scripts/build-parallel-n64.sh` (it appends
+`scripts/patches/romdev-snippets/n64-regsnap.c` to the core and adds
+`n64-debug.c` plus romdev's shared debug library to the R4300 sources). See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map. The `.wasm` is not in git; it ships to npm
+through the package's `files` list.
diff --git a/packages/romdev-core-parallel-n64/index.js b/packages/romdev-core-parallel-n64/index.js
index 00afd3cf..9a28842f 100644
--- a/packages/romdev-core-parallel-n64/index.js
+++ b/packages/romdev-core-parallel-n64/index.js
@@ -1,13 +1,11 @@
// romdev-core-parallel-n64 - binary package: ParaLLEl-N64 libretro core (N64).
-// HEADLESS-ANGRYLION software build: GL is compiled OUT and the angrylion software
-// RDP is forced, so raw CPU-rendered VI framebuffers DISPLAY (the GL/glide64 build
-// only presents RDP display-lists). This is what lets romdev's software-3D homebrew
-// render. CUSTOM romdev build: upstream core + romdev's debug exports
+// GL-rendered build: the RDP runs on the real GPU through glide64 (GL HLE) and
+// romdev-core-host's native-gles bridge. CUSTOM romdev build: upstream core + romdev's debug exports
// (romdev_mips_regs_get, watchpoint/pcbreak/range live-debug, romdev_ai_get for the
// Audio Interface) + a clean-room IPL3 so build({platform:n64}) self-boots.
// Built reproducibly by scripts/build-parallel-n64.sh.
//
-// Loaded with hwRender:false (the renderer presents via video_cb, not a GL FBO).
+// Loaded with hwRender:true (glide64 renders into the host's GL framebuffer).
import { fileURLToPath } from "node:url";
import path from "node:path";
@@ -16,10 +14,10 @@ const WASM = path.join(__dirname, "wasm");
export const platform = "n64";
-// Emulator core (libretro) - glue .js + .wasm. Software renderer (no GL bridge).
+// Emulator core (libretro) - glue .js + .wasm. GL renderer (glide64).
export const core = {
name: "parallel_n64",
jsPath: path.join(WASM, "parallel_n64_libretro.js"),
wasmPath: path.join(WASM, "parallel_n64_libretro.wasm"),
- hwRender: false,
+ hwRender: true,
};
diff --git a/packages/romdev-core-parallel-n64/package.json b/packages/romdev-core-parallel-n64/package.json
index 167ea4f1..1dabea5f 100644
--- a/packages/romdev-core-parallel-n64/package.json
+++ b/packages/romdev-core-parallel-n64/package.json
@@ -1,7 +1,7 @@
{
"name": "romdev-core-parallel-n64",
- "version": "0.3.1",
- "description": "ParaLLEl-N64 libretro core (Nintendo 64), HEADLESS-ANGRYLION software build for romdev (no GL - scans out raw RDRAM framebuffers), bundled as WASM with romdev's CPU + AI + live-debug exports.",
+ "version": "0.3.2",
+ "description": "ParaLLEl-N64 libretro core (Nintendo 64), GL-rendered through glide64, for romdev, bundled as WASM with romdev's CPU + AI + live-debug exports.",
"type": "module",
"main": "index.js",
"exports": {
diff --git a/packages/romdev-core-prosystem/README.md b/packages/romdev-core-prosystem/README.md
index 1035daf9..4d6d43af 100644
--- a/packages/romdev-core-prosystem/README.md
+++ b/packages/romdev-core-prosystem/README.md
@@ -2,19 +2,21 @@
ProSystem - Atari 7800 emulator core (libretro), as WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand. You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
-## Upstream & license
+## Upstream and license
-Bundles: **prosystem**.
+Bundles: **ProSystem**, https://github.com/libretro/prosystem-libretro.
**License:** GPL-2.0-or-later
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+This package redistributes the upstream source built to WebAssembly. The
+upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
-**Built by:** `romdevtools/scripts/build-prosystem.sh` + patch(es) `prosystem-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-prosystem.sh` with patch(es) `prosystem-romdev-memory-regions.patch`. See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-prosystem/package.json b/packages/romdev-core-prosystem/package.json
index d5ceec12..affc232b 100644
--- a/packages/romdev-core-prosystem/package.json
+++ b/packages/romdev-core-prosystem/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-prosystem",
- "version": "0.10.1",
+ "version": "0.10.2",
"description": "ProSystem libretro core (Atari 7800) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-runner/README.md b/packages/romdev-core-runner/README.md
index 18fb34ec..91e15ef5 100644
--- a/packages/romdev-core-runner/README.md
+++ b/packages/romdev-core-runner/README.md
@@ -110,11 +110,12 @@ produces a zero-size window), `letterbox(winW, winH, aspect)`,
`framebufferToRgba(fb, out?)` (pass the previous return value as `out` to
reuse the buffer across ticks - no per-frame allocation), and
`drawFpsOverlay(rgba, width, height, fps)` (the corner fps counter, pure
-pixel writes), plus `initSdl()` (the hardened loader) and
+pixel writes), plus `initSdl()` (the SDL loader with the self-repair step above) and
`sdlPackageRoot()`.
## Requirements
Node >= 24, ESM only. Software-rendered cores work everywhere SDL does;
-the 3D cores additionally want the `native-gles` optional dependency (see
-the `romdev-core-host` README).
+the 3D cores also need a working GPU for the headless GL context that
+`romdev-core-host` creates through its `native-gles` dependency (see the
+`romdev-core-host` README).
diff --git a/packages/romdev-core-runner/package.json b/packages/romdev-core-runner/package.json
index 52d97031..18d66494 100644
--- a/packages/romdev-core-runner/package.json
+++ b/packages/romdev-core-runner/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-runner",
- "version": "0.2.18",
+ "version": "0.2.19",
"description": "Play a ROM you just built: an SDL window over the romdev libretro host (romdev-core-host) with keyboard + hot-plug gamepad input, audio, and aspect-correct pixel-perfect scaling. The human 'fire it up' tier between an external emulator and the romdev MCP server. Bundles NO cores; pass any romdev-core-* package.",
"type": "module",
"main": "index.js",
@@ -23,7 +23,7 @@
"url": "git+https://github.com/monteslu/romdev.git"
},
"dependencies": {
- "romdev-core-host": "0.16.0"
+ "romdev-core-host": "0.14.1"
},
"optionalDependencies": {
"@kmamal/sdl": "^0.11.13"
diff --git a/packages/romdev-core-runner/runRom.js b/packages/romdev-core-runner/runRom.js
index 4bc8b915..f25c987e 100644
--- a/packages/romdev-core-runner/runRom.js
+++ b/packages/romdev-core-runner/runRom.js
@@ -72,7 +72,7 @@ export async function runRom(rom, opts = {}) {
const buttonMap = opts.buttonMap ?? SDL_BUTTON_TO_LIBRETRO_BIT;
const keyMap = opts.keyMap ?? KEY_TO_LIBRETRO_BIT;
- // SDL first - fail fast (and honestly: SDL_UNAVAILABLE) before touching the core.
+ // SDL first - fail fast (with SDL_UNAVAILABLE) before touching the core.
const sdl = await initSdl({ log, ...(opts._initSdlOpts ?? {}) });
// Load core + ROM.
diff --git a/packages/romdev-core-runner/sdl.js b/packages/romdev-core-runner/sdl.js
index 86b4454f..f674f141 100644
--- a/packages/romdev-core-runner/sdl.js
+++ b/packages/romdev-core-runner/sdl.js
@@ -11,7 +11,7 @@
// verified (and repaired) BEFORE the first import.
// - With no presentable display SDL silently picks the "offscreen"/"dummy"
// video driver - createWindow SUCCEEDS but nothing appears on any screen.
-// We ask SDL which driver it actually selected and fail honestly.
+// We ask SDL which driver it actually selected and fail with a clear error.
//
// On failure throws an Error tagged `.code = "SDL_UNAVAILABLE"` plus
// `.sdlKind` ("missing-binary" | "install-failed" | "sdl-error" |
@@ -52,7 +52,7 @@ export function sdlPackageRoot(resolve = require.resolve) {
let _sdlModule = null;
/**
- * Load @kmamal/sdl with the self-repair + honest-failure behavior described in
+ * Load @kmamal/sdl with the self-repair + clear-failure behavior described in
* the header. Memoized per process (SDL can only init once anyway).
*
* @param {Object} [opts]
diff --git a/packages/romdev-core-s32core/README.md b/packages/romdev-core-s32core/README.md
index 32224262..7c6b06d9 100644
--- a/packages/romdev-core-s32core/README.md
+++ b/packages/romdev-core-s32core/README.md
@@ -1,50 +1,58 @@
# romdev-core-s32core
The **sync32** console core for [romdev](https://github.com/monteslu/romdev),
-bundled as WASM.
+bundled as WebAssembly.
-sync32 is monteslu's RP2350 console: games are Cortex-M33 ARM binaries shipped
-as `.s32` files. `s32core` is a first-party pure-C interpreter for it, exposed
-through the libretro API - the same shape as every other romdev core, so the
-host runs it with no special-casing.
+sync32 is an open RP2350-based console: games are Cortex-M33 ARM binaries
+shipped as `.s32` files. `s32core` is a pure-C interpreter for it, exposed
+through the libretro API, the same shape as every other romdev core, so the
+host runs it with no special cases.
-Built with **NODERAWFS**: the frontend `fopen()`s the `.s32` by its real path
-and streams the game's `/` data directory straight off the host
-filesystem, rather than preloading it into MEMFS. A cart with resources
-therefore reads them from disk exactly as it does on hardware.
+It is built with **NODERAWFS**: the frontend `fopen()`s the `.s32` by its real
+path and streams the game's `/` data directory from the host
+filesystem rather than preloading it into memory, so a cart reads its
+resources from disk the way it does on hardware.
## Debugger views
The core exposes its state through libretro's memory interface, so a frontend
-can inspect a running game - this is aimed at **developing** a cart, since
-sync32 has no commercial ROMs to reverse-engineer:
+can inspect a running game while you develop a cart:
| id | region | what it is |
|---|---|---|
-| `SYSTEM_RAM` | `system_ram` | the 520KB SRAM at `0x20000000` - a game's globals, its stack, and in ram mode its code |
+| `SYSTEM_RAM` | `system_ram` | the 520KB SRAM at `0x20000000`: a game's globals, its stack, and in RAM mode its code |
| `0x1A0` | `sync32_cpu_regs` | r0-r15, the packed APSR, s0-s31, ITSTATE |
| `0x1A1` | `sync32_palette` | 256 entries, RGB565 |
-| `0x1A2` | `sync32_canvas` | the 320x240 8-bit indexed framebuffer |
+| `0x1A2` | `sync32_canvas` | the 8-bit indexed framebuffer: 320x240, 320x180, or 128x128 in the 128x128 video mode |
+| `0x1A3` | `sync32_timing` | frame timing (u32 LE): the ABI cycle budget per frame, frames presented, the last frame's work cycles, and a ring of per-frame work cycles |
+| `0x1A4` | `sync32_profile` | a PC-sampling profiler (u32 LE, writable control block): enable, base address, shift and bucket count, then CPU cycles per bucket; vblank idle time is excluded |
| `0x1B0+n` | `sync32_sheet0`... | loaded sprite sheet *n*, 8-bit indices |
-SAVE_RAM is deliberately **not** mapped: a frontend persists that to disk, and
-dumping live stack into a `.srm` would be both wrong and useless - sync32 saves
-go through the console's own save slots.
+The video mode comes from the cart header: mode 0 is 320x240 (4:3), mode 1 is
+320x180 (16:9 letterbox), and mode 2 is 128x128, shown at 3x for 128x128
+fantasy-console games.
-These hand out pointers to live state rather than copies, so nothing is paid per
-frame. The CPU block is the one exception - a snapshot refreshed on demand,
-because the interpreter keeps each APSR flag as its own word (faster in the hot
-loop) and packing them belongs on the debugger's side, not the emulator's.
+SAVE_RAM is not mapped: a frontend persists that region to disk, and sync32
+saves go through the console's own save slots instead.
-This package ships built artifacts only. The core's source lives in its own
-repository, and romdev's `scripts/build-s32core.sh` compiles it here.
+These regions hand out pointers to live state rather than copies, so nothing is
+paid per frame. The CPU block is the exception: a snapshot refreshed on demand,
+because the interpreter keeps each APSR flag in its own word and the packing
+happens on the debugger's side.
## Use
```js
import { core, platform } from "romdev-core-s32core";
-// → { name: "s32core", jsPath: ".../s32core_libretro.js", wasmPath: ".../...wasm" }
+// core = { name: "s32core", jsPath: ".../s32core_libretro.js", wasmPath: ".../s32core_libretro.wasm" }
```
-Normally you do not import this directly - romdev's core registry resolves it
-by platform id (`sync32`).
+Normally you do not import this directly: romdevtools' core registry resolves
+it for `loadMedia({platform:'sync32'})`. You normally install `romdevtools`
+(`npx romdevtools`).
+
+## License
+
+MIT. This package ships built artifacts only. The core's source lives in its
+own repository, and `packages/romdevtools/scripts/build-s32core.sh` in the
+romdev repo compiles it from a local checkout (`S32CORE_SRC`).
diff --git a/packages/romdev-core-s32core/package.json b/packages/romdev-core-s32core/package.json
index 89b90439..60b96749 100644
--- a/packages/romdev-core-s32core/package.json
+++ b/packages/romdev-core-s32core/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-s32core",
- "version": "0.2.1",
+ "version": "0.2.2",
"description": "sync32 console core (s32core) for romdev, bundled as WASM. sync32 is an RP2350/Cortex-M33 console; s32core is a first-party pure-C interpreter exposed through the libretro API.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-core-vice/README.md b/packages/romdev-core-vice/README.md
index 46fb51c6..a91770ce 100644
--- a/packages/romdev-core-vice/README.md
+++ b/packages/romdev-core-vice/README.md
@@ -2,9 +2,10 @@
VICE (x64) - Commodore 64 emulator core (libretro), as WebAssembly.
-A binary package for [romdev](https://github.com/monteslu/romdev) - it ships the
-prebuilt WebAssembly + JS glue and is resolved by the main `romdev` package on
-demand. You normally install `romdev`, not this package directly.
+A binary package for [romdev](https://github.com/monteslu/romdev). It ships the
+prebuilt WebAssembly and JS glue, and the main `romdevtools` package loads it on
+demand. You normally install `romdevtools` (`npx romdevtools`), not this package
+directly.
## C64 ROMs: free replacements, bundled
@@ -15,8 +16,8 @@ covers VICE's code rather than those ROMs.
Instead this package ships **[MEGA65 Open ROMs](https://github.com/MEGA65/open-roms)**
in `roms/` - a clean-room, dual GPL-3.0/LGPL-3.0 KERNAL+BASIC+CHARGEN written so
-emulators can ship a working C64 legally. The host installs them automatically,
-so **the C64 boots with zero setup**.
+emulators can ship a working C64. The host installs them automatically, so the
+C64 boots with no setup.
The files are named after Commodore's part numbers (`kernal-901227-03.bin` and
friends) because VICE resolves ROM images by those exact names. The contents are
@@ -29,15 +30,18 @@ notably incomplete. If you own the originals, point `ROMDEV_C64_ROM_DIR` at a
directory containing `kernal-901227-03.bin`, `basic-901226-01.bin` and
`chargen-901225-01.bin`; that overrides the bundled set.
-## Upstream & license
+## Upstream and license
-Bundles: **VICE**.
+Bundles: **VICE** (x64), https://github.com/libretro/vice-libretro.
**License:** GPL-2.0-or-later
-This package redistributes the upstream binary built to WebAssembly; the source
-is fetched from a pinned upstream commit at build time (see the romdev repo's
-`scripts/versions.json` and `BUILDING.md`). See the romdev repo `NOTICE` for the
-full third-party inventory.
+This package redistributes the upstream source built to WebAssembly. The
+upstream version is pinned in `packages/romdevtools/scripts/versions.json` in the
+romdev repo, and the repo's `NOTICE` has the full third-party inventory.
-**Built by:** `romdevtools/scripts/build-vice.sh` + patch(es) `vice-romdev-memory-regions.patch`. See `scripts/BUILD_MAP.md` in the romdev repo for the full recipe→package map.
+**Built by:** `packages/romdevtools/scripts/build-vice.sh` with patches
+`vice-romdev-memory-regions.patch` and `vice-no-embedded-roms.patch` (undefines
+`USE_EMBEDDED`, so no Commodore ROM is compiled in). See
+[BUILD_MAP.md](https://github.com/monteslu/romdev/blob/main/packages/romdevtools/scripts/BUILD_MAP.md)
+for the recipe-to-package map.
diff --git a/packages/romdev-core-vice/package.json b/packages/romdev-core-vice/package.json
index 08afcb86..8ed43d83 100644
--- a/packages/romdev-core-vice/package.json
+++ b/packages/romdev-core-vice/package.json
@@ -1,6 +1,6 @@
{
"name": "romdev-core-vice",
- "version": "0.12.0",
+ "version": "0.12.1",
"description": "VICE x64 libretro core (Commodore 64) for romdev, bundled as WASM.",
"type": "module",
"main": "index.js",
diff --git a/packages/romdev-m2c/LICENSE b/packages/romdev-m2c/LICENSE
new file mode 100644
index 00000000..94a9ed02
--- /dev/null
+++ b/packages/romdev-m2c/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/packages/romdev-m2c/NOTICE b/packages/romdev-m2c/NOTICE
new file mode 100644
index 00000000..2af4f856
--- /dev/null
+++ b/packages/romdev-m2c/NOTICE
@@ -0,0 +1,38 @@
+romdev-m2c
+==========
+
+This package is a JavaScript port of m2c, the MIPS/PowerPC/ARM/SuperH to C
+decompiler, made for romdev. It is a derivative work of m2c and is therefore
+licensed under the GNU General Public License, version 3 (see LICENSE). It is
+kept in its own package so that its GPL terms stay separate from romdev's
+MIT-licensed code, which only calls it.
+
+Components and attribution
+--------------------------
+
+1. m2c (formerly mips_to_c)
+ https://github.com/matt-kempster/m2c
+ Ported from commit 1d1c4454a445326541305f83f2b0cb680a9ecb2d.
+ Copyright the m2c contributors (Matt Kempster, Simon Lindholm, and others).
+ Licensed under the GNU General Public License v3.0 (LICENSE).
+ src/*.js are module-by-module translations of m2c/*.py; m2c_macros.h is
+ copied unchanged.
+
+2. pycparser (m2c's vendored, patched copy m2c_pycparser)
+ Not contained in this package: romdev-m2c depends on the separate
+ romdev-pycparser package (BSD 3-Clause, Eli Bendersky; PLY by David M.
+ Beazley), which is the shared JS port also used by romdev-permuter.
+
+3. CodeWarrior demangler (src/demangle_codewarrior.js)
+ Based on demangler.cs by arookas, 3-clause BSD License
+ (notice reproduced in the source file), as incorporated in m2c.
+
+Corresponding source: this package ships its complete JavaScript source.
+The upstream Python source is available at the URL and commit above.
+
+Graphviz (used only for --visualize SVG output)
+ Not contained in this package: the @viz-js/viz npm dependency (MIT
+ wrapper, https://github.com/mdaines/viz-js) ships Graphviz compiled to
+ WebAssembly. Graphviz is licensed under the Eclipse Public License 1.0
+ (https://graphviz.org/license/). It runs as a separate program on the dot
+ text m2c produces; no Graphviz code is part of romdev-m2c.
diff --git a/packages/romdev-m2c/README.md b/packages/romdev-m2c/README.md
new file mode 100644
index 00000000..44cf1126
--- /dev/null
+++ b/packages/romdev-m2c/README.md
@@ -0,0 +1,73 @@
+# romdev-m2c
+
+A plain JavaScript (ESM) port of [m2c](https://github.com/matt-kempster/m2c),
+the MIPS/PowerPC/ARM/SuperH to C decompiler used by matching-decompilation
+projects. It takes the same flags as upstream's command line and prints the
+same C. No Python is needed.
+
+It is part of [romdev](https://github.com/monteslu/romdev) and is kept in its
+own package so that m2c's GPL terms stay separate from romdev's MIT code, which
+only calls it.
+
+## Upstream and license
+
+- Upstream: m2c, https://github.com/matt-kempster/m2c
+- Ported from commit `1d1c4454a445326541305f83f2b0cb680a9ecb2d`
+- License: GPL-3.0-only (a derivative of m2c). See `LICENSE` and `NOTICE`.
+- `src/*.js` translate `m2c/*.py` module by module; `m2c_macros.h` is copied
+ unchanged. The CodeWarrior demangler is based on arookas' demangler.cs
+ (BSD-3-Clause, notice kept in the source file).
+- The C parser is the separate
+ [`romdev-pycparser`](https://www.npmjs.com/package/romdev-pycparser) package.
+ `--visualize` SVG output uses the
+ [`@viz-js/viz`](https://www.npmjs.com/package/@viz-js/viz) dependency
+ (Graphviz compiled to WebAssembly, EPL-1.0), which runs as a separate program
+ on the dot text m2c produces.
+
+The end-to-end tests run upstream's `tests/end_to_end` corpus through the port
+and compare each result byte for byte with upstream's expected output.
+
+## How romdev uses it
+
+romdevtools' `decomp` tool calls it to produce a first C candidate for a
+function: `decomp({op:'generate', ...})` runs m2c on the function's assembly
+with the translation unit's type context, and `decomp({op:'compare'})` then
+compiles that candidate with the project's original compiler.
+
+## Command line
+
+```sh
+npx romdev-m2c --target mips-ido-c --context ctx.c func.s
+```
+
+The bin is `romdev-m2c`. It accepts upstream m2c's flags, writes the same
+stdout and stderr, and exits with the same code.
+
+## API
+
+```js
+import { decompile, decompileInWorker, UPSTREAM } from "romdev-m2c";
+
+const { code, stdout, stderr } = await decompile([
+ "--target", "mips-ido-c", "--context", "ctx.c", "func.s",
+]);
+```
+
+- `decompile(flags)`: runs m2c in process with upstream's CLI flags and
+ resolves to `{ code, stdout, stderr }`. Assembly inputs may also be passed
+ inline as `{ name, text }` objects.
+- `decompileInWorker(flags, { timeoutMs })`: the same in a worker thread;
+ resolves to `{ code, stdout, stderr, timedOut }` and terminates the worker
+ on timeout.
+- `parse_flags`, `run`, `ArgumentError`: lower-level entry points.
+- `UPSTREAM`: `{ repo, commit }` of the ported m2c.
+
+Exports: `.` and `./m2c_macros.h` (the header m2c's output expects).
+
+## Requirements
+
+Node >= 24, ESM only. No Python, no native code.
+
+## Versions
+
+romdev-m2c 0.1.0 ports m2c at commit `1d1c4454`.
diff --git a/packages/romdev-m2c/m2c_macros.h b/packages/romdev-m2c/m2c_macros.h
new file mode 100644
index 00000000..d4095ead
--- /dev/null
+++ b/packages/romdev-m2c/m2c_macros.h
@@ -0,0 +1,69 @@
+/*
+ * This header contains macros emitted by m2c in "valid syntax" mode,
+ * which can be enabled by passing `--valid-syntax` on the command line.
+ *
+ * In this mode, unhandled types and expressions are emitted as macros so
+ * that the output is compilable without human intervention.
+ */
+
+#ifndef M2C_MACROS_H
+#define M2C_MACROS_H
+
+/* Unknown types */
+typedef s32 M2C_UNK;
+typedef s8 M2C_UNK8;
+typedef s16 M2C_UNK16;
+typedef s32 M2C_UNK32;
+typedef s64 M2C_UNK64;
+
+/* Unknown field access, like `*(type_ptr) &expr->unk_offset` */
+#define M2C_FIELD(expr, type_ptr, offset) (*(type_ptr)((s8 *)(expr) + (offset)))
+
+/* Bitwise (reinterpret) cast */
+#define M2C_BITWISE(type, expr) ((type)(expr))
+
+/* Unaligned reads */
+#define M2C_LWL(expr) (expr)
+#define M2C_FIRST3BYTES(expr) (expr)
+#define M2C_UNALIGNED32(expr) (expr)
+
+/* Unhandled instructions */
+#define M2C_ERROR(desc) (0)
+#define M2C_TRAP_IF(cond) (0)
+#define M2C_BREAK() (0)
+#define M2C_SYNC() (0)
+
+#define GLUE_F64(a, b) (0.0)
+#define MULT_HI(a, b) (0)
+#define MULTU_HI(a, b) (0)
+#define DMULT_HI(a, b) (0)
+#define DMULTU_HI(a, b) (0)
+#define CLZ(x) (0)
+#define REVERSE_BITS(x) (0)
+#define ROTATE_RIGHT(x, shift) (0)
+#define ARM_RRX(x, carry) (0)
+#define BSWAP32(x) (0)
+#define BSWAP16(x) (0)
+#define BSWAP16X2(x) (0)
+
+/* Carry/overflow bits from partially-implemented instructions */
+#define M2C_CARRY 0
+#define M2C_OVERFLOW(a) (0)
+
+/* Memcpy patterns */
+#define M2C_MEMCPY_ALIGNED memcpy
+#define M2C_MEMCPY_UNALIGNED memcpy
+#define M2C_STRUCT_COPY memcpy
+
+/* Sh2 control register loads/stores */
+#define M2C_LOAD_SR() (0)
+#define M2C_LOAD_GBR() (0)
+#define M2C_LOAD_VBR() (0)
+#define M2C_STORE_SR(a)
+#define M2C_STORE_GBR(a)
+#define M2C_STORE_VBR(a)
+
+#define M2C_CMP_STR(a, b) (0)
+#define M2C_TAS_B(a) (0)
+
+#endif
diff --git a/packages/romdev-m2c/package.json b/packages/romdev-m2c/package.json
new file mode 100644
index 00000000..61613ef4
--- /dev/null
+++ b/packages/romdev-m2c/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "romdev-m2c",
+ "version": "0.1.0",
+ "description": "m2c (MIPS/PowerPC/ARM/SuperH to C decompiler) ported to plain JavaScript ESM, for romdev. Output is byte-identical to upstream m2c at the pinned commit.",
+ "type": "module",
+ "main": "src/index.js",
+ "exports": {
+ ".": "./src/index.js",
+ "./m2c_macros.h": "./m2c_macros.h",
+ "./package.json": "./package.json"
+ },
+ "bin": {
+ "romdev-m2c": "src/cli.js"
+ },
+ "files": [
+ "src",
+ "m2c_macros.h",
+ "LICENSE",
+ "NOTICE"
+ ],
+ "scripts": {
+ "test": "node --test 'test/**/*.test.mjs'"
+ },
+ "engines": {
+ "node": ">=24"
+ },
+ "license": "GPL-3.0-only",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/monteslu/romdev.git",
+ "directory": "packages/romdev-m2c"
+ },
+ "homepage": "https://github.com/monteslu/romdev#readme",
+ "bugs": {
+ "url": "https://github.com/monteslu/romdev/issues"
+ },
+ "author": "Luis Montes",
+ "dependencies": {
+ "romdev-pycparser": "0.1.0",
+ "@viz-js/viz": "3.31.0"
+ }
+}
diff --git a/packages/romdev-m2c/scripts/regen-candidates.mjs b/packages/romdev-m2c/scripts/regen-candidates.mjs
new file mode 100644
index 00000000..3e4893b0
--- /dev/null
+++ b/packages/romdev-m2c/scripts/regen-candidates.mjs
@@ -0,0 +1,64 @@
+#!/usr/bin/env node
+// Regenerate recorded m2c candidates (romdev decomp workspaces: candidates//gen-N.{c,json})
+// with the JS port, using the exact args recorded in each sidecar, and compare byte-for-byte.
+// Usage: node scripts/regen-candidates.mjs [--verbose]
+import fs from "node:fs";
+import path from "node:path";
+import { decompile } from "../src/main.js";
+
+const root = process.argv[2];
+const verbose = process.argv.includes("--verbose");
+if (!root) {
+ console.error("usage: regen-candidates.mjs ");
+ process.exit(2);
+}
+
+// Same split as romdevtools src/decomp/m2c.js splitM2cOutput
+function splitM2cOutput(text) {
+ const lines = text.split("\n");
+ const declarations = [];
+ let i = 0;
+ for (; i < lines.length; i++) {
+ const l = lines[i].trim();
+ if (!l) continue;
+ if (/^\?\s+\w+\s*\(.*\)\s*;/.test(l) || /^extern\s+\?/.test(l) || (/^extern\s+[^(]*;$/.test(l) && /\?/.test(l))) {
+ declarations.push(l);
+ continue;
+ }
+ break;
+ }
+ return { declarations, body: lines.slice(i).join("\n") };
+}
+
+const candDir = path.join(root, "candidates");
+let same = 0;
+let differ = 0;
+let skipped = 0;
+const diffs = [];
+for (const fn of fs.readdirSync(candDir).sort()) {
+ const dir = path.join(candDir, fn);
+ for (const f of fs.readdirSync(dir).filter((x) => /^gen-\d+\.json$/.test(x)).sort()) {
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, f), "utf8"));
+ const cfile = path.join(dir, f.replace(/\.json$/, ".c"));
+ const args = (meta.args ?? []).slice(1); // drop m2c.py
+ const missing = args.filter((a, k) => (k === args.length - 1 || args[k - 1] === "--context") && !fs.existsSync(a));
+ if (!fs.existsSync(cfile) || missing.length) {
+ skipped++;
+ if (verbose) console.log(`SKIP ${fn}/${f}: missing ${missing.join(", ") || cfile}`);
+ continue;
+ }
+ const r = await decompile(args);
+ const parsed = splitM2cOutput(r.stdout);
+ const text = parsed.body.trim() + "\n";
+ const expected = fs.readFileSync(cfile, "utf8");
+ const declsOk = JSON.stringify(parsed.declarations) === JSON.stringify(meta.declarations ?? parsed.declarations);
+ if (text === expected && declsOk) same++;
+ else {
+ differ++;
+ diffs.push(`${fn}/${f}${declsOk ? "" : " (declarations)"}`);
+ }
+ }
+}
+console.log(`candidates: ${same} identical, ${differ} different, ${skipped} skipped (inputs gone)`);
+for (const d of diffs) console.log(` DIFF ${d}`);
+process.exit(differ ? 1 : 0);
diff --git a/packages/romdev-m2c/src/arch_arm.js b/packages/romdev-m2c/src/arch_arm.js
new file mode 100644
index 00000000..7fa3e632
--- /dev/null
+++ b/packages/romdev-m2c/src/arch_arm.js
@@ -0,0 +1,1547 @@
+// Port of m2c/arch_arm.py
+import { DecompFailure } from "./error.js";
+import { PyEnum, Target } from "./options.js";
+import { AsmSymbolicData, Label } from "./asm_file.js";
+import {
+ ARM_BARREL_SHIFTER_OPS,
+ AsmAddressMode,
+ AsmGlobalSymbol,
+ AsmInstruction,
+ AsmLiteral,
+ BinOp,
+ JumpTarget,
+ Macro,
+ Register,
+ RegisterList,
+ Writeback,
+ get_jump_target,
+} from "./asm_instruction.js";
+import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js";
+import { Instruction, InstructionMeta } from "./instruction.js";
+import {
+ Abi,
+ AbiArgSlot,
+ AddressMode,
+ ArgLoc,
+ Arch,
+ BinaryOp,
+ CarryBit,
+ ErrorExpr,
+ ExprStmt,
+ Literal,
+ SecondF64Half,
+ UnaryOp,
+ as_type,
+ as_f32,
+ as_f64,
+ format_hex,
+} from "./translate.js";
+import {
+ condition_from_expr,
+ deref,
+ eval_arm_cmp,
+ fn_op,
+ fold_divmod,
+ fold_mul_chains,
+ handle_add_arm,
+ handle_add_double,
+ handle_add_float,
+ handle_add_real,
+ handle_arm_mov,
+ handle_bitinv,
+ handle_convert,
+ handle_la,
+ handle_load,
+ handle_or,
+ handle_shift_right,
+ handle_sll,
+ handle_sub,
+ handle_sub_arm,
+ handle_xor,
+ make_store,
+ make_store_real,
+ replace_bitand,
+ set_arm_flags_from_add,
+} from "./evaluate.js";
+import { Type } from "./types.js";
+import { band, bxor, floordiv, format, has, int_, pyassert, pymod, shr } from "./py.js";
+
+export const SUFFIXABLE_INSTRUCTIONS = new Set([
+ "adc", "adr", "add", "and", "asr", "b", "bic", "bl", "blx", "bx", "cbnz", "cbz", "clz", "cmn", "cmp", "cpy",
+ "eor", "ldm", "ldr", "ldrb", "ldrh", "ldrsb", "ldrsh", "lsl", "lsr", "mla", "mls", "movimm.fictive", "mov",
+ "mul", "mvn", "neg", "nop", "orn", "orr", "pop", "push", "rbit", "rev", "rev16", "revsh", "ror", "rrx", "rsb",
+ "rsc", "sbc", "sdiv", "smlabb", "smlal", "smmla", "smmls", "smmul", "smulbb", "smull", "stm", "str", "strb",
+ "strh", "sub", "tablejmp.fictive", "teq", "tst", "udiv", "umlal", "umull", "vldm", "vldr", "vstm", "vstr",
+]);
+
+export const LENGTH_THREE = new Set(["adc", "add", "and", "asr", "bic", "eor", "lsl", "lsr", "mul", "orn", "orr", "ror", "rsb", "rsc", "sbc", "sub"]);
+
+export const THUMB1_FLAG_SETTING = new Set(["adc", "add", "and", "asr", "bic", "eor", "lsl", "lsr", "mov", "mul", "mvn", "neg", "orr", "ror", "sbc", "sub"]);
+
+export const MAGIC_FUNCTIONS = {
+ __divsi3: ["sdiv", "001"],
+ _idiv: ["sdiv", "001"],
+ __udivsi3: ["udiv", "001"],
+ _uidiv: ["udiv", "001"],
+ __modsi3: ["smod.fictive", "001"],
+ __umodsi3: ["umod.fictive", "001"],
+ _s32_div_f: ["sdivmod.fictive", "01"],
+ _idivmod: ["sdivmod.fictive", "01"],
+ _u32_div_f: ["udivmod.fictive", "01"],
+ _uidivmod: ["udivmod.fictive", "01"],
+ __clzsi2: ["clz", "00"],
+ // Soft float emulation from fplib
+ _fadd: ["add.s.fictive", "001"],
+ _fsub: ["sub.s.fictive", "001"],
+ _frsub: ["sub.s.fictive", "010"],
+ _fmul: ["mul.s.fictive", "001"],
+ _fdiv: ["div.s.fictive", "001"],
+ _frdiv: ["div.s.fictive", "010"],
+ _fsqrt: ["sqrt.s.fictive", "00"],
+ _frnd: ["round.s.fictive", "00"],
+ _fflt: ["cvt.s.w.fictive", "00"],
+ _ffltu: ["cvt.s.u.fictive", "00"],
+ _ffix: ["cvt.w.s.fictive", "00"],
+ _ffixu: ["cvt.u.s.fictive", "00"],
+ _f2d: ["cvt.d.s.fictive", "00"],
+ _fls: ["c.lt.s.fictive", "01"],
+ _fgr: ["c.gt.s.fictive", "01"],
+ _fleq: ["c.le.s.fictive", "01"],
+ _fgeq: ["c.ge.s.fictive", "01"],
+ _feq: ["c.eq.s.fictive", "01"],
+ _fneq: ["c.neq.s.fictive", "01"],
+ _dadd: ["add.d.fictive", "002"],
+ _dsub: ["sub.d.fictive", "002"],
+ _drsub: ["sub.d.fictive", "020"],
+ _dmul: ["mul.d.fictive", "002"],
+ _ddiv: ["div.d.fictive", "002"],
+ _drdiv: ["div.d.fictive", "020"],
+ _dsqrt: ["sqrt.d.fictive", "00"],
+ _drnd: ["round.d.fictive", "00"],
+ _dflt: ["cvt.d.w.fictive", "00"],
+ _dfltu: ["cvt.d.u.fictive", "00"],
+ _dfix: ["cvt.w.d.fictive", "00"],
+ _dfixu: ["cvt.u.d.fictive", "00"],
+ _d2f: ["cvt.s.d.fictive", "00"],
+ _dls: ["c.lt.d.fictive", "02"],
+ _dgr: ["c.gt.d.fictive", "02"],
+ _dleq: ["c.le.d.fictive", "02"],
+ _dgeq: ["c.ge.d.fictive", "02"],
+ _deq: ["c.eq.d.fictive", "02"],
+ _dneq: ["c.neq.d.fictive", "02"],
+};
+
+const HI_REGS = new Set(["r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc"].map((r) => new Register(r)));
+
+export class Cc extends PyEnum {}
+PyEnum.define(Cc, {
+ EQ: "eq",
+ NE: "ne",
+ CS: "cs",
+ CC: "cc",
+ MI: "mi",
+ PL: "pl",
+ VS: "vs",
+ VC: "vc",
+ HI: "hi",
+ LS: "ls",
+ GE: "ge",
+ LT: "lt",
+ GT: "gt",
+ LE: "le",
+ AL: "al",
+});
+
+export const CC_REGS = new Map([
+ [Cc.EQ, new Register("z")],
+ [Cc.CS, new Register("c")],
+ [Cc.MI, new Register("n")],
+ [Cc.VS, new Register("v")],
+ [Cc.HI, new Register("hi")],
+ [Cc.GE, new Register("ge")],
+ [Cc.GT, new Register("gt")],
+]);
+
+function cc_reg(cc) {
+ const r = CC_REGS.get(cc);
+ if (r === undefined) throw new Error(`KeyError: ${cc}`);
+ return r;
+}
+
+const NEGATE = new Map([
+ [Cc.EQ, Cc.NE],
+ [Cc.NE, Cc.EQ],
+ [Cc.CS, Cc.CC],
+ [Cc.CC, Cc.CS],
+ [Cc.MI, Cc.PL],
+ [Cc.PL, Cc.MI],
+ [Cc.VS, Cc.VC],
+ [Cc.VC, Cc.VS],
+ [Cc.HI, Cc.LS],
+ [Cc.LS, Cc.HI],
+ [Cc.GE, Cc.LT],
+ [Cc.LT, Cc.GE],
+ [Cc.GT, Cc.LE],
+ [Cc.LE, Cc.GT],
+]);
+
+export function negate_cond(cc) {
+ const r = NEGATE.get(cc);
+ if (r === undefined) throw new Error(`KeyError: ${cc}`);
+ return r;
+}
+
+const FACTOR = new Map([
+ [Cc.EQ, [Cc.EQ, false]],
+ [Cc.NE, [Cc.EQ, true]],
+ [Cc.CS, [Cc.CS, false]],
+ [Cc.CC, [Cc.CS, true]],
+ [Cc.MI, [Cc.MI, false]],
+ [Cc.PL, [Cc.MI, true]],
+ [Cc.VS, [Cc.VS, false]],
+ [Cc.VC, [Cc.VS, true]],
+ [Cc.HI, [Cc.HI, false]],
+ [Cc.LS, [Cc.HI, true]],
+ [Cc.GE, [Cc.GE, false]],
+ [Cc.LT, [Cc.GE, true]],
+ [Cc.GT, [Cc.GT, false]],
+ [Cc.LE, [Cc.GT, true]],
+]);
+
+export function factor_cond(cc) {
+ const r = FACTOR.get(cc);
+ if (r === undefined) throw new Error(`KeyError: ${cc}`);
+ return r;
+}
+
+/** Returns [mnemonic, cc|null, set_flags, direction]. */
+export function parse_suffix(mnemonic) {
+ const ldm = mnemonic.startsWith("ldm") || mnemonic.startsWith("vldm");
+ const stm = mnemonic.startsWith("stm") || mnemonic.startsWith("vstm");
+
+ const strip_cc = (mn) => {
+ for (const suffix of [...Cc.members.map((c) => c.value), "hs", "lo"]) {
+ if (mn.endsWith(suffix)) {
+ let cc;
+ if (suffix === "hs") cc = Cc.CS;
+ else if (suffix === "lo") cc = Cc.CC;
+ else cc = Cc.of(suffix);
+ return [mn.slice(0, -suffix.length), cc];
+ }
+ }
+ return [mn, null];
+ };
+
+ const strip_dir = (mn) => {
+ if (!ldm && !stm) return [mn, ""];
+ if (["ia", "ib", "da", "db"].some((s) => mn.endsWith(s))) return [mn.slice(0, -2), mn.slice(-2)];
+ if (["fa", "ea", "fd", "ed"].some((s) => mn.endsWith(s))) {
+ const tr = { fa: ["da", "ib"], ea: ["db", "ia"], fd: ["ia", "db"], ed: ["ib", "da"] };
+ return [mn.slice(0, -2), tr[mn.slice(-2)][ldm ? 0 : 1]];
+ }
+ return [mn, ""];
+ };
+
+ // bls should be parsed as b + ls, not bl + s
+ let s_ok = !mnemonic.startsWith("b") || mnemonic.startsWith("bic");
+
+ let memsize = "";
+ if (mnemonic.startsWith("str") || mnemonic.startsWith("ldr")) {
+ // ldrhs should be parsed as ldr + hs, not ldrh + s
+ s_ok = false;
+ for (const suffix of ["b", "h", "d"]) {
+ if (mnemonic.endsWith(suffix)) {
+ mnemonic = mnemonic.slice(0, -1);
+ memsize = suffix;
+ break;
+ }
+ }
+ if ((memsize === "b" || memsize === "h") && mnemonic.endsWith("s") && (!strip_cc(mnemonic)[1] || strip_cc(mnemonic.slice(0, -1))[1])) {
+ mnemonic = mnemonic.slice(0, -1);
+ memsize = "s" + memsize;
+ }
+ }
+
+ const orig_mn = mnemonic;
+ for (const cc_is_last of [false, true]) {
+ let direction;
+ [mnemonic, direction] = strip_dir(orig_mn);
+ let cc = null;
+ let set_flags = "";
+ if (cc_is_last) {
+ [mnemonic, cc] = strip_cc(mnemonic);
+ if (!direction) [mnemonic, direction] = strip_dir(mnemonic);
+ }
+ if (SUFFIXABLE_INSTRUCTIONS.has(mnemonic)) return [mnemonic + memsize, cc, set_flags, direction];
+ if (mnemonic.endsWith("s") && s_ok) {
+ set_flags = "s";
+ mnemonic = mnemonic.slice(0, -1);
+ if (SUFFIXABLE_INSTRUCTIONS.has(mnemonic)) return [mnemonic + memsize, cc, set_flags, direction];
+ }
+ if (!cc_is_last) {
+ [mnemonic, cc] = strip_cc(mnemonic);
+ if (SUFFIXABLE_INSTRUCTIONS.has(mnemonic)) return [mnemonic + memsize, cc, set_flags, direction];
+ }
+ }
+ return [orig_mn + memsize, null, "", ""];
+}
+
+export function get_ldm_stm_offset(i, num_regs, direction) {
+ if (direction === "ia") return 4 * i;
+ if (direction === "ib") return 4 * (i + 1);
+ if (direction === "da") return 4 * (i + 1 - num_regs);
+ if (direction === "db") return 4 * (i - num_regs);
+ pyassert(false, `bad ldm/stm direction ${direction}`);
+}
+
+export function other_f64_reg(reg) {
+ const num = int_(reg.register_name.slice(1));
+ return new Register(`r${num ^ 1}`);
+}
+
+export function vreg_type(reg) {
+ const [tp] = reg.arm_regtype_index();
+ if (tp === "s") return Type.reg32({ likely_float: true });
+ else if (tp === "d") return Type.reg64({ likely_float: true });
+ else if (tp === "q") return Type.reg128();
+ pyassert(false, `invalid vldr target ${reg}`);
+}
+
+/** Detect switch jumps of the form "add pc, pc, reg, lsl 2". */
+export class AddPcPcPattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction) || !instr.mnemonic.startsWith("add")) return null;
+ const [base, cc, set_flags] = parse_suffix(instr.mnemonic);
+ if (
+ base !== "add" ||
+ set_flags ||
+ instr.args[0] !== new Register("pc") ||
+ instr.args[1] !== new Register("pc") ||
+ !(instr.args[2] instanceof BinOp) ||
+ instr.args[2].op !== "lsl" ||
+ instr.args[2].rhs !== new AsmLiteral(2)
+ ) {
+ return null;
+ }
+ let i = matcher.index + 1;
+ let seen_first = false;
+ const new_args = [instr.args[2].lhs];
+ while (i < matcher.input.length) {
+ const ins2 = matcher.input[i];
+ i += 1;
+ if (ins2 instanceof Label) continue;
+ if (!seen_first) {
+ seen_first = true;
+ continue;
+ }
+ if (ins2.mnemonic === "pop" && ins2.args[0] instanceof RegisterList && ins2.args[0].regs.includes(new Register("pc"))) {
+ new_args.push(new AsmGlobalSymbol("_m2c_ret"));
+ } else if (ins2.mnemonic === "b") {
+ pyassert(ins2.args[0] instanceof AsmGlobalSymbol);
+ new_args.push(ins2.args[0]);
+ } else break;
+ }
+ const cc_str = cc !== null ? cc.value : "";
+ const jump_ins = new AsmInstruction("tablejmp.fictive" + cc_str, new_args);
+ return new Replacement([jump_ins], 1);
+ }
+}
+
+/** Detect switch jumps emitted by MWCC for Thumb. */
+export class ShortJumpTablePattern extends AsmPattern {
+ pattern = make_pattern("adds $x, $x, $x", "add $x, $x, $pc", "ldrh $x, [$x, 6]", "movs $x, $x, lsl 0x10", "movs $x, $x, asr 0x10", "add $pc, $pc, $x", ".label:");
+
+ match(matcher) {
+ const m = matcher.try_match(this.pattern);
+ if (!m) return null;
+ const label = m.labels.get(".label").names[0];
+ const ent = matcher.asm_data.values.get(label) ?? null;
+ if (ent === null) return null;
+ const new_args = [m.regs.get("x")];
+ for (const data of ent.data) {
+ if (
+ !(data instanceof AsmSymbolicData) ||
+ !(data.data instanceof BinOp) ||
+ data.data.rhs !== new AsmLiteral(2) ||
+ !(data.data.lhs instanceof BinOp) ||
+ data.data.lhs.rhs !== new AsmGlobalSymbol(label)
+ ) {
+ break;
+ }
+ new_args.push(data.data.lhs.lhs);
+ }
+ const jump_ins = new AsmInstruction("tablejmp.fictive", new_args);
+ return new Replacement([jump_ins], this.pattern.length - 1);
+ }
+}
+
+function intersects(a, setb) {
+ for (const x of a) if (setb.has(x)) return true;
+ return false;
+}
+
+export class InstructionEffects {
+ constructor() {
+ this.inputs = new Set();
+ this.outputs = new Set();
+ this.is_effectful = false;
+ this.has_load = false;
+ }
+ can_move_before(instr) {
+ const outputs = [...instr.outputs, ...instr.clobbers];
+ if (intersects([...instr.inputs, ...outputs], this.outputs)) return false;
+ if (intersects(outputs, this.inputs)) return false;
+ if (this.is_effectful && (instr.is_effectful || instr.is_load)) return false;
+ if (this.has_load && instr.is_effectful) return false;
+ return true;
+ }
+ add(instr) {
+ for (const x of [...instr.outputs, ...instr.clobbers]) this.outputs.add(x);
+ for (const x of instr.inputs) this.inputs.add(x);
+ if (instr.is_effectful) this.is_effectful = true;
+ if (instr.is_load) this.has_load = true;
+ }
+}
+
+/** Replace conditionally executed instructions by branches. */
+export class ConditionalInstrPattern extends AsmPattern {
+ match(matcher) {
+ let matched_cc = null;
+ let i = 0;
+ const if_instrs = [];
+ const else_instrs = [];
+ const before_instrs = [];
+ const after_instrs = [];
+ const mid_set = new InstructionEffects();
+ const after_set = new InstructionEffects();
+ let moved_before_streak = 0;
+ let moved_after_streak = 0;
+ const label1 = `._m2c_cc_${matcher.index}`;
+ const label2 = `._m2c_cc2_${matcher.index}`;
+ let flag_check = null;
+ while (matcher.index + i < matcher.input.length) {
+ const instr = matcher.input[matcher.index + i];
+ if (!(instr instanceof Instruction)) break;
+ const [base, cc, set_flags, direction] = parse_suffix(instr.mnemonic);
+ if (cc === null) {
+ if (matched_cc === null) return null;
+ if (instr.is_jump()) break;
+ if (mid_set.can_move_before(instr) && !after_instrs.length) {
+ before_instrs.push(instr);
+ moved_before_streak += 1;
+ } else {
+ after_set.add(instr);
+ after_instrs.push(instr);
+ moved_after_streak += 1;
+ }
+ i += 1;
+ continue;
+ }
+ const outputs = [...instr.outputs, ...instr.clobbers];
+ if (!after_set.can_move_before(instr)) break;
+ if (after_instrs.length && instr.is_jump()) break;
+ mid_set.add(instr);
+ const new_instr = new AsmInstruction(base + set_flags + direction, instr.args);
+ if (matched_cc === null) {
+ if (base === "b") break;
+ matched_cc = cc;
+ }
+ if (cc !== matched_cc && cc !== negate_cond(matched_cc)) break;
+ if (flag_check !== null) if_instrs.push(flag_check);
+ flag_check = null;
+ if (matched_cc === cc) if_instrs.push(new_instr);
+ else else_instrs.push(new_instr);
+ i += 1;
+ moved_before_streak = 0;
+ moved_after_streak = 0;
+ if (instr.is_jump()) break;
+ if (outputs.includes(cc_reg(factor_cond(matched_cc)[0]))) {
+ if (matched_cc === cc && !else_instrs.length) {
+ const b_mn = "b" + negate_cond(matched_cc).value;
+ flag_check = new AsmInstruction(b_mn, [new AsmGlobalSymbol(label1)]);
+ } else break;
+ }
+ }
+ if (matched_cc === null) return null;
+
+ i -= moved_before_streak + moved_after_streak;
+ before_instrs.splice(before_instrs.length - moved_before_streak);
+ after_instrs.splice(after_instrs.length - moved_after_streak);
+
+ const b_mn = "b" + negate_cond(matched_cc).value;
+ if (else_instrs.length) {
+ return new Replacement(
+ [
+ ...before_instrs,
+ new AsmInstruction(b_mn, [new AsmGlobalSymbol(label1)]),
+ ...if_instrs,
+ new AsmInstruction("b", [new AsmGlobalSymbol(label2)]),
+ Label.new(label1),
+ ...else_instrs,
+ Label.new(label2),
+ ...after_instrs,
+ ],
+ i,
+ );
+ }
+ return new Replacement([...before_instrs, new AsmInstruction(b_mn, [new AsmGlobalSymbol(label1)]), ...if_instrs, Label.new(label1), ...after_instrs], i);
+ }
+}
+
+/** Replace negated registers in address modes by neg instructions. */
+export class NegatedRegAddrModePattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction)) return null;
+ if (!instr.args.length || !(instr.args[instr.args.length - 1] instanceof AsmAddressMode)) return null;
+ const last = instr.args[instr.args.length - 1];
+ const addend = last.addend;
+ const inner = addend instanceof BinOp && addend.op !== "-" ? addend.lhs : addend;
+ if (!(inner instanceof BinOp) || inner.op !== "-") return null;
+ const temp = Register.fictive("neg");
+ let new_addend;
+ if (addend instanceof BinOp && addend.op !== "-") new_addend = new BinOp(addend.op, temp, addend.rhs);
+ else new_addend = temp;
+ const new_args = [...instr.args];
+ new_args[new_args.length - 1] = new AsmAddressMode(last.base, new_addend, last.writeback);
+ return new Replacement([new AsmInstruction("rsb", [temp, inner.rhs, new AsmLiteral(0)]), new AsmInstruction(instr.mnemonic, new_args)], 1);
+ }
+}
+
+/** Replace barrel shifted registers in address modes by additional instructions. */
+export class ShiftedRegAddrModePattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction)) return null;
+ if (!instr.args.length || !(instr.args[instr.args.length - 1] instanceof AsmAddressMode)) return null;
+ const last = instr.args[instr.args.length - 1];
+ const addend = last.addend;
+ if (!(addend instanceof BinOp) || !ARM_BARREL_SHIFTER_OPS.includes(addend.op)) return null;
+ const temp = Register.fictive(addend.op);
+ const new_args = [...instr.args];
+ new_args[new_args.length - 1] = new AsmAddressMode(last.base, temp, last.writeback);
+ return new Replacement([new AsmInstruction("mov", [temp, addend]), new AsmInstruction(instr.mnemonic, new_args)], 1);
+ }
+}
+
+/** Replace writebacks in address modes by additional instructions. */
+export class AddrModeWritebackPattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction) || !instr.args.length) return null;
+ const addr = instr.args[instr.args.length - 1];
+ if (!(addr instanceof AsmAddressMode) || addr.writeback === null) return null;
+ const new_args = [...instr.args];
+ new_args[new_args.length - 1] = new AsmAddressMode(addr.base, new AsmLiteral(0), null);
+ if (instr.args[0] === addr.base) {
+ throw new DecompFailure("Writeback of same register as is being loaded/stored, " + `for instruction: ${instr}`);
+ }
+ if (addr.writeback === Writeback.PRE) {
+ return new Replacement([new AsmInstruction("add", [addr.base, addr.base, addr.addend]), new AsmInstruction(instr.mnemonic, new_args)], 1);
+ }
+ return new Replacement([new AsmInstruction(instr.mnemonic, new_args), new AsmInstruction("add", [addr.base, addr.base, addr.addend])], 1);
+ }
+}
+
+/** Replace register addends in address modes by a separate add instruction. */
+export class RegRegAddrModePattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction) || !instr.args.length) return null;
+ const arg = instr.args[instr.args.length - 1];
+ if (!(arg instanceof AsmAddressMode) || !(arg.addend instanceof Register)) return null;
+ pyassert(arg.writeback === null);
+ const temp = Register.fictive("mem_loc");
+ const new_args = [...instr.args];
+ new_args[new_args.length - 1] = new AsmAddressMode(temp, new AsmLiteral(0), null);
+ return new Replacement([new AsmInstruction("add", [temp, arg.base, arg.addend]), new AsmInstruction(instr.mnemonic, new_args)], 1);
+ }
+}
+
+/** Replace barrel shifted registers by additional instructions. */
+export class ShiftedRegPattern extends AsmPattern {
+ static _sets_flags(base, set_flags) {
+ return Boolean(base === "tst" || base === "teq" || (["mov", "mvn", "and", "eor", "orr", "orn", "bic"].includes(base) && set_flags));
+ }
+
+ static _get_literal_carry(base, arg) {
+ if (!(arg instanceof AsmLiteral)) return null;
+ // Carry = bit 31 if the constant is greater than 255 and can be
+ // produced by shifting an 8-bit value
+ let value = band(arg.value, 0xffffffff);
+ if (value >= 0x100 && value < band(value, -value) * 0x100) return shr(value, 31);
+ if (base === "mov" || base === "mvn") value = bxor(value, 0xffffffff);
+ if (value >= 0x100 && value < band(value, -value) * 0x100) return shr(value, 31);
+ return null;
+ }
+
+ static sets_flags_based_on_barrel_shifter(base, set_flags, args) {
+ if (!args.length) return false;
+ const arg = args[args.length - 1];
+ return (
+ ShiftedRegPattern._sets_flags(base, set_flags) &&
+ (ShiftedRegPattern._get_literal_carry(base, arg) !== null || (arg instanceof BinOp && ARM_BARREL_SHIFTER_OPS.includes(arg.op)))
+ );
+ }
+
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction) || !instr.args.length) return null;
+ const [base, , set_flags] = parse_suffix(instr.mnemonic);
+ const arg = instr.args[instr.args.length - 1];
+
+ const literal_carry = ShiftedRegPattern._get_literal_carry(base, arg);
+ if (literal_carry !== null) {
+ if (!ShiftedRegPattern._sets_flags(base, set_flags)) return null;
+ return new Replacement([instr, new AsmInstruction("setcarryi.fictive", [new AsmLiteral(literal_carry)])], 1);
+ }
+
+ if (!(arg instanceof BinOp) || !ARM_BARREL_SHIFTER_OPS.includes(arg.op)) return null;
+
+ const temp = Register.fictive(arg.op);
+ // (upstream builds the 3-arg form and pops the last arg for rrx; AsmInstruction
+ // is interned here, so build the final arg list directly)
+ const shift_args = arg.op === "rrx" ? [temp, arg.lhs] : [temp, arg.lhs, arg.rhs];
+ const shift_ins = new AsmInstruction(arg.op, shift_args);
+ const new_instrs = [shift_ins, new AsmInstruction(instr.mnemonic, [...instr.args.slice(0, -1), temp])];
+ if (ShiftedRegPattern._sets_flags(base, set_flags)) new_instrs.push(new AsmInstruction("setcarry.fictive", [temp]));
+ return new Replacement(new_instrs, 1);
+ }
+}
+
+export class PopAndReturnPattern extends SimpleAsmPattern {
+ pattern = make_pattern("pop {x}", "add $sp, $sp, N?", "bx $x");
+ replace(m) {
+ return new Replacement([new AsmInstruction("bx", [new Register("lr")])], m.body.length);
+ }
+}
+
+export class OldThumbBlxPattern extends SimpleAsmPattern {
+ pattern = make_pattern("mov $lr, $pc", "bx $x");
+ replace(m) {
+ return new Replacement([new AsmInstruction("blx", [m.regs.get("x")])], m.body.length);
+ }
+}
+
+export class IndirectTailCallPattern extends SimpleAsmPattern {
+ pattern = make_pattern("bx $x");
+ replace(m) {
+ if (m.regs.get("x") === new Register("lr")) return null;
+ return new Replacement([new AsmInstruction("blx", [m.regs.get("x")]), new AsmInstruction("bx", [new Register("lr")])], m.body.length);
+ }
+}
+
+/** `return fn(...);` may be optimized to perform a `b fn` instead of `bl fn; bx lr`. */
+export class TailCallPattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (instr instanceof Instruction && instr.mnemonic === "b" && instr.args[0] instanceof AsmGlobalSymbol && !matcher.is_local_label(instr.args[0].symbol_name)) {
+ return new Replacement([new AsmInstruction("bl", instr.args), new AsmInstruction("bx", [new Register("lr")])], 1);
+ }
+ return null;
+ }
+}
+
+/** Replace bl by b when used for intra-function jumps. */
+export class BlBranchPattern extends AsmPattern {
+ match(matcher) {
+ const is_local_bl = (instr) => instr.mnemonic === "bl" && instr.args[0] instanceof AsmGlobalSymbol && matcher.is_local_label(instr.args[0].symbol_name);
+
+ const instr = matcher.input[matcher.index];
+ if (instr instanceof Instruction && is_local_bl(instr)) {
+ return new Replacement([new AsmInstruction("b", instr.args)], 1, [new Register("lr")]);
+ }
+
+ if (matcher.index + 2 >= matcher.input.length) return null;
+ const instr2 = matcher.input[matcher.index + 1];
+ const label = matcher.input[matcher.index + 2];
+ if (
+ instr instanceof Instruction &&
+ instr2 instanceof Instruction &&
+ label instanceof Label &&
+ is_local_bl(instr2) &&
+ instr.jump_target instanceof JumpTarget &&
+ label.names.includes(instr.jump_target.target) &&
+ instr.is_conditional
+ ) {
+ const [base, cc] = parse_suffix(instr.mnemonic);
+ if (base === "b" && cc !== null) {
+ const b_mn = "b" + negate_cond(cc).value;
+ return new Replacement([new AsmInstruction(b_mn, instr2.args)], 2, [new Register("lr")]);
+ }
+ }
+ return null;
+ }
+}
+
+export class MagicFuncPattern extends SimpleAsmPattern {
+ pattern = make_pattern("bl");
+ replace(m) {
+ const ins = m.body[0];
+ pyassert(ins instanceof Instruction);
+ pyassert(ins.args[0] instanceof AsmGlobalSymbol);
+ let target = ins.args[0].symbol_name;
+ if (target.startsWith("_call_via_")) {
+ const reg_name = target.slice(10);
+ let reg = has(ArmArch.prototype.aliased_regs, reg_name) ? ArmArch.prototype.aliased_regs[reg_name] : null;
+ if (reg === null && ArmArch.prototype.all_regs.includes(new Register(reg_name))) reg = new Register(reg_name);
+ if (reg !== null) return new Replacement([new AsmInstruction("blx", [reg])], 1);
+ }
+ if (target.startsWith("__aeabi_")) target = target.slice(7);
+ if (has(MAGIC_FUNCTIONS, target)) {
+ const [mn, arg_str] = MAGIC_FUNCTIONS[target];
+ const args = [...arg_str].map((x) => new Register("r" + x));
+ return new Replacement([new AsmInstruction(mn, args)], 1, []);
+ }
+ return null;
+ }
+}
+
+export class ArmArch extends Arch {
+ missing_return() {
+ return [this.parse("bx", [new Register("lr")], InstructionMeta.missing())];
+ }
+
+ normalize_instruction(instr, asm_state) {
+ if (instr.mnemonic.endsWith(".n") || instr.mnemonic.endsWith(".w")) instr = new AsmInstruction(instr.mnemonic.slice(0, -2), instr.args);
+ if (asm_state.is_thumb && !asm_state.is_unified) {
+ if (instr.mnemonic.length > 3 && instr.mnemonic.endsWith("s")) {
+ throw new DecompFailure("Missing '.syntax unified' marker");
+ }
+ if (THUMB1_FLAG_SETTING.has(instr.mnemonic) && instr.args.every((arg) => !HI_REGS.has(arg))) {
+ instr = new AsmInstruction(instr.mnemonic + "s", instr.args);
+ }
+ }
+ return this.normalize_instruction_real(instr);
+ }
+
+ normalize_instruction_real(instr) {
+ let [base, cc, set_flags, direction] = parse_suffix(instr.mnemonic);
+ if (cc === Cc.AL) {
+ cc = null;
+ instr = new AsmInstruction(base + set_flags + direction, instr.args);
+ }
+ const cc_str = cc ? cc.value : "";
+ const suffix = cc_str + set_flags + direction;
+ const args = instr.args;
+ if (args.length === 3) {
+ if (base === "lsl" && args[2] === new AsmLiteral(0)) return new AsmInstruction("mov" + suffix, args.slice(0, 2));
+ if (base === "add" && !set_flags && args[2] === new AsmLiteral(0)) return new AsmInstruction("mov" + suffix, args.slice(0, 2));
+ if (["asr", "lsl", "lsr", "ror"].includes(base)) return new AsmInstruction("mov" + suffix, [args[0], new BinOp(base, args[1], args[2])]);
+ }
+ if (args.length === 2) {
+ if (instr.mnemonic === "mov" && args[0] === args[1] && args[1] === new Register("r8")) return new AsmInstruction("nop", []);
+ if (
+ base === "ldr" &&
+ args[0] instanceof Register &&
+ args[1] instanceof AsmAddressMode &&
+ args[1].base === new Register("sp") &&
+ args[1].addend === new AsmLiteral(4) &&
+ args[1].writeback === Writeback.POST
+ ) {
+ return new AsmInstruction("pop" + suffix, [new RegisterList([args[0]])]);
+ }
+ if (base === "ldr" && args[1] instanceof Macro && args[1].macro_name === "eqsign") {
+ const mn = args[1].argument instanceof AsmLiteral ? "movimm.fictive" : "adr";
+ return new AsmInstruction(mn + suffix, [args[0], args[1].argument]);
+ }
+ if (
+ base === "str" &&
+ args[0] instanceof Register &&
+ args[1] instanceof AsmAddressMode &&
+ args[1].base === new Register("sp") &&
+ args[1].addend === new AsmLiteral(-4) &&
+ args[1].writeback === Writeback.PRE
+ ) {
+ return new AsmInstruction("push" + suffix, [new RegisterList([args[0]])]);
+ }
+ if (base === "cpy") return new AsmInstruction("mov" + suffix, args);
+ if (base === "neg") return new AsmInstruction("rsb" + suffix, [...args, new AsmLiteral(0)]);
+ if (base === "rrx") return new AsmInstruction("mov" + suffix, [args[0], new BinOp(base, args[1], new AsmLiteral(1))]);
+ if (["stm", "ldm", "vstm", "vldm"].includes(base) && !direction) return this.normalize_instruction_real(new AsmInstruction(instr.mnemonic + "ia", args));
+ const sp_excl = new AsmAddressMode(new Register("sp"), new AsmLiteral(0), Writeback.PRE);
+ if ((base === "stm" || base === "vstm") && direction === "db" && args[0] === sp_excl) {
+ const v = base === "vstm" ? "v" : "";
+ return new AsmInstruction(v + "push" + cc_str, [args[1]]);
+ }
+ if ((base === "ldm" || base === "vldm") && direction === "ia" && args[0] === sp_excl) {
+ const v = base === "vldm" ? "v" : "";
+ return new AsmInstruction(v + "pop" + cc_str, [args[1]]);
+ }
+ if (LENGTH_THREE.has(base)) return this.normalize_instruction_real(new AsmInstruction(instr.mnemonic, [args[0], ...args]));
+ }
+ if (instr.mnemonic.startsWith("it")) return new AsmInstruction("nop", []);
+ return instr;
+ }
+
+ parse(mnemonic, args, meta) {
+ const cls = this;
+ let inputs = [];
+ let clobbers = [];
+ let outputs = [];
+ let jump_target = null;
+ let function_target = null;
+ let is_conditional = false;
+ let is_return = false;
+ let is_load = false;
+ let is_store = false;
+ let is_effectful = true;
+ let eval_fn = null;
+
+ const instr_str = String(new AsmInstruction(mnemonic, args));
+
+ let [base, cc, set_flags, direction] = parse_suffix(mnemonic);
+ let cc_negated;
+ if (cc !== null) [cc, cc_negated] = factor_cond(cc);
+ else cc_negated = false;
+
+ const get_inputs = (starti) => {
+ const ret = [];
+ for (let arg of args.slice(starti)) {
+ if (arg instanceof AsmAddressMode) {
+ ret.push(arg.base);
+ arg = arg.addend;
+ }
+ if (arg instanceof BinOp) {
+ if (arg.rhs instanceof Register) ret.push(arg.rhs);
+ arg = arg.lhs;
+ }
+ if (arg instanceof BinOp && arg.op === "-" && arg.lhs === new AsmLiteral(0)) arg = arg.rhs;
+ if (arg instanceof Register) ret.push(arg);
+ }
+ return ret;
+ };
+
+ if (base === "b") {
+ pyassert(args.length === 1);
+ jump_target = get_jump_target(args[0]);
+ if (cc !== null) {
+ is_conditional = true;
+ eval_fn = (s, a) => {
+ let cond = condition_from_expr(a.regs.get(cc_reg(cc)));
+ if (cc_negated) cond = cond.negated();
+ s.set_branch_condition(cond);
+ };
+ }
+ } else if (base === "cbz" || base === "cbnz") {
+ pyassert(args.length === 2);
+ pyassert(args[0] instanceof Register);
+ inputs = [args[0]];
+ jump_target = get_jump_target(args[1]);
+ is_conditional = true;
+ eval_fn = (s, a) => {
+ const op = base === "cbz" ? "==" : "!=";
+ s.set_branch_condition(BinaryOp.icmp(a.reg(0), op, new Literal(0)));
+ };
+ } else if (base === "bx" && args[0] === new Register("lr")) {
+ pyassert(args.length === 1);
+ inputs = [new Register("lr")];
+ is_return = true;
+ } else if (base === "pop") {
+ pyassert(args.length === 1);
+ pyassert(args[0] instanceof RegisterList);
+ outputs = [...args[0].regs];
+ if (args[0].regs.includes(new Register("pc"))) is_return = true;
+ } else if (base === "blx" && args[0] instanceof Register) {
+ inputs = [...cls.argument_regs];
+ inputs.push(args[0]);
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = args[0];
+ eval_fn = (s, a) => s.make_function_call(a.reg(0), outputs);
+ } else if (base === "bl" || base === "blx") {
+ pyassert(args.length === 1);
+ inputs = [...cls.argument_regs];
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = args[0];
+ eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs);
+ } else if (base === "ldr" && args[0] === new Register("pc")) {
+ pyassert(!set_flags);
+ inputs = get_inputs(1);
+ outputs = [...cls.all_return_regs];
+ is_return = true;
+ function_target = args[1];
+ eval_fn = (s, a) => {
+ const target = handle_load(a, Type.reg32({ likely_float: false }));
+ s.make_function_call(target, outputs);
+ };
+ } else if (base === "tablejmp.fictive") {
+ pyassert(args.length >= 1 && args[0] instanceof Register);
+ const targets = [];
+ for (const arg of args.slice(1)) {
+ pyassert(arg instanceof AsmGlobalSymbol);
+ targets.push(new JumpTarget(arg.symbol_name));
+ }
+ inputs = [args[0]];
+ jump_target = targets;
+ is_conditional = true;
+ eval_fn = (s, a) => s.set_switch_expr(a.reg(0), true);
+ } else if (has(cls.instrs_no_flags, base)) {
+ pyassert(!set_flags);
+ pyassert(args[0] instanceof Register);
+ outputs = [args[0]];
+ inputs = get_inputs(1);
+ is_effectful = false;
+ is_load = base.startsWith("ldr") || base === "vldr";
+
+ if (base.startsWith("cvt.")) {
+ pyassert(args.length === 2 && args[1] instanceof Register);
+ const mn_parts = base.split(".");
+ if (mn_parts[1] === "d") outputs.push(other_f64_reg(args[0]));
+ if (mn_parts[2] === "d") inputs.push(other_f64_reg(args[1]));
+ } else if (base.endsWith(".d.fictive")) {
+ for (const reg of args.slice(1)) {
+ pyassert(reg instanceof Register);
+ inputs.push(reg, other_f64_reg(reg));
+ }
+ outputs.push(other_f64_reg(args[0]));
+ }
+
+ eval_fn = (s, a) => {
+ const target = a.reg_ref(0);
+ s.set_reg(target, cls.instrs_no_flags[base](a));
+ if (outputs.length === 2) s.set_reg(other_f64_reg(target), new SecondF64Half());
+ };
+ } else if (has(cls.instrs_divmod, base)) {
+ pyassert(!set_flags);
+ outputs = [new Register("r0"), new Register("r1")];
+ inputs = get_inputs(0);
+ is_effectful = false;
+ eval_fn = (s, a) => {
+ const [div, mod] = cls.instrs_divmod[base](a);
+ s.set_reg_real(new Register("r0"), div, { function_return: true });
+ s.set_reg_real(new Register("r1"), mod, { function_return: true });
+ };
+ } else if (base === "ldm") {
+ pyassert(!set_flags);
+ pyassert(["ia", "ib", "da", "db"].includes(direction));
+ pyassert(args[1] instanceof RegisterList);
+ const reg_list = args[1];
+ outputs = [...args[1].regs];
+ let writeback = false;
+ let base_reg;
+ if (args[0] instanceof Register) base_reg = args[0];
+ else {
+ pyassert(args[0] instanceof AsmAddressMode);
+ pyassert(args[0].addend === new AsmLiteral(0));
+ pyassert(args[0].writeback === Writeback.PRE);
+ base_reg = args[0].base;
+ if (outputs.includes(base_reg)) {
+ // pass
+ } else {
+ outputs.push(base_reg);
+ writeback = true;
+ }
+ }
+ inputs = [base_reg];
+ is_effectful = false;
+ is_load = true;
+
+ eval_fn = (s, a) => {
+ const loads = [];
+ for (let i = 0; i < reg_list.regs.length; i++) {
+ const offset = get_ldm_stm_offset(i, reg_list.regs.length, direction);
+ const target = new AddressMode(offset, base_reg);
+ loads.push(deref(target, a.regs, a.stack_info, { size: 4 }));
+ }
+ reg_list.regs.forEach((r, k) => {
+ if (k < loads.length) s.set_reg(r, as_type(loads[k], Type.reg32({ likely_float: false }), true));
+ });
+ if (writeback) {
+ const imm = new Literal(4 * reg_list.regs.length);
+ const op = direction === "ia" || direction === "ib" ? "+" : "-";
+ s.set_reg(base_reg, BinaryOp.intptr(a.regs.get(base_reg), op, imm));
+ }
+ };
+ } else if (base === "stm") {
+ pyassert(!set_flags);
+ pyassert(["ia", "ib", "da", "db"].includes(direction));
+ pyassert(args[1] instanceof RegisterList);
+ const reg_list = args[1];
+ inputs = [...args[1].regs];
+ let writeback = false;
+ let base_reg;
+ if (args[0] instanceof Register) base_reg = args[0];
+ else {
+ pyassert(args[0] instanceof AsmAddressMode);
+ pyassert(args[0].addend === new AsmLiteral(0));
+ pyassert(args[0].writeback === Writeback.PRE);
+ base_reg = args[0].base;
+ outputs.push(base_reg);
+ writeback = true;
+ }
+ inputs.push(base_reg);
+ is_store = true;
+
+ eval_fn = (s, a) => {
+ reg_list.regs.forEach((r, i) => {
+ const offset = get_ldm_stm_offset(i, reg_list.regs.length, direction);
+ const target = new AddressMode(offset, base_reg);
+ const store = make_store_real(a.regs.get(r), a.regs.get_raw(r), target, a.regs, a.stack_info, Type.reg32({ likely_float: false }));
+ if (store !== null) s.store_memory(store, r);
+ });
+ if (writeback) {
+ const imm = new Literal(4 * reg_list.regs.length);
+ const op = direction === "ia" || direction === "ib" ? "+" : "-";
+ s.set_reg(base_reg, BinaryOp.intptr(a.regs.get(base_reg), op, imm));
+ }
+ };
+ } else if (base === "mov" && args[0] === new Register("pc")) {
+ pyassert(args.length === 2 && args[1] instanceof Register);
+ inputs.push(args[1]);
+ if (args[1] === new Register("lr")) is_return = true;
+ else {
+ jump_target = args[1];
+ is_conditional = true;
+ eval_fn = (s, a) => s.set_switch_expr(a.reg(1));
+ }
+ } else if (has(cls.instrs_store, base)) {
+ pyassert(args[0] instanceof Register);
+ inputs = [args[0]];
+ is_store = true;
+ if (args[1] instanceof AsmAddressMode) inputs.push(args[1].base);
+ eval_fn = (s, a) => {
+ const store = cls.instrs_store[base](a);
+ if (store !== null) s.store_memory(store, a.reg_ref(0));
+ };
+ } else if (has(cls.instrs_nz_flags, base)) {
+ if (base === "mov" || base === "mvn") pyassert(args.length === 2);
+ else if (base === "mla") pyassert(args.length === 4);
+ else pyassert(args.length === 3);
+ pyassert(args[0] instanceof Register);
+ outputs = [args[0]];
+ inputs = get_inputs(1);
+ if (set_flags) {
+ outputs.push(new Register("n"), new Register("z"));
+ clobbers = [new Register("hi"), new Register("ge"), new Register("gt")];
+ }
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ let val = cls.instrs_nz_flags[base](a);
+ val = s.set_reg(a.reg_ref(0), val);
+ if (set_flags) {
+ if (base === "mov" || base === "mul" || base === "mla") {
+ const sval = as_type(val, Type.s32(), true, { unify: false });
+ s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0)));
+ } else {
+ const top_bit = BinaryOp.int(val, "&", new Literal(2 ** 31));
+ s.set_reg(new Register("n"), BinaryOp.icmp(top_bit, "!=", new Literal(0)));
+ }
+ s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0)));
+ }
+ };
+ } else if (has(cls.instrs_mul_full, base)) {
+ pyassert(args.length === 4);
+ pyassert(args[0] instanceof Register);
+ pyassert(args[1] instanceof Register);
+ outputs = [args[0], args[1]];
+ inputs = get_inputs(2);
+ if (set_flags) {
+ outputs.push(new Register("n"), new Register("z"));
+ clobbers = [new Register("hi"), new Register("ge"), new Register("gt")];
+ }
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ let [hi, lo] = cls.instrs_mul_full[base](a);
+ lo = s.set_reg(a.reg_ref(0), lo);
+ hi = s.set_reg(a.reg_ref(1), hi);
+ if (set_flags) {
+ const shi = as_type(hi, Type.s32(), true, { unify: false });
+ s.set_reg(new Register("n"), BinaryOp.scmp(shi, "<", new Literal(0)));
+ s.set_reg(new Register("z"), new BinaryOp(BinaryOp.icmp(lo, "==", new Literal(0)), "&&", BinaryOp.icmp(hi, "==", new Literal(0)), { type: Type.boolean() }));
+ }
+ };
+ } else if (base === "smlal" || base === "umlal") {
+ pyassert(args.length === 4);
+ pyassert(args[0] instanceof Register);
+ pyassert(args[1] instanceof Register);
+ outputs = [args[0], args[1], new Register(base)];
+ inputs = get_inputs(0);
+ if (set_flags) {
+ outputs.push(new Register("n"), new Register("z"));
+ clobbers = [new Register("hi"), new Register("ge"), new Register("gt")];
+ }
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ const signed = base === "smlal";
+ const tp = signed ? Type.sintish() : Type.uintish();
+ const tp64 = signed ? Type.s64() : Type.u64();
+ const lhs = as_type(a.reg(2), tp, true);
+ const rhs = as_type(a.reg(3), tp, true);
+ const orig = BinaryOp.int(a.reg(0), "+", BinaryOp.int(a.reg(1), "<<", new Literal(32)));
+ const mul = BinaryOp.int(lhs, "*", rhs);
+ let mlal = as_type(BinaryOp.int(orig, "+", mul), tp64, true);
+ mlal = s.set_reg(new Register(base), mlal);
+ const upper = BinaryOp.int(mlal, ">>", new Literal(32));
+ const lo = as_type(mlal, Type.int_of_size(32), false);
+ const hi = as_type(upper, Type.int_of_size(32), false);
+ s.set_reg(a.reg_ref(0), lo);
+ s.set_reg(a.reg_ref(1), hi);
+ if (set_flags) {
+ const as_s64 = as_type(mlal, Type.s64(), true, { unify: false });
+ s.set_reg(new Register("n"), BinaryOp.scmp(as_s64, "<", new Literal(0)));
+ s.set_reg(new Register("z"), BinaryOp.icmp(mlal, "==", new Literal(0)));
+ }
+ };
+ } else if (base === "tst" || base === "teq") {
+ pyassert(args.length === 2);
+ inputs = get_inputs(0);
+ outputs = [new Register("n"), new Register("z")];
+ clobbers = [new Register("hi"), new Register("ge"), new Register("gt")];
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ const lhs = a.reg(0);
+ const rhs = a.reg_or_imm(1);
+ let val;
+ if (base === "tst") {
+ val = BinaryOp.int(lhs, "&", rhs);
+ s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0)));
+ } else {
+ val = BinaryOp.int(lhs, "^", rhs);
+ s.set_reg(new Register("z"), BinaryOp.icmp(lhs, "==", rhs));
+ }
+ const top_bit = BinaryOp.int(val, "&", new Literal(2 ** 31));
+ s.set_reg(new Register("n"), BinaryOp.icmp(top_bit, "!=", new Literal(0)));
+ };
+ } else if (mnemonic === "setcarryi.fictive") {
+ pyassert(args.length === 1 && args[0] instanceof AsmLiteral);
+ const imm = args[0].value;
+ outputs = [new Register("c"), new Register("hi")];
+ inputs = imm ? [new Register("z")] : [];
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ s.set_reg(new Register("c"), new Literal(imm));
+ if (imm === 0) s.set_reg(new Register("hi"), new Literal(0));
+ else {
+ const z = condition_from_expr(a.regs.get(new Register("z")));
+ s.set_reg(new Register("hi"), z.negated());
+ }
+ };
+ } else if (mnemonic === "setcarry.fictive") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ outputs = [new Register("c"), new Register("hi")];
+ inputs = [new Register("z")];
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ const c = s.set_reg(new Register("c"), new CarryBit(a.reg(0)));
+ const z = condition_from_expr(a.regs.get(new Register("z")));
+ const hi = new BinaryOp(c, "&&", z.negated(), { type: Type.boolean() });
+ s.set_reg(new Register("hi"), hi);
+ };
+ } else if (has(cls.instrs_add, base)) {
+ pyassert(args.length === 3 && args[0] instanceof Register);
+ outputs = [args[0]];
+ if (set_flags) outputs.push(...cls.flag_regs);
+ inputs = get_inputs(1);
+ if (base === "adc") inputs.push(new Register("c"));
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ let val = cls.instrs_add[base](a);
+ val = s.set_reg(a.reg_ref(0), val);
+ if (set_flags) set_arm_flags_from_add(s, val);
+ };
+ } else if (has(cls.instrs_sub, base)) {
+ pyassert(args.length === 3 && args[0] instanceof Register);
+ outputs = [args[0]];
+ if (set_flags) outputs.push(...cls.flag_regs);
+ inputs = get_inputs(1);
+ if (base === "sbc" || base === "rsc") inputs.push(new Register("c"));
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ let val = cls.instrs_sub[base](a);
+ if (val instanceof BinaryOp) val = fold_divmod(val);
+ val = fold_mul_chains(val);
+ val = s.set_reg(a.reg_ref(0), val);
+ if (set_flags) {
+ s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0, { type: val.type })));
+ let sval = as_type(val, Type.s32(), true, { unify: false });
+ s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0)));
+ const v = fn_op("M2C_OVERFLOW", [sval], Type.boolean());
+ s.set_reg(new Register("v"), v);
+ const uval = as_type(val, Type.u32(), true, { unify: false });
+ sval = as_type(val, Type.s32(), true, { unify: false });
+ const s64u = as_type(uval, Type.s64(), false, { unify: false });
+ const s64s = as_type(sval, Type.s64(), false, { unify: false });
+ s.set_reg(new Register("c"), BinaryOp.scmp(s64u, ">=", new Literal(0)));
+ s.set_reg(new Register("hi"), BinaryOp.scmp(s64u, ">", new Literal(0)));
+ s.set_reg(new Register("ge"), BinaryOp.scmp(s64s, ">=", new Literal(0)));
+ s.set_reg(new Register("gt"), BinaryOp.scmp(s64s, ">", new Literal(0)));
+ }
+ };
+ } else if (base === "cmp") {
+ pyassert(args.length === 2 && args[0] instanceof Register);
+ outputs = [...cls.flag_regs];
+ inputs = get_inputs(0);
+ is_effectful = false;
+ eval_fn = (s, a) => eval_arm_cmp(s, a.reg(0), a.reg_or_imm(1));
+ } else if (base === "cmn") {
+ pyassert(args.length === 2 && args[0] instanceof Register);
+ outputs = [...cls.flag_regs];
+ inputs = get_inputs(0);
+ is_effectful = false;
+ eval_fn = (s, a) => {
+ const lhs = a.reg(0);
+ const rhs = a.reg_or_imm(1);
+ if (rhs instanceof Literal && band(rhs.value, 0xffffffff) !== 0x80000000) eval_arm_cmp(s, lhs, new Literal(-rhs.value));
+ else set_arm_flags_from_add(s, handle_add_real(lhs, rhs, a));
+ };
+ } else if (has(cls.instrs_float_comp, base)) {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ if (mnemonic.includes(".d.")) inputs = [args[0], other_f64_reg(args[0]), args[1], other_f64_reg(args[1])];
+ else inputs = [args[0], args[1]];
+
+ let [cmp_cc, handler] = cls.instrs_float_comp[base];
+ let fc_negated;
+ [cmp_cc, fc_negated] = factor_cond(cmp_cc);
+ const creg = cc_reg(cmp_cc);
+
+ clobbers = cls.flag_regs.filter((r) => r !== creg);
+ outputs = [new Register("r0"), creg];
+ is_effectful = false;
+
+ eval_fn = (s, a) => {
+ const cond = handler(a);
+ s.set_reg_real(new Register("r0"), cond, { function_return: true });
+ s.set_reg(creg, fc_negated ? cond.negated() : cond);
+ };
+ // (upstream rebinds cc_negated here; the outer `cc` stays as parsed)
+ cc_negated = fc_negated;
+ } else if (cls.instrs_ignore.has(base)) {
+ is_effectful = false;
+ } else {
+ let maybe_dest_first;
+ if (args.length && args[0] instanceof Register && base !== "bx") {
+ inputs = args.slice(1).filter((r) => r instanceof Register);
+ outputs = [args[0]];
+ maybe_dest_first = true;
+ } else maybe_dest_first = false;
+
+ eval_fn = (s, a) => {
+ const error = new ErrorExpr(`unknown instruction: ${instr_str}`);
+ if (maybe_dest_first) s.set_reg_real(a.reg_ref(0), error, { emit_exactly_once: true });
+ else s.write_statement(new ExprStmt(error));
+ };
+ }
+
+ if (cc !== null) inputs.push(cc_reg(cc));
+
+ if (ShiftedRegPattern.sets_flags_based_on_barrel_shifter(base, set_flags, args)) outputs.push(new Register("c"), new Register("hi"));
+
+ return new Instruction({
+ mnemonic,
+ args,
+ meta,
+ inputs,
+ clobbers,
+ outputs,
+ jump_target,
+ function_target,
+ is_conditional,
+ is_return,
+ is_store,
+ is_load,
+ is_effectful,
+ eval_fn,
+ });
+ }
+
+ default_function_abi_candidate_slots() {
+ return [0, 1, 2, 3].map((i) => new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i}`)), Type.any_reg()));
+ }
+
+ is_likely_partial_offset(addend) {
+ return addend < 0x1000000 && pymod(addend, 0x100) === 0;
+ }
+
+ arg_name(loc) {
+ if (loc.offset !== null) return `arg${format_hex(floordiv(loc.offset, 4) + 4)}`;
+ pyassert(loc.reg !== null);
+ return `arg${loc.reg.register_name.slice(1)}`;
+ }
+
+ /** Compute stack positions/registers used by a function according to the agbcc ABI. */
+ function_abi(fn_sig, likely_regs, { for_call }) {
+ void for_call;
+ const known_slots = [];
+ let candidate_slots = [];
+ if (fn_sig.params_known) {
+ let offset = 0;
+ if (fn_sig.return_type.is_struct() && fn_sig.return_type.get_parameter_size_align_bytes()[0] > 4) {
+ known_slots.push(new AbiArgSlot(new ArgLoc(null, 0, new Register("r0")), Type.ptr(fn_sig.return_type), { name: "__return__", comment: "return" }));
+ offset = 4;
+ }
+
+ for (const param of fn_sig.params) {
+ const param_type = param.type.decay();
+ let [size, align] = param_type.get_parameter_size_align_bytes();
+ size = band(size + 3, ~3);
+ offset = band(offset + align - 1, -align);
+ const name = param.name;
+ for (let i = floordiv(offset, 4); i < floordiv(offset + size, 4); i++) {
+ const unk_offset = 4 * i - offset;
+ let reg2 = null;
+ let stack_loc = null;
+ if (i < 4) reg2 = new Register(`r${i}`);
+ else stack_loc = (i - 4) * 4;
+ let name2, sub_type, comment;
+ if (size > 4) {
+ name2 = name ? `${name}_unk${format(unk_offset, "X")}` : null;
+ sub_type = Type.any();
+ comment = `${param_type}+${format(unk_offset, "#x")}`;
+ } else {
+ pyassert(unk_offset === 0);
+ name2 = name;
+ sub_type = param_type;
+ comment = null;
+ }
+ known_slots.push(new AbiArgSlot(new ArgLoc(stack_loc, i, reg2), sub_type, { name: name2, comment }));
+ }
+ offset += size;
+ }
+
+ if (fn_sig.is_variadic) {
+ for (let i = floordiv(offset, 4); i < 4; i++) candidate_slots.push(new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i}`)), Type.any_reg()));
+ }
+ } else {
+ candidate_slots = this.default_function_abi_candidate_slots();
+ }
+
+ const valid_extra_regs = new Set();
+ for (const slot of known_slots) if (slot.loc.reg !== null) valid_extra_regs.add(slot.loc.reg);
+ const possible_slots = [];
+
+ let lasti = -1;
+ for (let i = 0; i < 4; i++) {
+ if (!likely_regs.has(new Register(`r${i}`))) break;
+ lasti = i;
+ }
+ for (let i = lasti; i > 0; i--) {
+ if (likely_regs.get(new Register(`r${i}`))) likely_regs.set(new Register(`r${i - 1}`), true);
+ }
+
+ for (const slot of candidate_slots) {
+ const reg = slot.loc.reg;
+ if (reg === null || !likely_regs.has(reg)) continue;
+
+ let require = null;
+ if (slot === candidate_slots[0]) {
+ // pass
+ } else if (reg === new Register("r1")) require = ["r0"];
+ else if (reg === new Register("r2")) require = ["r1"];
+ else if (reg === new Register("r3")) require = ["r2"];
+ if (require && !require.some((r) => valid_extra_regs.has(new Register(r)))) continue;
+
+ valid_extra_regs.add(reg);
+
+ if (!likely_regs.get(reg)) continue;
+
+ possible_slots.push(slot);
+ }
+
+ return new Abi({ arg_slots: known_slots, possible_slots });
+ }
+
+ function_return(expr) {
+ return new Map([
+ [new Register("r0"), as_type(expr, Type.intptr(), true, { unify: false })],
+ [new Register("r1"), fn_op("SECOND_REG", [expr], Type.reg32({ likely_float: false }))],
+ ]);
+ }
+}
+
+{
+ const argument_regs = ["r0", "r1", "r2", "r3"].map((r) => new Register(r));
+ const simple_temp_regs = [
+ new Register("r12"),
+ ...Array.from({ length: 16 }, (_, i) => new Register(`s${i}`)),
+ ...Array.from({ length: 8 }, (_, i) => new Register(`d${i}`)),
+ ...Array.from({ length: 4 }, (_, i) => new Register(`q${i}`)),
+ ];
+ const flag_regs = ["n", "z", "c", "v", "hi", "ge", "gt"].map((r) => new Register(r));
+ const temp_regs = [...argument_regs, ...simple_temp_regs, ...flag_regs];
+ const saved_regs = [
+ new Register("lr"),
+ ...Array.from({ length: 8 }, (_, i) => new Register(`r${i + 4}`)),
+ ...Array.from({ length: 16 }, (_, i) => new Register(`s${i + 16}`)),
+ ...Array.from({ length: 8 }, (_, i) => new Register(`d${i + 8}`)),
+ ...Array.from({ length: 4 }, (_, i) => new Register(`q${i + 4}`)),
+ ];
+ const stack_pointer_reg = new Register("sp");
+ const R = (n) => new Register(n);
+
+ Object.assign(ArmArch.prototype, {
+ arch: Target.ArchEnum.ARM,
+ re_comment: String.raw`^[ \t]*#.*|[@;].*`,
+ supports_dollar_regs: false,
+ home_space_size: 0,
+ stack_pointer_reg,
+ frame_pointer_regs: [R("r7"), R("r11")],
+ return_address_reg: R("lr"),
+ base_return_regs: [[R("r0"), false]],
+ all_return_regs: [R("r0"), R("r1")],
+ argument_regs,
+ simple_temp_regs,
+ flag_regs,
+ temp_regs,
+ saved_regs,
+ all_regs: [...saved_regs, ...temp_regs, stack_pointer_reg, R("pc")],
+ aliased_regs: {
+ a1: R("r0"),
+ a2: R("r1"),
+ a3: R("r2"),
+ a4: R("r3"),
+ v1: R("r4"),
+ v2: R("r5"),
+ v3: R("r6"),
+ v4: R("r7"),
+ v5: R("r8"),
+ v6: R("r9"),
+ v7: R("r10"),
+ v8: R("r11"),
+ wr: R("r7"),
+ sb: R("r9"),
+ tr: R("r9"),
+ sl: R("r10"),
+ fp: R("r11"),
+ ip: R("r12"),
+ r13: R("sp"),
+ r14: R("lr"),
+ r15: R("pc"),
+ },
+ asm_patterns: [
+ new AddPcPcPattern(),
+ new ShortJumpTablePattern(),
+ new ConditionalInstrPattern(),
+ new NegatedRegAddrModePattern(),
+ new ShiftedRegAddrModePattern(),
+ new ShiftedRegPattern(),
+ new AddrModeWritebackPattern(),
+ new RegRegAddrModePattern(),
+ new PopAndReturnPattern(),
+ new OldThumbBlxPattern(),
+ new IndirectTailCallPattern(),
+ new TailCallPattern(),
+ new BlBranchPattern(),
+ new MagicFuncPattern(),
+ ],
+ instrs_ignore: new Set(["push", "vpush", "vpop", "nop"]),
+ instrs_no_flags: {
+ // Bit-fiddling
+ clz: (a) => fn_op("CLZ", [a.reg(1)], Type.intish()),
+ rbit: (a) => fn_op("REVERSE_BITS", [a.reg(1)], Type.intish()),
+ rev: (a) => fn_op("BSWAP32", [a.reg(1)], Type.intish()),
+ rev16: (a) => fn_op("BSWAP16X2", [a.reg(1)], Type.intish()),
+ revsh: (a) => fn_op("BSWAP16", [a.reg(1)], Type.s16()),
+ // Shifts
+ lsl: (a) => handle_sll(a, { arm: true }),
+ asr: (a) => handle_shift_right(a, { arm: true, signed: true }),
+ lsr: (a) => handle_shift_right(a, { arm: true, signed: false }),
+ ror: (a) => fn_op("ROTATE_RIGHT", [a.reg(1), a.reg_or_imm(2)], Type.intish()),
+ rrx: (a) => fn_op("ARM_RRX", [a.reg(1), a.regs.get(new Register("c"))], Type.intish()),
+ // Immediate movs
+ adr: (a) => handle_la(a),
+ "movimm.fictive": (a) => a.full_imm(1),
+ // Loading instructions
+ ldr: (a) => handle_load(a, Type.reg32({ likely_float: false })),
+ ldrb: (a) => handle_load(a, Type.u8()),
+ ldrsb: (a) => handle_load(a, Type.s8()),
+ ldrh: (a) => handle_load(a, Type.u16()),
+ ldrsh: (a) => handle_load(a, Type.s16()),
+ vldr: (a) => handle_load(a, vreg_type(a.reg_ref(0))),
+ // Arithmetic
+ smulbb: (a) => BinaryOp.int(a.reg(1), "*", a.reg(2)),
+ smlabb: (a) => handle_add_real(a.reg(3), BinaryOp.int(a.reg(1), "*", a.reg(2)), a),
+ sdiv: (a) => BinaryOp.sint(a.reg(1), "/", a.reg(2)),
+ udiv: (a) => BinaryOp.uint(a.reg(1), "/", a.reg(2)),
+ "smod.fictive": (a) => BinaryOp.sint(a.reg(1), "%", a.reg(2)),
+ "umod.fictive": (a) => BinaryOp.uint(a.reg(1), "%", a.reg(2)),
+ // Floating point arithmetic
+ "add.s.fictive": (a) => handle_add_float(a),
+ "sub.s.fictive": (a) => BinaryOp.f32(a.reg(1), "-", a.reg(2)),
+ "div.s.fictive": (a) => BinaryOp.f32(a.reg(1), "/", a.reg(2)),
+ "mul.s.fictive": (a) => BinaryOp.f32(a.reg(1), "*", a.reg(2)),
+ "sqrt.s.fictive": (a) => fn_op("sqrtf", [as_f32(a.reg(1))], Type.f32()),
+ "round.s.fictive": (a) => fn_op("roundf", [as_f32(a.reg(1))], Type.f32()),
+ "add.d.fictive": (a) => handle_add_double(a),
+ "sub.d.fictive": (a) => BinaryOp.f64(a.dreg(1), "-", a.dreg(2)),
+ "div.d.fictive": (a) => BinaryOp.f64(a.dreg(1), "/", a.dreg(2)),
+ "mul.d.fictive": (a) => BinaryOp.f64(a.dreg(1), "*", a.dreg(2)),
+ "sqrt.d.fictive": (a) => fn_op("sqrt", [as_f64(a.dreg(1))], Type.f64()),
+ "round.d.fictive": (a) => fn_op("round", [as_f64(a.dreg(1))], Type.f64()),
+ // Floating point conversions
+ "cvt.d.s.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.f32()),
+ "cvt.d.w.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.intish()),
+ "cvt.d.u.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.u32()),
+ "cvt.s.d.fictive": (a) => handle_convert(a.dreg(1), Type.f32(), Type.f64()),
+ "cvt.s.w.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.intish()),
+ "cvt.s.u.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.u32()),
+ "cvt.w.d.fictive": (a) => handle_convert(a.dreg(1), Type.s32(), Type.f64()),
+ "cvt.w.s.fictive": (a) => handle_convert(a.reg(1), Type.s32(), Type.f32()),
+ "cvt.u.d.fictive": (a) => handle_convert(a.dreg(1), Type.u32(), Type.f64()),
+ "cvt.u.s.fictive": (a) => handle_convert(a.reg(1), Type.u32(), Type.f32()),
+ },
+ instrs_float_comp: {
+ "c.eq.s.fictive": [Cc.EQ, (a) => BinaryOp.fcmp(a.reg(0), "==", a.reg(1))],
+ "c.lt.s.fictive": [Cc.CC, (a) => BinaryOp.fcmp(a.reg(0), "<", a.reg(1))],
+ "c.ge.s.fictive": [Cc.CS, (a) => BinaryOp.fcmp(a.reg(0), ">=", a.reg(1))],
+ "c.le.s.fictive": [Cc.LS, (a) => BinaryOp.fcmp(a.reg(0), "<=", a.reg(1))],
+ "c.gt.s.fictive": [Cc.HI, (a) => BinaryOp.fcmp(a.reg(0), ">", a.reg(1))],
+ "c.neq.s.fictive": [Cc.NE, (a) => BinaryOp.fcmp(a.reg(0), "==", a.reg(1)).negated()],
+ "c.eq.d.fictive": [Cc.EQ, (a) => BinaryOp.dcmp(a.dreg(0), "==", a.dreg(1))],
+ "c.lt.d.fictive": [Cc.CC, (a) => BinaryOp.dcmp(a.dreg(0), "<", a.dreg(1))],
+ "c.ge.d.fictive": [Cc.CS, (a) => BinaryOp.dcmp(a.dreg(0), ">=", a.dreg(1))],
+ "c.le.d.fictive": [Cc.LS, (a) => BinaryOp.dcmp(a.dreg(0), "<=", a.dreg(1))],
+ "c.gt.d.fictive": [Cc.HI, (a) => BinaryOp.dcmp(a.dreg(0), ">", a.dreg(1))],
+ "c.neq.d.fictive": [Cc.NE, (a) => BinaryOp.dcmp(a.dreg(0), "==", a.dreg(1)).negated()],
+ },
+ instrs_divmod: {
+ "sdivmod.fictive": (a) => [BinaryOp.sint(a.reg(0), "/", a.reg(1)), BinaryOp.sint(a.reg(0), "%", a.reg(1))],
+ "udivmod.fictive": (a) => [BinaryOp.uint(a.reg(0), "/", a.reg(1)), BinaryOp.uint(a.reg(0), "%", a.reg(1))],
+ },
+ instrs_nz_flags: {
+ mov: (a) => handle_arm_mov(a),
+ mul: (a) => BinaryOp.int(a.reg(1), "*", a.reg(2)),
+ mla: (a) => BinaryOp.int(BinaryOp.int(a.reg(1), "*", a.reg(2)), "+", a.reg(3)),
+ mvn: (a) => handle_bitinv(a.reg_or_imm(1)),
+ and: (a) => replace_bitand(BinaryOp.int(a.reg(1), "&", a.reg_or_imm(2))),
+ orr: (a) => handle_or(a.reg(1), a.reg_or_imm(2), { is_arm: true }),
+ eor: (a) => handle_xor(a.reg(1), a.reg_or_imm(2)),
+ bic: (a) => BinaryOp.int(a.reg(1), "&", UnaryOp.int("~", a.reg_or_imm(2))),
+ orn: (a) => BinaryOp.int(a.reg(1), "|", UnaryOp.int("~", a.reg_or_imm(2))),
+ },
+ instrs_mul_full: {
+ smull: (a) => [fold_divmod(BinaryOp.int(a.reg(2), "MULT_HI", a.reg(3))), BinaryOp.int(a.reg(2), "*", a.reg(3))],
+ umull: (a) => [fold_divmod(BinaryOp.int(a.reg(2), "MULTU_HI", a.reg(3))), BinaryOp.int(a.reg(2), "*", a.reg(3))],
+ },
+ instrs_store: {
+ str: (a) => make_store(a, Type.reg32({ likely_float: false })),
+ strb: (a) => make_store(a, Type.int_of_size(8)),
+ strh: (a) => make_store(a, Type.int_of_size(16)),
+ vstr: (a) => make_store(a, vreg_type(a.reg_ref(0))),
+ },
+ instrs_add: {
+ add: (a) => handle_add_arm(a),
+ adc: (a) => handle_add_real(handle_add_arm(a), a.regs.get(new Register("c")), a),
+ },
+ instrs_sub: {
+ sub: (a) => handle_sub_arm(a),
+ rsb: (a) => handle_sub(a.reg_or_imm(2), a.reg(1)),
+ sbc: (a) => handle_add_real(handle_sub(a.reg(1), a.reg_or_imm(2)), condition_from_expr(a.regs.get(new Register("c"))).negated(), a),
+ rsc: (a) => handle_add_real(handle_sub(a.reg_or_imm(2), a.reg(1)), condition_from_expr(a.regs.get(new Register("c"))).negated(), a),
+ },
+ });
+}
+
+/** Arch variant that follows the APCS ABI used on Gameboy Advance. */
+export class ArmGbaArch extends ArmArch {}
+ArmGbaArch.prototype.base_struct_align = 4;
diff --git a/packages/romdev-m2c/src/arch_mips.js b/packages/romdev-m2c/src/arch_mips.js
new file mode 100644
index 00000000..e7cdf558
--- /dev/null
+++ b/packages/romdev-m2c/src/arch_mips.js
@@ -0,0 +1,1134 @@
+// Port of m2c/arch_mips.py
+import { DecompFailure } from "./error.js";
+import { Target } from "./options.js";
+import { Label } from "./asm_file.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, Register, get_jump_target } from "./asm_instruction.js";
+import { Instruction, InstructionMeta, StackLocation } from "./instruction.js";
+import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js";
+import {
+ Abi,
+ AbiArgSlot,
+ Arch,
+ ArgLoc,
+ BinaryOp,
+ Cast,
+ CommentStmt,
+ ErrorExpr,
+ ExprStmt,
+ Literal,
+ SecondF64Half,
+ UnaryOp,
+ as_f32,
+ as_f64,
+ as_intish,
+ as_s64,
+ as_type,
+ as_u32,
+ as_u64,
+ format_hex,
+} from "./translate.js";
+import {
+ condition_from_expr,
+ error_stmt,
+ fn_op,
+ fold_divmod,
+ fold_mul_chains,
+ handle_add,
+ handle_add_double,
+ handle_add_float,
+ handle_add_real,
+ handle_addi_mips,
+ handle_bgez,
+ handle_conditional_move,
+ handle_convert,
+ handle_la,
+ handle_load,
+ handle_lw,
+ handle_lwl,
+ handle_lwr,
+ handle_or,
+ handle_shift_right,
+ handle_sltiu,
+ handle_sltu,
+ handle_swl,
+ handle_swr,
+ handle_xor,
+ imm_add_32,
+ load_upper,
+ make_store,
+ void_fn_op,
+} from "./evaluate.js";
+import { Type } from "./types.js";
+import { band, floordiv, format, has, int_, pyassert } from "./py.js";
+
+const R = (n) => new Register(n);
+
+const LENGTH_TWO = new Set(["neg", "negu", "not", "neg.s", "abs.s", "sqrt.s", "neg.d", "abs.d", "sqrt.d"]);
+const LENGTH_THREE = new Set([
+ "slt", "slti", "sltu", "sltiu", "add", "addi", "addiu", "addu", "sub", "subu", "daddi", "daddiu", "dsubu",
+ "add.s", "sub.s", "div.s", "mul.s", "add.d", "sub.d", "div.d", "mul.d", "ori", "and", "or", "nor", "xor",
+ "andi", "xori", "sll", "sllv", "srl", "srlv", "sra", "srav", "dsll", "dsll32", "dsllv", "dsrl", "dsrl32",
+ "dsrlv", "dsra", "dsra32", "dsrav", "div", "divu", "ddiv", "ddivu",
+]);
+
+export function other_f64_reg(reg) {
+ pyassert(reg.is_float(), "tried to get complement reg of non-floating point register");
+ const num = int_(reg.register_name.slice(1));
+ return R(`f${num ^ 1}`);
+}
+
+class DivPattern extends SimpleAsmPattern {
+ pattern = make_pattern("bnez $q, .A", "*", "break", ".A:", "li $at, -1", "bne $q, $at, .B", "li $at, 0x80000000", "bne $p, $at, .B", "nop", "break", ".B:");
+ replace(m) {
+ return new Replacement([m.body[1]], m.body.length - 1);
+ }
+}
+
+class DivuPattern extends SimpleAsmPattern {
+ pattern = make_pattern("bnez $q, .A", "nop", "break", ".A:");
+ replace(m) {
+ return new Replacement([], m.body.length - 1);
+ }
+}
+
+/** Modulo by power of two. */
+class ModP2Pattern1 extends SimpleAsmPattern {
+ pattern = make_pattern("bgez $i, .A", "andi $o, $i, N", "beqz $o, .A", "nop", "addiu $o, $o, (-1 - N)", ".A:");
+ replace(m) {
+ const val = band(m.literals.get("N"), 0xffff) + 1;
+ if (band(val, val - 1)) return null;
+ const mod = new AsmInstruction("mod.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(val)]);
+ return new Replacement([mod], m.body.length - 1);
+ }
+}
+
+/** Modulo by power of two where the mask is too big to fit an andi. */
+class ModP2Pattern2 extends SimpleAsmPattern {
+ pattern = make_pattern("li $at, HI", "addiu $at, $at, LO?", "bgez $i, .A", "and $o, $i, $at", "beqz $o, .A", "addiu $at, $at, 1", "subu $o, $o, $at", ".A:");
+ replace(m) {
+ let val = band(m.literals.get("HI"), 0xffffffff) + 1;
+ if (m.literals.has("LO")) val += band(m.literals.get("LO") + 0x8000, 0xffff) - 0x8000;
+ if (!val || band(val, val - 1)) return null;
+ const mod = new AsmInstruction("mod.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(val)]);
+ return new Replacement([mod], m.body.length - 1);
+ }
+}
+
+/** Division by power of two where input reg != output reg. */
+class DivP2Pattern1 extends SimpleAsmPattern {
+ pattern = make_pattern("bgez $i, .A", "sra $o, $i, N", "addiu $at, $i, ((1 << N) - 1)", "sra $o, $at, N", ".A:");
+ replace(m) {
+ const shift = band(m.literals.get("N"), 0x1f);
+ const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(2 ** shift)]);
+ return new Replacement([div], m.body.length - 1);
+ }
+}
+
+/** Division by power of two where input reg = output reg. */
+class DivP2Pattern2 extends AsmPattern {
+ pattern1 = make_pattern("bgez $x, .A", "move $at, $x", "addiu $at, $x, M", ".A:", "sra $x, $at, N");
+ pattern2 = make_pattern("bgez $x, .A", "nop", "addiu $x, $x, M", ".A:", "sra $x, $x, N");
+ pattern3 = make_pattern("bltzl $x, .A", "addiu $x, $x, M", ".A:", "sra $x, $x, N");
+ match(matcher) {
+ for (const pattern of [this.pattern1, this.pattern2, this.pattern3]) {
+ const m = matcher.try_match(pattern);
+ if (!m) continue;
+ const shift = band(m.literals.get("N"), 0x1f);
+ if (m.literals.get("M") !== 2 ** shift - 1) continue;
+ const div = new AsmInstruction("div.fictive", [m.regs.get("x"), m.regs.get("x"), new AsmLiteral(2 ** shift)]);
+ return new Replacement([div], m.body.length);
+ }
+ return null;
+ }
+}
+
+class Div2S16Pattern extends SimpleAsmPattern {
+ pattern = make_pattern("sll $i, $i, N", "sra $o, $i, N", "srl $i, $i, 0x1f", "addu $o, $o, $i", "sra $o, $o, 1");
+ replace(m) {
+ const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("o"), new AsmLiteral(2)]);
+ return new Replacement([m.body[0], m.body[1], div], m.body.length);
+ }
+}
+
+class Div2S32Pattern1 extends SimpleAsmPattern {
+ pattern = make_pattern("srl $t, $i, 0x1f", "addu $t, $i, $t", "sra $o, $t, 1");
+ replace(m) {
+ if (m.regs.get("t") === m.regs.get("i")) return null;
+ const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(2)]);
+ return new Replacement([div], m.body.length);
+ }
+}
+
+class Div2S32Pattern2 extends SimpleAsmPattern {
+ pattern = make_pattern("srl $t, $i, 0x1f", "addu $i, $i, $t", "sra $o, $i, 1");
+ replace(m) {
+ if (m.regs.get("t") === m.regs.get("i")) return null;
+ const div = new AsmInstruction("div.fictive", [m.regs.get("o"), m.regs.get("i"), new AsmLiteral(2)]);
+ return new Replacement([div], m.body.length);
+ }
+}
+
+class UtfPattern extends SimpleAsmPattern {
+ pattern = make_pattern("bgez $x, .A", "cvt.s.w $o, $i", "li $at, 0x4f800000", "mtc1", "nop", "add.s", ".A:");
+ replace(m) {
+ const new_instr = new AsmInstruction("cvt.s.u.fictive", [m.regs.get("o"), m.regs.get("i")]);
+ return new Replacement([new_instr], m.body.length - 1);
+ }
+}
+
+class FtuPattern extends SimpleAsmPattern {
+ pattern = make_pattern(
+ "cfc1 $o, $31", "nop", "andi", "andi?", "*", "*", "li?", "mtc1", "mtc1?", "li", "*", "ctc1", "nop", "*",
+ "cfc1", "nop", "andi", "andi?", "bnez", "nop", "mfc1", "li", "b", "or", ".A:", "b", "li", "*", "*", "nop", "bltz", "nop",
+ );
+ replace(m) {
+ const sub = m.body.find((x) => x instanceof Instruction && x.mnemonic.startsWith("sub"));
+ if (sub === undefined) throw new Error("StopIteration");
+ const parts = sub.mnemonic.split(".");
+ const fmt = parts[parts.length - 1];
+ const args = [m.regs.get("o"), sub.args[1]];
+ const new_instr = fmt === "s" ? new AsmInstruction("cvt.u.s.fictive", args) : new AsmInstruction("cvt.u.d.fictive", args);
+ return new Replacement([new_instr], m.body.length);
+ }
+}
+
+class Mips1DoubleLoadStorePattern extends AsmPattern {
+ lwc_pattern = make_pattern("lwc1", "lwc1");
+ swc_pattern = make_pattern("swc1", "swc1");
+ match(matcher) {
+ if (matcher.arch instanceof MipseeArch) return null;
+ const m = matcher.try_match(this.lwc_pattern) || matcher.try_match(this.swc_pattern);
+ if (!m) return null;
+ const [a, b] = m.body;
+ pyassert(a instanceof Instruction);
+ pyassert(b instanceof Instruction);
+ let [ra, ma] = a.args;
+ let [rb, mb] = b.args;
+ if (!(ra instanceof Register && ra.is_float() && other_f64_reg(ra) === rb && ma instanceof AsmAddressMode && mb instanceof AsmAddressMode && ma.base === mb.base)) return null;
+ const num = int_(ra.register_name.slice(1));
+ if (num % 2 === 1) {
+ [ra, rb] = [rb, ra];
+ [ma, mb] = [mb, ma];
+ }
+ if (ma.addend instanceof AsmLiteral && mb.addend instanceof AsmLiteral && ma.addend.value !== mb.addend.value + 4) return null;
+ const new_mn = a.mnemonic === "lwc1" ? "ldc1" : "sdc1";
+ const new_instr = new AsmInstruction(new_mn, [ra, mb]);
+ return new Replacement([new_instr], m.body.length);
+ }
+}
+
+class GccSqrtPatternJal extends SimpleAsmPattern {
+ pattern = make_pattern("sqrt.s $o, $i", "c.eq.s", "nop?", "bc1t", "*", "jal sqrtf", "nop", "mov.s $o, $f0?");
+ replace(m) {
+ return new Replacement([m.body[0], m.wildcard_items[0]], m.body.length);
+ }
+}
+
+class GccSqrtPatternJalr extends SimpleAsmPattern {
+ pattern = make_pattern("sqrt.s $o, $i", "c.eq.s", "nop?", "bc1t", "*", "lui $x, %hi(sqrtf)", "addiu $x, $x, %lo(sqrtf)", "jalr $ra, $x", "nop", "mov.s $o, $f0?");
+ replace(m) {
+ return new Replacement([m.body[0], m.wildcard_items[0]], m.body.length);
+ }
+}
+
+class TrapuvPattern extends SimpleAsmPattern {
+ pattern = make_pattern("li $x, 0xfffa0000", "move $y, $sp", "addiu $sp, $sp, N", "ori $x, $x, 0x5a5a", ".loop:", "addiu $y, $y, -8", "sw $x, ($y)", "bne $y, $sp, .loop", "sw $x, 4($y)");
+ replace(m) {
+ const new_instr = new AsmInstruction("trapuv.fictive", []);
+ return new Replacement([m.body[2], new_instr], m.body.length);
+ }
+}
+
+/** Strip PIC .cpload pattern at the top of functions. */
+class SetGpPattern extends AsmPattern {
+ pattern = make_pattern("*", "addiu $gp, $gp, _", "addu $gp, $gp, $t9");
+ match(matcher) {
+ if (matcher.index !== 0) return null;
+ const m = matcher.try_match(this.pattern);
+ if (m === null) return null;
+ const nop = new AsmInstruction("nop", []);
+ return new Replacement([nop], m.body.length);
+ }
+}
+
+/** IDO unrolled memcpy, used e.g. for struct copies. */
+class MemcpyPatternBase extends AsmPattern {
+ match(matcher) {
+ let m = null;
+ let pattern = null;
+ for (const p of [this.pattern_mips1, this.pattern_mips2]) {
+ m = matcher.try_match(p);
+ pattern = p;
+ if (m) break;
+ }
+ if (!m) return null;
+
+ let e_src = null;
+ let i_src = null;
+ for (let i = matcher.index - 1; i >= 0; i--) {
+ const item = matcher.input[i];
+ if (item instanceof Label) break;
+ if (!i_src && item.outputs.includes(m.regs.get("i"))) i_src = item;
+ if (!e_src && item.outputs.includes(m.regs.get("e"))) e_src = item;
+ }
+ if (e_src === null || e_src.mnemonic !== "addiu") return null;
+ if (e_src.args[1] !== m.regs.get("i") && (i_src === null || i_src.mnemonic !== "move" || i_src.args[1] !== e_src.args[1])) return null;
+ pyassert(e_src.args[2] instanceof AsmLiteral);
+ let length = e_src.args[2].value;
+
+ const added_length = length;
+ const m2 = matcher.try_match([...pattern, ...this.epilogue1]);
+ if (m2) {
+ m = m2;
+ length += 4;
+ const m3 = matcher.try_match([...pattern, ...this.epilogue1, ...this.epilogue2]);
+ if (m3) {
+ m = m3;
+ length += 4;
+ }
+ }
+
+ const from_reg = R("from");
+ const to_reg = R("to");
+ const from_offset = new AsmLiteral(m.literals.get("N"));
+ const to_offset = new AsmLiteral(m.literals.get("M"));
+ const added_len_arg = new AsmLiteral(added_length);
+ const len_arg = new AsmLiteral(length);
+ return new Replacement(
+ [
+ m.body[0],
+ new AsmInstruction("addiu", [from_reg, m.regs.get("i"), from_offset]),
+ new AsmInstruction("addiu", [to_reg, m.regs.get("o"), to_offset]),
+ new AsmInstruction(this.instruction_name, [to_reg, from_reg, len_arg]),
+ new AsmInstruction("addiu", [m.regs.get("o"), m.regs.get("o"), added_len_arg]),
+ new AsmInstruction("addiu", [m.regs.get("i"), m.regs.get("i"), added_len_arg]),
+ ...m.wildcard_items,
+ new AsmInstruction("nop", []),
+ ],
+ m.body.length,
+ );
+ }
+}
+
+class AlignedMemcpyPattern extends MemcpyPatternBase {
+ pattern_mips1 = make_pattern(".loop:", "lw $a, N($i)", "addiu $i, $i, 12", "sw $a, M($o)", "lw $b, (N-8)($i)", "addiu $o, $o, 12", "sw $b, (M-8)($o)", "lw $c, (N-4)($i)", "bne $i, $e, .loop", "sw $c, (M-4)($o)");
+ pattern_mips2 = make_pattern(".loop:", "lw $a, N($i)", "addiu $i, $i, 12", "addiu $o, $o, 12", "sw $a, MM($o)", ".eq M, MM+12", "lw $b, (N-8)($i)", "sw $b, (M-8)($o)", "lw $c, (N-4)($i)", "bne $i, $e, .loop", "sw $c, (M-4)($o)");
+ epilogue1 = make_pattern("lw $x, N($i)", "*", "sw $x, M($o)");
+ epilogue2 = make_pattern("lw $y, (N+4)($i)", "*", "sw $y, (M+4)($o)");
+ instruction_name = "memcpy.aligned.fictive";
+}
+
+class UnalignedMemcpyPattern extends MemcpyPatternBase {
+ pattern_mips1 = make_pattern(
+ ".loop:", "lwl $a, N($i)", "lwr $a, (N+3)($i)", "addiu $i, $i, 12", "swl $a, M($o)", "swr $a, (M+3)($o)", "lwl $b, (N-8)($i)", "lwr $b, (N-5)($i)",
+ "addiu $o, $o, 12", "swl $b, (M-8)($o)", "swr $b, (M-5)($o)", "lwl $c, (N-4)($i)", "lwr $c, (N-1)($i)", "nop", "swl $c, (M-4)($o)", "bne $i, $e, .loop", "swr $c, (M-1)($o)",
+ );
+ pattern_mips2 = make_pattern(
+ ".loop:", "lwl $a, N($i)", "lwr $a, (N+3)($i)", "addiu $i, $i, 12", "addiu $o, $o, 12", "swl $a, MM($o)", ".eq M, MM+12", "swr $a, (M-9)($o)", "lwl $b, (N-8)($i)",
+ "lwr $b, (N-5)($i)", "swl $b, (M-8)($o)", "swr $b, (M-5)($o)", "lwl $c, (N-4)($i)", "lwr $c, (N-1)($i)", "swl $c, (M-4)($o)", "bne $i, $e, .loop", "swr $c, (M-1)($o)",
+ );
+ epilogue1 = make_pattern("lwl $x, N($i)", "lwr $x, (N+3)($i)", "*", "swl $x, M($o)", "swr $x, (M+3)($o)");
+ epilogue2 = make_pattern("lwl $y, (N+4)($i)", "lwr $y, (N+7)($i)", "*", "swl $y, (M+4)($o)", "swr $y, (M+7)($o)");
+ instruction_name = "memcpy.unaligned.fictive";
+}
+
+/** Remove additions of $gp used for position-independent jump tables. */
+class GpJumpPattern extends SimpleAsmPattern {
+ pattern = make_pattern("addu $x, $x, $gp", "jr $x");
+ replace(m) {
+ return new Replacement([m.body[1]], m.body.length);
+ }
+}
+
+/** Some PS2 compilers emit ori for small stack additions instead of addiu. */
+class OriSpPattern extends SimpleAsmPattern {
+ pattern = make_pattern("ori $x, $sp, N");
+ replace(m) {
+ const n = m.literals.get("N");
+ if (0 <= n && n < 16 && m.regs.get("x") !== R("sp")) {
+ const ins = new AsmInstruction("addiu", [m.regs.get("x"), R("sp"), new AsmLiteral(n)]);
+ return new Replacement([ins], m.body.length);
+ }
+ return null;
+ }
+}
+
+/** `return fn(...);` may be optimized to a `j fn`. */
+class TailCallPattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (instr instanceof Instruction && instr.mnemonic === "j" && instr.args[0] instanceof AsmGlobalSymbol && !matcher.is_local_label(instr.args[0].symbol_name)) {
+ return new Replacement(
+ [new AsmInstruction("jal", instr.args), new AsmInstruction("nop", []), new AsmInstruction("jr", [R("ra")]), new AsmInstruction("nop", [])],
+ 1,
+ );
+ }
+ return null;
+ }
+}
+
+const regs = (names) => names.map(R);
+
+export class MipsArch extends Arch {
+ missing_return() {
+ const meta = InstructionMeta.missing();
+ return [this.parse("jr", [R("ra")], meta), this.parse("nop", [], meta)];
+ }
+
+ normalize_instruction(instr, asm_state) {
+ const args = instr.args;
+ const zero = R("zero");
+ if (args.length === 3) {
+ if (instr.mnemonic === "sll" && args[0] === zero && args[1] === zero) return new AsmInstruction("nop", []);
+ if (instr.mnemonic === "or" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2));
+ if (instr.mnemonic === "addu" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2));
+ if (instr.mnemonic === "daddu" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2));
+ if (instr.mnemonic === "nor" && args[1] === zero) return new AsmInstruction("not", [args[0], args[2]]);
+ if (instr.mnemonic === "nor" && args[2] === zero) return new AsmInstruction("not", [args[0], args[1]]);
+ if (instr.mnemonic === "addiu" && args[2] === new AsmLiteral(0)) return new AsmInstruction("move", args.slice(0, 2));
+ if (instr.mnemonic === "paddub" && args[2] === zero) return new AsmInstruction("move", args.slice(0, 2));
+ if (instr.mnemonic === "ori" && args[1] === zero && args[2] instanceof AsmLiteral) {
+ return new AsmInstruction("li", [args[0], new AsmLiteral(band(args[2].value, 0xffff))]);
+ }
+ if (instr.mnemonic === "addiu" && args[1] === zero && args[2] instanceof AsmLiteral) {
+ return new AsmInstruction("li", [args[0], new AsmLiteral(band(args[2].value + 0x8000, 0xffff) - 0x8000)]);
+ }
+ if (instr.mnemonic === "beq" && args[0] === zero && args[1] === zero) return new AsmInstruction("b", [args[2]]);
+ if (["bne", "beq", "beql", "bnel"].includes(instr.mnemonic) && args[1] === zero) {
+ const mn = instr.mnemonic.slice(0, 3) + "z" + instr.mnemonic.slice(3);
+ return new AsmInstruction(mn, [args[0], args[2]]);
+ }
+ }
+ if (args.length === 2) {
+ if (instr.mnemonic === "beqz" && args[0] === zero) return new AsmInstruction("b", [args[1]]);
+ if (instr.mnemonic === "lui" && args[1] instanceof AsmLiteral) return new AsmInstruction("li", [args[0], new AsmLiteral(band(args[1].value, 0xffff) * 0x10000)]);
+ if (instr.mnemonic === "jalr" && args[0] !== R("ra")) throw new DecompFailure("Two-argument form of jalr is not supported.");
+ if (["mult", "multu", "dmult", "dmultu", "madd", "maddu"].includes(instr.mnemonic)) return new AsmInstruction(instr.mnemonic, [zero, ...args]);
+ if (LENGTH_THREE.has(instr.mnemonic)) return this.normalize_instruction(new AsmInstruction(instr.mnemonic, [args[0], ...args]), asm_state);
+ }
+ if (args.length === 1) {
+ if (instr.mnemonic === "jalr") return new AsmInstruction("jalr", [R("ra"), args[0]]);
+ if (LENGTH_TWO.has(instr.mnemonic)) return this.normalize_instruction(new AsmInstruction(instr.mnemonic, [args[0], ...args]), asm_state);
+ }
+ return instr;
+ }
+
+ parse(mnemonic, args, meta) {
+ let inputs = [];
+ let clobbers = [];
+ let outputs = [];
+ let jump_target = null;
+ let function_target = null;
+ let has_delay_slot = false;
+ let is_branch_likely = false;
+ let is_conditional = false;
+ let is_return = false;
+ let is_load = false;
+ let is_store = false;
+ let eval_fn = null;
+ const cls = this;
+
+ const instr_str = String(new AsmInstruction(mnemonic, args));
+
+ const memory_sizes = { b: 1, h: 2, w: 4, d: 8, q: 16 };
+ const c1 = mnemonic.slice(1, 2);
+ const size = has(memory_sizes, c1) ? memory_sizes[c1] : null;
+
+ const alt_mult_pipeline = mnemonic.endsWith("1");
+ const base_mult_mnemonic = alt_mult_pipeline ? mnemonic.slice(0, -1) : mnemonic;
+ const lo_reg = alt_mult_pipeline ? R("lo1") : R("lo");
+ const hi_reg = alt_mult_pipeline ? R("hi1") : R("hi");
+
+ const make_memory_access = (arg) => {
+ pyassert(size !== null);
+ if (arg instanceof AsmAddressMode && arg.base === cls.stack_pointer_reg) {
+ const loc = StackLocation.from_offset(arg.addend);
+ if (loc === null) return [];
+ const at = (d) => new StackLocation(loc.offset + d, loc.symbolic_offset);
+ if (size === 16) return [loc, at(4), at(8), at(12)];
+ if (size === 8) return [loc, at(4)];
+ pyassert(size <= 4);
+ return [loc];
+ }
+ return [];
+ };
+
+ const unreachable_eval = () => {
+ throw new DecompFailure(`Instruction ${instr_str} should be replaced before eval`);
+ };
+
+ if (mnemonic === "jr" && args[0] === R("ra")) {
+ pyassert(args.length === 1);
+ inputs = [R("ra")];
+ is_return = true;
+ has_delay_slot = true;
+ } else if (mnemonic === "jr") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ inputs.push(args[0]);
+ jump_target = args[0];
+ is_conditional = true;
+ has_delay_slot = true;
+ eval_fn = (s, a) => s.set_switch_expr(a.reg(0));
+ } else if (mnemonic === "jal" || mnemonic === "bal") {
+ pyassert(args.length === 1);
+ inputs = [...cls.argument_regs];
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = args[0];
+ has_delay_slot = true;
+ eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs);
+ } else if (mnemonic === "jalr") {
+ pyassert(args.length === 2 && args[0] === R("ra") && args[1] instanceof Register);
+ inputs = [...cls.argument_regs];
+ inputs.push(args[1]);
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = args[1];
+ has_delay_slot = true;
+ eval_fn = (s, a) => s.make_function_call(a.reg(1), outputs);
+ } else if (mnemonic === "b" || mnemonic === "j") {
+ pyassert(args.length === 1);
+ jump_target = get_jump_target(args[0]);
+ has_delay_slot = true;
+ } else if (["beql", "bnel", "beqzl", "bnezl", "bgezl", "bgtzl", "blezl", "bltzl", "bc1tl", "bc1fl"].includes(mnemonic)) {
+ if (mnemonic === "beql" || mnemonic === "bnel") {
+ pyassert(args.length === 3 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs.push(args[0]);
+ inputs.push(args[1]);
+ } else if (mnemonic === "bc1tl" || mnemonic === "bc1fl") {
+ pyassert(args.length === 1);
+ inputs.push(R("condition_bit"));
+ } else {
+ pyassert(args.length === 2 && args[0] instanceof Register);
+ inputs.push(args[0]);
+ }
+ jump_target = get_jump_target(args[args.length - 1]);
+ has_delay_slot = true;
+ is_branch_likely = true;
+ is_conditional = true;
+ eval_fn = unreachable_eval;
+ } else if (["beq", "bne", "beqz", "bnez", "bgez", "bgtz", "blez", "bltz", "bc1t", "bc1f"].includes(mnemonic)) {
+ if (mnemonic === "beq" || mnemonic === "bne") {
+ pyassert(args.length === 3 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[0], args[1]];
+ } else if (mnemonic === "bc1t" || mnemonic === "bc1f") {
+ pyassert(args.length === 1);
+ inputs = [R("condition_bit")];
+ } else {
+ pyassert(args.length === 2 && args[0] instanceof Register);
+ inputs = [args[0]];
+ }
+ jump_target = get_jump_target(args[args.length - 1]);
+ has_delay_slot = true;
+ is_conditional = true;
+ eval_fn = (s, a) => {
+ let cond;
+ if (mnemonic === "bc1t" || mnemonic === "bc1f") {
+ cond = condition_from_expr(a.regs.get(R("condition_bit")));
+ if (mnemonic === "bc1f") cond = cond.negated();
+ } else cond = cls.instrs_branches[mnemonic](a);
+ s.set_branch_condition(cond);
+ };
+ } else if (mnemonic === "mfc0") {
+ pyassert(args.length === 2 && args[0] instanceof Register);
+ outputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(0), new ErrorExpr(`mfc0 ${a.raw_arg(1)}`));
+ } else if (mnemonic === "mtc0") {
+ pyassert(args.length === 2 && args[0] instanceof Register);
+ inputs = [args[0]];
+ eval_fn = (s) => s.write_statement(error_stmt(instr_str));
+ } else if (has(cls.instrs_no_dest, mnemonic)) {
+ pyassert(!args.some((a) => a instanceof AsmAddressMode));
+ inputs = args.filter((r) => r instanceof Register);
+ eval_fn = (s, a) => s.write_statement(cls.instrs_no_dest[mnemonic](a));
+ } else if (has(cls.instrs_store, mnemonic)) {
+ pyassert(args[0] instanceof Register);
+ outputs = make_memory_access(args[1]);
+ inputs = [args[0]];
+ is_store = true;
+ if (mnemonic === "sdc1") inputs.push(other_f64_reg(args[0]));
+ else if ((mnemonic === "sd" || mnemonic === "sq") && outputs.length) {
+ const n = outputs.length;
+ const base = inputs;
+ inputs = [];
+ for (let k = 0; k < n; k++) inputs.push(...base);
+ }
+ if (args[1] instanceof AsmAddressMode) inputs.push(args[1].base);
+ eval_fn = (s, a) => {
+ const store = cls.instrs_store[mnemonic](a);
+ if (store !== null) s.store_memory(store, a.reg_ref(0));
+ };
+ } else if (mnemonic === "mtc1") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[0]];
+ outputs = [args[1]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), a.reg(0));
+ } else if (has(cls.instrs_destination_first, mnemonic)) {
+ pyassert(args[0] instanceof Register);
+ outputs = [args[0]];
+ const mn_parts = mnemonic.split(".");
+ if (["add.d", "sub.d", "neg.d", "abs.d", "sqrt.d", "div.d", "mul.d", "mov.d"].includes(mnemonic)) {
+ pyassert(2 <= args.length && args.length <= 3);
+ for (const reg of args.slice(1)) {
+ pyassert(reg instanceof Register);
+ inputs.push(reg, other_f64_reg(reg));
+ }
+ outputs.push(other_f64_reg(args[0]));
+ } else if (mn_parts[0] === "cvt" || mn_parts[0] === "trunc") {
+ pyassert(args.length === 2 && args[1] instanceof Register);
+ if (mn_parts[2] === "d") inputs = [args[1], other_f64_reg(args[1])];
+ else inputs = [args[1]];
+ if (mn_parts[1] === "d") outputs.push(other_f64_reg(args[0]));
+ } else if (mnemonic.startsWith("l") && size !== null) {
+ pyassert(args.length === 2);
+ is_load = true;
+ inputs = make_memory_access(args[1]);
+ if (args[1] instanceof AsmAddressMode) inputs.push(args[1].base);
+ if (mnemonic === "lwr") inputs.push(args[0]);
+ else if (mnemonic === "ldc1") outputs.push(other_f64_reg(args[0]));
+ } else if (mnemonic === "la" && args[1] instanceof AsmAddressMode) {
+ inputs = [args[1].base];
+ } else if (base_mult_mnemonic === "mfhi") {
+ pyassert(args.length === 1);
+ inputs = [hi_reg];
+ } else if (base_mult_mnemonic === "mflo") {
+ pyassert(args.length === 1);
+ inputs = [lo_reg];
+ } else if (mnemonic === "movn" || mnemonic === "movz") {
+ pyassert(args.length === 3 && args[1] instanceof Register && args[2] instanceof Register);
+ inputs = [args[0], args[1], args[2]];
+ } else {
+ pyassert(!args.some((a) => a instanceof AsmAddressMode));
+ inputs = args.slice(1).filter((r) => r instanceof Register);
+ }
+ eval_fn = (s, a) => {
+ const target = a.reg_ref(0);
+ s.set_reg(target, cls.instrs_destination_first[mnemonic](a));
+ if (outputs.length === 2) s.set_reg(other_f64_reg(target), new SecondF64Half());
+ };
+ } else if (has(cls.instrs_float_comp, mnemonic)) {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ if (mnemonic.endsWith(".d")) inputs = [args[0], other_f64_reg(args[0]), args[1], other_f64_reg(args[1])];
+ else inputs = [args[0], args[1]];
+ outputs = [R("condition_bit")];
+ eval_fn = (s, a) => s.set_reg(R("condition_bit"), cls.instrs_float_comp[mnemonic](a));
+ } else if (has(cls.instrs_hi_lo, base_mult_mnemonic)) {
+ pyassert(args.length === 3 && args[0] instanceof Register && args[1] instanceof Register && args[2] instanceof Register);
+ inputs = [args[1], args[2]];
+ if (base_mult_mnemonic === "madd" || base_mult_mnemonic === "maddu") inputs.push(lo_reg);
+ outputs = [hi_reg, lo_reg];
+ if (args[0] !== R("zero")) outputs.push(args[0]);
+ eval_fn = (s, a) => {
+ const [hi, lo] = cls.instrs_hi_lo[base_mult_mnemonic](a, lo_reg);
+ s.set_reg(hi_reg, hi);
+ s.set_reg(lo_reg, lo);
+ const copy_lo_to = a.reg_ref(0);
+ if (copy_lo_to !== R("zero")) s.set_reg(copy_lo_to, lo);
+ };
+ } else if (base_mult_mnemonic === "mtlo" || base_mult_mnemonic === "mthi") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ inputs = [args[0]];
+ const output_reg = base_mult_mnemonic === "mthi" ? hi_reg : lo_reg;
+ outputs = [output_reg];
+ eval_fn = (s, a) => s.set_reg(output_reg, a.reg(0));
+ } else if (cls.instrs_ignore.has(mnemonic)) {
+ // pass
+ } else {
+ let maybe_dest_first;
+ if (args.length && args[0] instanceof Register) {
+ inputs = args.slice(1).filter((r) => r instanceof Register);
+ outputs = [args[0]];
+ maybe_dest_first = true;
+ } else maybe_dest_first = false;
+ eval_fn = (s, a) => {
+ const error = new ErrorExpr(`unknown instruction: ${instr_str}`);
+ if (maybe_dest_first) s.set_reg_real(a.reg_ref(0), error, { emit_exactly_once: true });
+ else s.write_statement(new ExprStmt(error));
+ };
+ }
+
+ return new Instruction({
+ mnemonic,
+ args,
+ meta,
+ inputs,
+ clobbers,
+ outputs,
+ jump_target,
+ function_target,
+ has_delay_slot,
+ is_branch_likely,
+ is_conditional,
+ is_return,
+ is_load,
+ is_store,
+ eval_fn,
+ });
+ }
+
+ arg_name(loc) {
+ pyassert(loc.offset !== null);
+ return `arg${floordiv(loc.offset, 4)}`;
+ }
+
+ default_function_abi_candidate_slots() {
+ return [
+ new AbiArgSlot(new ArgLoc(0, 0, R("f12")), Type.floatish()),
+ new AbiArgSlot(new ArgLoc(4, 1, R("f13")), Type.floatish()),
+ new AbiArgSlot(new ArgLoc(4, 2, R("f14")), Type.floatish()),
+ new AbiArgSlot(new ArgLoc(12, 3, R("f15")), Type.floatish()),
+ new AbiArgSlot(new ArgLoc(0, 4, R("a0")), Type.intptr()),
+ new AbiArgSlot(new ArgLoc(4, 5, R("a1")), Type.any_reg()),
+ new AbiArgSlot(new ArgLoc(8, 6, R("a2")), Type.any_reg()),
+ new AbiArgSlot(new ArgLoc(12, 7, R("a3")), Type.any_reg()),
+ ];
+ }
+
+ /** Compute stack positions/registers used by a function according to the o32 ABI. */
+ function_abi(fn_sig, likely_regs, { for_call }) {
+ const known_slots = [];
+ let candidate_slots = [];
+ if (fn_sig.params_known) {
+ let offset = 0;
+ let only_floats = true;
+ if (fn_sig.return_type.is_struct()) {
+ known_slots.push(new AbiArgSlot(new ArgLoc(0, 0, R("a0")), Type.ptr(fn_sig.return_type), { name: "__return__", comment: "return" }));
+ offset = 4;
+ only_floats = false;
+ }
+ fn_sig.params.forEach((param, ind) => {
+ const param_type = param.type.decay();
+ let [size, align] = param_type.get_parameter_size_align_bytes();
+ size = band(size + 3, -4);
+ only_floats = only_floats && param_type.is_float();
+ offset = band(offset + align - 1, -align);
+ const name = param.name;
+ let reg2;
+ if (ind < 2 && only_floats) {
+ reg2 = R(ind === 0 ? "f12" : "f14");
+ const is_double = param_type.is_float() && param_type.get_size_bits() === 64;
+ known_slots.push(new AbiArgSlot(new ArgLoc(offset, floordiv(offset, 4), reg2), param_type, { name }));
+ if (is_double && !for_call) {
+ const name2 = name ? `${name}_lo` : null;
+ reg2 = R(ind === 0 ? "f13" : "f15");
+ known_slots.push(new AbiArgSlot(new ArgLoc(offset + 4, floordiv(offset, 4) + 1, reg2), Type.any_reg(), { name: name2 }));
+ }
+ } else {
+ for (let i = floordiv(offset, 4); i < floordiv(offset + size, 4); i++) {
+ const unk_offset = 4 * i - offset;
+ reg2 = i < 4 ? R(`a${i}`) : null;
+ let name2, sub_type, comment;
+ if (size > 4) {
+ name2 = name ? `${name}_unk${format(unk_offset, "X")}` : null;
+ sub_type = Type.any();
+ comment = `${param_type}+${format(unk_offset, "#x")}`;
+ } else {
+ pyassert(unk_offset === 0);
+ name2 = name;
+ sub_type = param_type;
+ comment = null;
+ }
+ known_slots.push(new AbiArgSlot(new ArgLoc(4 * i, i, reg2), sub_type, { name: name2, comment }));
+ }
+ }
+ offset += size;
+ });
+ if (fn_sig.is_variadic) {
+ for (let i = floordiv(offset, 4); i < 4; i++) candidate_slots.push(new AbiArgSlot(new ArgLoc(i * 4, i, R(`a${i}`)), Type.any_reg()));
+ }
+ } else {
+ candidate_slots = this.default_function_abi_candidate_slots();
+ }
+
+ const valid_extra_regs = new Set(known_slots.filter((slot) => slot.loc.reg !== null).map((slot) => slot.loc.reg));
+ const possible_slots = [];
+ for (const slot of candidate_slots) {
+ const reg = slot.loc.reg;
+ if (reg === null || !likely_regs.has(reg)) continue;
+ let require = null;
+ if (slot === candidate_slots[0]) {
+ // pass
+ } else if (reg === R("f13") || reg === R("f14")) require = ["f12"];
+ else if (reg === R("f15")) require = ["f14"];
+ else if (reg === R("a1")) require = ["a0", "f12"];
+ else if (reg === R("a2")) require = ["a1", "f13", "f14"];
+ else if (reg === R("a3")) require = ["a2"];
+ if (require && !require.some((r) => valid_extra_regs.has(R(r)))) continue;
+ valid_extra_regs.add(reg);
+ if ((reg === R("f13") || reg === R("f15")) && for_call) continue;
+ if (!likely_regs.get(reg)) continue;
+ possible_slots.push(slot);
+ }
+ return new Abi({ arg_slots: known_slots, possible_slots });
+ }
+
+ function_return(expr) {
+ return new Map([
+ [R("f0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.floatish() })],
+ [R("v0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.intptr() })],
+ [R("v1"), as_u32(new Cast(expr, { reinterpret: true, silent: false, type: Type.u64() }))],
+ [R("f1"), new SecondF64Half()],
+ ]);
+ }
+}
+
+{
+ const argument_regs = regs(["a0", "a1", "a2", "a3", "f12", "f13", "f14", "f15"]);
+ const simple_temp_regs = regs([
+ "v0", "v1", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f16", "f17", "f18", "f19",
+ ]);
+ const temp_regs = [...argument_regs, ...simple_temp_regs, ...regs(["at", "hi", "lo", "lo1", "hi1", "condition_bit"])];
+ const saved_regs = regs(["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "ra", "31", "fp", "gp"]);
+ const stack_pointer_reg = R("sp");
+ const aliased_gp_regs = { s8: R("fp"), r0: R("zero") };
+ const o32abi_float_regs = {};
+ const fnames = ["fv0", "fv0f", "fv1", "fv1f", "ft0", "ft0f", "ft1", "ft1f", "ft2", "ft2f", "ft3", "ft3f", "fa0", "fa0f", "fa1", "fa1f", "ft4", "ft4f", "ft5", "ft5f", "fs0", "fs0f", "fs1", "fs1f", "fs2", "fs2f", "fs3", "fs3f", "fs4", "fs4f", "fs5", "fs5f"];
+ fnames.forEach((n, i) => (o32abi_float_regs[n] = R(`f${i}`)));
+
+ const instrs_store = {
+ sb: (a) => make_store(a, Type.int_of_size(8)),
+ sh: (a) => make_store(a, Type.int_of_size(16)),
+ sw: (a) => make_store(a, Type.reg32({ likely_float: false })),
+ sd: (a) => make_store(a, Type.reg64({ likely_float: false })),
+ sq: (a) => make_store(a, Type.reg128()),
+ swl: (a) => handle_swl(a),
+ swr: (a) => handle_swr(a),
+ swc1: (a) => make_store(a, Type.reg32({ likely_float: true })),
+ sdc1: (a) => make_store(a, Type.reg64({ likely_float: true })),
+ };
+ const instrs_branches = {
+ beq: (a) => BinaryOp.icmp(a.reg(0), "==", a.reg(1)),
+ bne: (a) => BinaryOp.icmp(a.reg(0), "!=", a.reg(1)),
+ beqz: (a) => BinaryOp.icmp(a.reg(0), "==", new Literal(0)),
+ bnez: (a) => BinaryOp.icmp(a.reg(0), "!=", new Literal(0)),
+ blez: (a) => BinaryOp.scmp(a.reg(0), "<=", new Literal(0)),
+ bgtz: (a) => BinaryOp.scmp(a.reg(0), ">", new Literal(0)),
+ bltz: (a) => handle_bgez(a).negated(),
+ bgez: (a) => handle_bgez(a),
+ };
+ const trap = (op, cmp, imm) => (a) => void_fn_op("M2C_TRAP_IF", [BinaryOp[cmp](a.reg(0), op, imm ? a.s16_imm(1) : a.reg(1))]);
+ const instrs_no_dest = {
+ teq: trap("==", "icmp", false),
+ tne: trap("!=", "icmp", false),
+ tlt: trap("<", "scmp", false),
+ tltu: trap("<", "ucmp", false),
+ tge: trap(">=", "scmp", false),
+ tgeu: trap(">=", "ucmp", false),
+ teqi: trap("==", "icmp", true),
+ tnei: trap("!=", "icmp", true),
+ tlti: trap("<", "scmp", true),
+ tltiu: trap("<", "ucmp", true),
+ tgei: trap(">=", "scmp", true),
+ tgeiu: trap(">=", "ucmp", true),
+ break: (a) => void_fn_op("M2C_BREAK", a.count() >= 1 ? [a.s16_imm(0)] : []),
+ sync: () => void_fn_op("M2C_SYNC", []),
+ "trapuv.fictive": () => new CommentStmt("code compiled with -trapuv"),
+ "memcpy.aligned.fictive": (a) => void_fn_op("M2C_MEMCPY_ALIGNED", [a.reg(0), a.reg(1), a.s16_imm(2)]),
+ "memcpy.unaligned.fictive": (a) => void_fn_op("M2C_MEMCPY_UNALIGNED", [a.reg(0), a.reg(1), a.s16_imm(2)]),
+ };
+ const fc = (op, neg) => (a) => {
+ const c = BinaryOp.fcmp(a.reg(0), op, a.reg(1));
+ return neg ? c.negated() : c;
+ };
+ const dc = (op, neg) => (a) => {
+ const c = BinaryOp.dcmp(a.dreg(0), op, a.dreg(1));
+ return neg ? c.negated() : c;
+ };
+ const instrs_float_comp = {};
+ for (const [suf, mk] of [
+ ["s", fc],
+ ["d", dc],
+ ]) {
+ Object.assign(instrs_float_comp, {
+ [`c.eq.${suf}`]: mk("==", false),
+ [`c.olt.${suf}`]: mk("<", false),
+ [`c.oge.${suf}`]: mk(">=", false),
+ [`c.ole.${suf}`]: mk("<=", false),
+ [`c.ogt.${suf}`]: mk(">", false),
+ [`c.neq.${suf}`]: mk("==", true),
+ [`c.uge.${suf}`]: mk("<", true),
+ [`c.ult.${suf}`]: mk(">=", true),
+ [`c.ugt.${suf}`]: mk("<=", true),
+ [`c.ule.${suf}`]: mk(">", true),
+ [`c.seq.${suf}`]: mk("==", false),
+ [`c.lt.${suf}`]: mk("<", false),
+ [`c.ge.${suf}`]: mk(">=", false),
+ [`c.le.${suf}`]: mk("<=", false),
+ [`c.gt.${suf}`]: mk(">", false),
+ [`c.sne.${suf}`]: mk("==", true),
+ [`c.nle.${suf}`]: mk("<=", true),
+ [`c.nlt.${suf}`]: mk("<", true),
+ [`c.nge.${suf}`]: mk(">=", true),
+ [`c.ngt.${suf}`]: mk(">", true),
+ });
+ }
+ const madd = (name) => (a, lo_reg) => [new ErrorExpr(`${name} top half`), handle_add_real(a.regs.get(lo_reg), BinaryOp.int(a.reg(1), "*", a.reg(2)), a)];
+ const instrs_hi_lo = {
+ div: (a) => [BinaryOp.sint(a.reg(1), "%", a.reg(2)), BinaryOp.sint(a.reg(1), "/", a.reg(2))],
+ divu: (a) => [BinaryOp.uint(a.reg(1), "%", a.reg(2)), BinaryOp.uint(a.reg(1), "/", a.reg(2))],
+ ddiv: (a) => [BinaryOp.s64(a.reg(1), "%", a.reg(2)), BinaryOp.s64(a.reg(1), "/", a.reg(2))],
+ ddivu: (a) => [BinaryOp.u64(a.reg(1), "%", a.reg(2)), BinaryOp.u64(a.reg(1), "/", a.reg(2))],
+ mult: (a) => [fold_divmod(BinaryOp.int(a.reg(1), "MULT_HI", a.reg(2))), BinaryOp.int(a.reg(1), "*", a.reg(2))],
+ multu: (a) => [fold_divmod(BinaryOp.int(a.reg(1), "MULTU_HI", a.reg(2))), BinaryOp.int(a.reg(1), "*", a.reg(2))],
+ dmult: (a) => [BinaryOp.int64(a.reg(1), "DMULT_HI", a.reg(2)), BinaryOp.int64(a.reg(1), "*", a.reg(2))],
+ dmultu: (a) => [BinaryOp.int64(a.reg(1), "DMULTU_HI", a.reg(2)), BinaryOp.int64(a.reg(1), "*", a.reg(2))],
+ madd: madd("madd"),
+ maddu: madd("maddu"),
+ };
+ const sub = (a) => fold_mul_chains(fold_divmod(BinaryOp.intptr(a.reg(1), "-", a.reg(2))));
+ const instrs_destination_first = {
+ slt: (a) => BinaryOp.scmp(a.reg(1), "<", a.reg(2)),
+ slti: (a) => BinaryOp.scmp(a.reg(1), "<", a.s16_imm(2)),
+ sltu: (a) => handle_sltu(a),
+ sltiu: (a) => handle_sltiu(a),
+ addi: (a) => handle_addi_mips(a),
+ addiu: (a) => handle_addi_mips(a),
+ add: (a) => handle_add(a),
+ addu: (a) => handle_add(a),
+ sub,
+ subu: sub,
+ negu: (a) => fold_mul_chains(UnaryOp.sint("-", a.reg(1))),
+ neg: (a) => fold_mul_chains(UnaryOp.sint("-", a.reg(1))),
+ "div.fictive": (a) => BinaryOp.sint(a.reg(1), "/", a.full_imm(2)),
+ "mod.fictive": (a) => BinaryOp.sint(a.reg(1), "%", a.full_imm(2)),
+ daddi: (a) => handle_addi_mips(a),
+ daddiu: (a) => handle_addi_mips(a),
+ daddu: (a) => handle_add(a),
+ dsubu: (a) => fold_mul_chains(BinaryOp.intptr(a.reg(1), "-", a.reg(2))),
+ dnegu: (a) => fold_mul_chains(new UnaryOp("-", as_s64(a.reg(1)), { type: Type.s64() })),
+ dneg: (a) => fold_mul_chains(new UnaryOp("-", as_s64(a.reg(1)), { type: Type.s64() })),
+ mfhi: (a) => a.regs.get(R("hi")),
+ mflo: (a) => a.regs.get(R("lo")),
+ mfhi1: (a) => a.regs.get(R("hi1")),
+ mflo1: (a) => a.regs.get(R("lo1")),
+ "add.s": (a) => handle_add_float(a),
+ "sub.s": (a) => BinaryOp.f32(a.reg(1), "-", a.reg(2)),
+ "neg.s": (a) => new UnaryOp("-", as_f32(a.reg(1)), { type: Type.f32() }),
+ "abs.s": (a) => fn_op("fabsf", [as_f32(a.reg(1))], Type.f32()),
+ "sqrt.s": (a) => fn_op("sqrtf", [as_f32(a.reg(1))], Type.f32()),
+ "div.s": (a) => BinaryOp.f32(a.reg(1), "/", a.reg(2)),
+ "mul.s": (a) => BinaryOp.f32(a.reg(1), "*", a.reg(2)),
+ "add.d": (a) => handle_add_double(a),
+ "sub.d": (a) => BinaryOp.f64(a.dreg(1), "-", a.dreg(2)),
+ "neg.d": (a) => new UnaryOp("-", as_f64(a.dreg(1)), { type: Type.f64() }),
+ "abs.d": (a) => fn_op("fabs", [as_f64(a.dreg(1))], Type.f64()),
+ "sqrt.d": (a) => fn_op("sqrt", [as_f64(a.dreg(1))], Type.f64()),
+ "div.d": (a) => BinaryOp.f64(a.dreg(1), "/", a.dreg(2)),
+ "mul.d": (a) => BinaryOp.f64(a.dreg(1), "*", a.dreg(2)),
+ "cvt.d.s": (a) => handle_convert(a.reg(1), Type.f64(), Type.f32()),
+ "cvt.d.w": (a) => handle_convert(a.reg(1), Type.f64(), Type.intish()),
+ "cvt.s.d": (a) => handle_convert(a.dreg(1), Type.f32(), Type.f64()),
+ "cvt.s.w": (a) => handle_convert(a.reg(1), Type.f32(), Type.intish()),
+ "cvt.w.d": (a) => handle_convert(a.dreg(1), Type.s32(), Type.f64()),
+ "cvt.w.s": (a) => handle_convert(a.reg(1), Type.s32(), Type.f32()),
+ "cvt.s.u.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.u32()),
+ "cvt.u.d.fictive": (a) => handle_convert(a.dreg(1), Type.u32(), Type.f64()),
+ "cvt.u.s.fictive": (a) => handle_convert(a.reg(1), Type.u32(), Type.f32()),
+ "trunc.w.s": (a) => handle_convert(a.reg(1), Type.s32(), Type.f32()),
+ "trunc.w.d": (a) => handle_convert(a.dreg(1), Type.s32(), Type.f64()),
+ ori: (a) => handle_or(a.reg(1), a.u16_imm(2)),
+ and: (a) => BinaryOp.int(a.reg(1), "&", a.reg(2)),
+ or: (a) => BinaryOp.int(a.reg(1), "|", a.reg(2)),
+ not: (a) => new UnaryOp("~", a.reg(1), { type: Type.intish() }),
+ nor: (a) => new UnaryOp("~", BinaryOp.int(a.reg(1), "|", a.reg(2)), { type: Type.intish() }),
+ xor: (a) => BinaryOp.int(a.reg(1), "^", a.reg(2)),
+ andi: (a) => BinaryOp.int(a.reg(1), "&", a.u16_imm(2)),
+ xori: (a) => handle_xor(a.reg(1), a.u16_imm(2)),
+ sll: (a) => fold_mul_chains(BinaryOp.int(a.reg(1), "<<", a.s16_imm(2))),
+ sllv: (a) => fold_mul_chains(BinaryOp.int(a.reg(1), "<<", a.reg(2))),
+ srl: (a) => fold_divmod(BinaryOp.ushift(a.reg(1), ">>", a.s16_imm(2))),
+ srlv: (a) => fold_divmod(BinaryOp.ushift(a.reg(1), ">>", a.reg(2))),
+ sra: (a) => handle_shift_right(a, { signed: true }),
+ srav: (a) => fold_divmod(BinaryOp.sshift(a.reg(1), ">>", a.reg(2))),
+ dsll: (a) => fold_mul_chains(BinaryOp.int64(a.reg(1), "<<", as_intish(a.s16_imm(2)))),
+ dsll32: (a) => fold_mul_chains(BinaryOp.int64(a.reg(1), "<<", imm_add_32(a.s16_imm(2)))),
+ dsllv: (a) => BinaryOp.int64(a.reg(1), "<<", as_intish(a.reg(2))),
+ dsrl: (a) => new BinaryOp(as_u64(a.reg(1)), ">>", as_intish(a.s16_imm(2)), { type: Type.u64() }),
+ dsrl32: (a) => new BinaryOp(as_u64(a.reg(1)), ">>", imm_add_32(a.s16_imm(2)), { type: Type.u64() }),
+ dsrlv: (a) => new BinaryOp(as_u64(a.reg(1)), ">>", as_intish(a.reg(2)), { type: Type.u64() }),
+ dsra: (a) => new BinaryOp(as_s64(a.reg(1)), ">>", as_intish(a.s16_imm(2)), { type: Type.s64() }),
+ dsra32: (a) => new BinaryOp(as_s64(a.reg(1)), ">>", imm_add_32(a.s16_imm(2)), { type: Type.s64() }),
+ dsrav: (a) => new BinaryOp(as_s64(a.reg(1)), ">>", as_intish(a.reg(2)), { type: Type.s64() }),
+ move: (a) => a.reg(1),
+ "move.fictive": (a) => a.reg(1),
+ mfc1: (a) => a.reg(1),
+ "mov.s": (a) => a.reg(1),
+ "mov.d": (a) => as_f64(a.dreg(1)),
+ movn: (a) => handle_conditional_move(a, true),
+ movz: (a) => handle_conditional_move(a, false),
+ cfc1: () => new ErrorExpr("cfc1"),
+ li: (a) => a.full_imm(1),
+ lui: (a) => load_upper(a),
+ la: (a) => handle_la(a),
+ lb: (a) => handle_load(a, Type.s8()),
+ lbu: (a) => handle_load(a, Type.u8()),
+ lh: (a) => handle_load(a, Type.s16()),
+ lhu: (a) => handle_load(a, Type.u16()),
+ lw: (a) => handle_lw(a),
+ ld: (a) => handle_load(a, Type.reg64({ likely_float: false })),
+ lq: (a) => handle_load(a, Type.reg128()),
+ lwu: (a) => handle_load(a, Type.u32()),
+ lwc1: (a) => handle_load(a, Type.reg32({ likely_float: true })),
+ ldc1: (a) => handle_load(a, Type.reg64({ likely_float: true })),
+ lwl: (a) => handle_lwl(a),
+ lwr: (a) => handle_lwr(a),
+ seb: (a) => as_type(a.reg(1), Type.s8(), false),
+ seh: (a) => as_type(a.reg(1), Type.s16(), false),
+ };
+
+ Object.assign(MipsArch.prototype, {
+ arch: Target.ArchEnum.MIPS,
+ re_comment: "[#;].*",
+ supports_dollar_regs: true,
+ has_delay_slots: true,
+ home_space_size: 0x10,
+ stack_pointer_reg,
+ frame_pointer_regs: [R("fp")],
+ return_address_reg: R("ra"),
+ base_return_regs: [
+ [R("v0"), false],
+ [R("f0"), true],
+ ],
+ all_return_regs: regs(["v0", "v1", "f0", "f1"]),
+ argument_regs,
+ simple_temp_regs,
+ temp_regs,
+ saved_regs,
+ all_regs: [...saved_regs, ...temp_regs, stack_pointer_reg, R("zero")],
+ aliased_gp_regs,
+ o32abi_float_regs,
+ aliased_regs: { ...o32abi_float_regs, ...aliased_gp_regs },
+ asm_patterns: [
+ new DivPattern(),
+ new DivuPattern(),
+ new DivP2Pattern1(),
+ new DivP2Pattern2(),
+ new Div2S16Pattern(),
+ new Div2S32Pattern1(),
+ new Div2S32Pattern2(),
+ new ModP2Pattern1(),
+ new ModP2Pattern2(),
+ new UtfPattern(),
+ new FtuPattern(),
+ new Mips1DoubleLoadStorePattern(),
+ new GccSqrtPatternJal(),
+ new GccSqrtPatternJalr(),
+ new TrapuvPattern(),
+ new SetGpPattern(),
+ new AlignedMemcpyPattern(),
+ new UnalignedMemcpyPattern(),
+ new GpJumpPattern(),
+ new OriSpPattern(),
+ new TailCallPattern(),
+ ],
+ instrs_ignore: new Set(["ctc1", "nop"]),
+ instrs_store,
+ instrs_branches,
+ instrs_no_dest,
+ instrs_float_comp,
+ instrs_hi_lo,
+ instrs_destination_first,
+ });
+}
+
+export class MipseeArch extends MipsArch {
+ default_function_abi_candidate_slots() {
+ const out = [];
+ for (let i = 0; i < 8; i++) out.push(new AbiArgSlot(new ArgLoc(null, i, R(`a${i}`)), Type.intptr()));
+ for (let i = 0; i < 8; i++) out.push(new AbiArgSlot(new ArgLoc(null, 8 + i, R(`f${12 + i}`)), Type.floatish()));
+ return out;
+ }
+
+ arg_name(loc) {
+ if (loc.offset !== null) return `arg_sp${format_hex(loc.offset)}`;
+ pyassert(loc.reg !== null);
+ const reg_num = int_(loc.reg.register_name.slice(1));
+ if (loc.reg.register_name.startsWith("a")) return `arg${reg_num}`;
+ return `fparg${reg_num - 12}`;
+ }
+
+ function_abi(fn_sig, likely_regs, { for_call }) {
+ void for_call;
+ const known_slots = [];
+ let candidate_slots = [];
+ const intptr_regs = this.argument_regs.filter((r) => r.register_name[0] !== "f");
+ const float_regs = this.argument_regs.filter((r) => r.register_name[0] === "f");
+
+ if (fn_sig.params_known) {
+ let ind = 0;
+ let stack_offset = 0;
+ for (const param of fn_sig.params) {
+ const param_type = param.type.decay();
+ let reg = null;
+ let offset = null;
+ const pool = param_type.is_float() ? float_regs : intptr_regs;
+ if (pool.length) reg = pool.shift();
+ else {
+ offset = stack_offset;
+ stack_offset += 4;
+ }
+ known_slots.push(new AbiArgSlot(new ArgLoc(offset, ind, reg), param_type, { name: param.name }));
+ ind += 1;
+ }
+ if (fn_sig.is_variadic) {
+ for (const reg of intptr_regs) {
+ candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.intptr()));
+ ind += 1;
+ }
+ for (const reg of float_regs) {
+ candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.floatish()));
+ ind += 1;
+ }
+ }
+ } else {
+ candidate_slots = this.default_function_abi_candidate_slots();
+ }
+
+ const possible_slots = [];
+ const valid_extra_regs = new Set(known_slots.filter((slot) => slot.loc.reg !== null).map((slot) => slot.loc.reg));
+ for (const slot of candidate_slots) {
+ const reg = slot.loc.reg;
+ if (reg === null || !likely_regs.has(reg)) continue;
+ if (slot === candidate_slots[0]) {
+ // pass
+ } else {
+ const regname = reg.register_name;
+ const prev_reg = R(`${regname[0]}${int_(regname.slice(1)) - 1}`);
+ if (this.argument_regs.includes(prev_reg) && !valid_extra_regs.has(prev_reg)) continue;
+ }
+ valid_extra_regs.add(reg);
+ if (!likely_regs.get(reg)) continue;
+ possible_slots.push(slot);
+ }
+ return new Abi({ arg_slots: known_slots, possible_slots });
+ }
+}
+
+{
+ const argument_regs = regs(["a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19"]);
+ const simple_temp_regs = regs(["v0", "v1", "t4", "t5", "t6", "t7", "t8", "t9", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11"]);
+ const temp_regs = [...argument_regs, ...simple_temp_regs, ...regs(["at", "hi", "lo", "condition_bit"])];
+ const saved_regs = regs(["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "ra", "31", "fp", "gp"]);
+ const stack_pointer_reg = R("sp");
+ const aliased_gp_regs = { s8: R("fp"), r0: R("zero") };
+ const eabi64_float_regs = {};
+ ["fv0", "fv1", "ft0", "ft1", "ft2", "ft3", "ft4", "ft5", "ft6", "ft7", "ft8", "ft9", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "fs0", "fs1", "fs2", "fs3", "fs4", "fs5", "fs6", "fs7", "fs8", "fs9", "fs10", "fs11"].forEach(
+ (n, i) => (eabi64_float_regs[n] = R(`f${i}`)),
+ );
+ const numeric_names = ["zero", "at", "v0", "v1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra"];
+ const numeric_regs = {};
+ numeric_names.forEach((n, i) => (numeric_regs[String(i)] = R(n)));
+ Object.assign(MipseeArch.prototype, {
+ stack_pointer_reg,
+ home_space_size: 0,
+ argument_regs,
+ simple_temp_regs,
+ temp_regs,
+ saved_regs,
+ all_regs: [...saved_regs, ...temp_regs, stack_pointer_reg, R("zero")],
+ aliased_gp_regs,
+ eabi64_float_regs,
+ numeric_regs,
+ aliased_regs: { ...eabi64_float_regs, ...aliased_gp_regs, ...numeric_regs },
+ });
+}
diff --git a/packages/romdev-m2c/src/arch_ppc.js b/packages/romdev-m2c/src/arch_ppc.js
new file mode 100644
index 00000000..7e3704fe
--- /dev/null
+++ b/packages/romdev-m2c/src/arch_ppc.js
@@ -0,0 +1,1298 @@
+// Port of m2c/arch_ppc.py
+import { DecompFailure } from "./error.js";
+import { IrPattern } from "./ir_pattern.js";
+import { Target } from "./options.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, BinOp, Macro, Register, get_jump_target } from "./asm_instruction.js";
+import { Instruction, InstructionMeta, StackLocation } from "./instruction.js";
+import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js";
+import {
+ Abi,
+ AbiArgSlot,
+ AddressMode,
+ Arch,
+ ArgLoc,
+ BinaryOp,
+ Cast,
+ ErrorExpr,
+ ExprStmt,
+ Literal,
+ TernaryOp,
+ UnaryOp,
+ as_intish,
+ as_u32,
+ as_type,
+ format_hex,
+} from "./translate.js";
+import {
+ add_imm,
+ carry_add_to,
+ carry_sub_from,
+ error_stmt,
+ fn_op,
+ fold_divmod,
+ fold_mul_chains,
+ handle_add,
+ handle_add_double,
+ handle_add_float,
+ handle_add_real,
+ handle_addi,
+ handle_addis,
+ handle_cmpnez,
+ handle_convert,
+ handle_load,
+ handle_loadx,
+ handle_or,
+ handle_rlwimi,
+ handle_rlwinm,
+ handle_rlwnm,
+ handle_shift_right,
+ handle_xor,
+ load_upper,
+ make_store,
+ make_storex,
+ void_fn_op,
+} from "./evaluate.js";
+import { InstrRef } from "./flow_graph.js";
+import { Type } from "./types.js";
+import { band, has, int_, lstrip, pyassert, pyeq, repr, rstrip } from "./py.js";
+
+/**
+ * For floating point, `x <= y` and `x >= y` use `cror` to OR together the `cr0_eq`
+ * bit with either `cr0_lt` or `cr0_gt`.
+ */
+class FcmpoCrorPattern extends SimpleAsmPattern {
+ pattern = make_pattern("fcmpo $cr0, $x, $y", "cror 2, N, 2");
+
+ replace(m) {
+ const fcmpo = m.body[0];
+ pyassert(fcmpo instanceof Instruction);
+ if (m.literals.get("N") === 0) return new Replacement([new AsmInstruction("fcmpo.lte.fictive", fcmpo.args)], m.body.length);
+ else if (m.literals.get("N") === 1) return new Replacement([new AsmInstruction("fcmpo.gte.fictive", fcmpo.args)], m.body.length);
+ return null;
+ }
+}
+
+/** Comparison results extracted as ints. */
+class MfcrPattern extends SimpleAsmPattern {
+ pattern = make_pattern("mfcr $x", "rlwinm $x, $x, N, 31, 31");
+
+ replace(m) {
+ const x = m.regs.get("x");
+ const n = m.literals.get("N");
+ let reg;
+ if (n === 1) reg = new Register("cr0_lt");
+ else if (n === 2) reg = new Register("cr0_gt");
+ else if (n === 3) reg = new Register("cr0_eq");
+ else if (n === 4) reg = new Register("cr0_so");
+ else return null;
+ return new Replacement([new AsmInstruction("move.fictive", [x, reg])], m.body.length);
+ }
+}
+
+/** `return fn(...);` emitted as `b fn` instead of `bl fn; blr`. */
+class TailCallPattern extends AsmPattern {
+ match(matcher) {
+ if (matcher.index !== matcher.input.length - 1) return null;
+ const instr = matcher.input[matcher.index];
+ if (instr instanceof Instruction && instr.mnemonic === "b" && instr.args[0] instanceof AsmGlobalSymbol && !matcher.is_local_label(instr.args[0].symbol_name)) {
+ return new Replacement([new AsmInstruction("bl", instr.args), new AsmInstruction("blr", [])], 1);
+ }
+ return null;
+ }
+}
+
+/** Expand calls to MWCC's built-in `_{save,rest}{gpr,fpr}_` functions into register saves/restores. */
+class SaveRestoreRegsFnPattern extends AsmPattern {
+ match(matcher) {
+ const bl = matcher.input[matcher.index];
+ if (!(bl instanceof Instruction) || bl.mnemonic !== "bl" || !(bl.args[0] instanceof AsmGlobalSymbol)) return null;
+ const parts = bl.args[0].symbol_name.split("_");
+ if (parts.length !== 3 || parts[0]) return null;
+ let mnemonic, size, reg_prefix;
+ if (parts[1] === "savegpr" || parts[1] === "restgpr") {
+ mnemonic = parts[1] === "savegpr" ? "stw" : "lwz";
+ size = 4;
+ reg_prefix = "r";
+ } else if (parts[1] === "savefpr" || parts[1] === "restfpr") {
+ mnemonic = parts[1] === "savefpr" ? "stfd" : "lfd";
+ size = 8;
+ reg_prefix = "f";
+ } else return null;
+
+ let addend = null;
+ for (let i = matcher.index - 1; i >= 0; i--) {
+ const instr = matcher.input[i];
+ if (
+ instr instanceof Instruction &&
+ instr.mnemonic === "addi" &&
+ instr.args[0] === new Register("r11") &&
+ instr.args[1] === new Register("r1") &&
+ instr.args[2] instanceof AsmLiteral
+ ) {
+ addend = instr.args[2].value;
+ break;
+ }
+ }
+ if (addend === null) return null;
+
+ const regnum = int_(parts[2]);
+ const new_instrs = [];
+ for (let i = regnum; i < 32; i++) {
+ const reg = new Register(reg_prefix + String(i));
+ const stack_pos = new AsmAddressMode(new Register("r1"), new AsmLiteral(size * (i - 32) + addend), null);
+ new_instrs.push(new AsmInstruction(mnemonic, [reg, stack_pos]));
+ }
+ return new Replacement(new_instrs, 1);
+ }
+}
+
+/** Comparison against 0. */
+class CmpnezPattern1 extends IrPattern {
+ replacement = "cmpnez.fictive $o, $i";
+ parts = ["addic $a, $i, -1", "subfe $o, $a, $i"];
+}
+
+class CmpnezPattern2 extends IrPattern {
+ replacement = "cmpnez.fictive $o, $i";
+ parts = ["neg $a, $i", "or $b, $a, $i", "srwi $o, $b, 31"];
+}
+
+class CmplezPattern extends IrPattern {
+ replacement = "cmplez.fictive $o, $i";
+ parts = ["cntlzw $a, $i", "li $b, 1", "rlwnm $o, $b, $a, 31, 31"];
+}
+
+class CmpgtzPattern extends IrPattern {
+ replacement = "cmpgtz.fictive $o, $i";
+ parts = ["neg $a, $i", "andc $b, $a, $i", "srwi $o, $b, 31"];
+}
+
+class CmpnePattern extends IrPattern {
+ replacement = "cmpne.fictive $o, $x, $y";
+ parts = ["subf $a, $x, $y", "subf $b, $y, $x", "or $c, $a, $b", "srwi $o, $c, 31"];
+}
+
+class CmplePattern extends IrPattern {
+ replacement = "cmple.fictive $o, $x, $y";
+ parts = ["srawi $a, $y, 31", "srwi $b, $x, 31", "subfc $c, $x, $y", "adde $o, $a, $b"];
+}
+
+class CmpltPattern1 extends IrPattern {
+ replacement = "cmplt.fictive $o, $x, $y";
+ parts = ["eqv $a, $y, $x", "subfc $b, $y, $x", "srwi $c, $a, 31", "addze $d, $c", "clrlwi $o, $d, 31"];
+}
+
+class CmpltPattern2 extends IrPattern {
+ replacement = "cmplt.fictive $o, $x, $y";
+ parts = ["xor $a, $y, $x", "srawi $b, $a, 1", "and $c, $a, $y", "subf $d, $c, $b", "srwi $o, $d, 31"];
+}
+
+class CmpleuPattern1 extends IrPattern {
+ replacement = "cmpleu.fictive $o, $x, $y";
+ parts = ["subf $a, $x, $y", "orc $b, $y, $x", "srwi $c, $a, 1", "subf $d, $c, $b", "srwi $o, $d, 31"];
+}
+
+class CmpleuPattern2 extends IrPattern {
+ replacement = "cmpleu.fictive $o, $x, $y";
+ parts = ["li $a, -1", "subfc $b, $x, $y", "subfze $o, $a"];
+}
+
+class CmpltuPattern1 extends IrPattern {
+ replacement = "cmpltu.fictive $o, $x, $y";
+ parts = ["subfc $a, $y, $x", "subfe $b, $a, $a", "neg $o, $b"];
+}
+
+class CmpltuPattern2 extends IrPattern {
+ replacement = "cmpltu.fictive $o, $x, $y";
+ parts = ["xor $a, $y, $x", "cntlzw $b, $a", "slw $c, $y, $b", "srwi $o, $c, 31"];
+}
+
+/** Split decrement-$ctr-and-branch instructions into a pair of instructions. */
+class BranchCtrPattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (instr instanceof Instruction && (instr.mnemonic === "bdz" || instr.mnemonic === "bdnz")) {
+ const ctr = new Register("ctr");
+ return new Replacement([new AsmInstruction("addi", [ctr, ctr, new AsmLiteral(-1)]), new AsmInstruction(instr.mnemonic + ".fictive", instr.args)], 1);
+ }
+ return null;
+ }
+}
+
+class FloatishToUintPattern extends SimpleAsmPattern {
+ pattern = make_pattern("bl __cvt_fp2unsigned");
+
+ replace(m) {
+ return new Replacement([new AsmInstruction("cvt.u.d.fictive", [new Register("r3"), new Register("f1")])], m.body.length);
+ }
+}
+
+class LoopStructCopyPattern extends AsmPattern {
+ loop_patterns = [
+ // 4-aligned
+ make_pattern(".loop:", ".set W, 8", ".set B, 4", "lwz $a, 4($x)", "lwzu $b, 8($x)", "stw $a, 4($y)", "stwu $b, 8($y)", "bdnz .loop"),
+ make_pattern(".loop:", ".set W, 8", ".set B, 8", "lwzu $a, 8($x)", "lwz $b, 4($x)", "stwu $a, 8($y)", "stw $b, 4($y)", "bdnz .loop"),
+ // 2-aligned
+ make_pattern(".loop:", ".set W, 4", ".set B, 2", "lhz $a, 2($x)", "lhzu $b, 4($x)", "sth $a, 2($y)", "sthu $b, 4($y)", "bdnz .loop"),
+ make_pattern(".loop:", ".set W, 4", ".set B, 4", "lhzu $a, 4($x)", "lhz $b, 2($x)", "sthu $a, 4($y)", "sth $b, 2($y)", "bdnz .loop"),
+ // 1-aligned
+ make_pattern(".loop:", ".set W, 2", ".set B, 1", "lbz $a, 1($x)", "lbzu $b, 2($x)", "stb $a, 1($y)", "stbu $b, 2($y)", "bdnz .loop"),
+ make_pattern(".loop:", ".set W, 2", ".set B, 2", "lbzu $a, 2($x)", "lbz $b, 1($x)", "stbu $a, 2($y)", "stb $b, 1($y)", "bdnz .loop"),
+ ];
+
+ match(matcher) {
+ let m = null;
+ for (const pattern of this.loop_patterns) {
+ m = matcher.try_match(pattern);
+ if (m !== null) break;
+ }
+ if (m === null) return null;
+ const new_instr = new AsmInstruction("loopstructcopy.fictive", [
+ m.regs.get("y"),
+ m.regs.get("x"),
+ m.regs.get("y"),
+ m.regs.get("x"),
+ new Register("ctr"),
+ new AsmLiteral(m.literals.get("W")),
+ new AsmLiteral(m.literals.get("B")),
+ new AsmLiteral(0),
+ new AsmLiteral(0),
+ ]);
+ return new Replacement([m.body[0], new_instr], m.body.length);
+ }
+}
+
+/** Recognizing struct copy when it starts with lwz lwz stw stw. */
+class StructCopyPattern extends AsmPattern {
+ pattern = make_pattern("lwz $a, I($s)", "lwz $b, (I+4)($s)", "stw $a, I($d)", "stw $b, (I+4)($d)");
+
+ match(matcher) {
+ let m = matcher.try_match(this.pattern);
+ if (m === null) return null;
+ let i = 8;
+ const pattern_ext = [...this.pattern];
+ for (;;) {
+ const pattern2 = make_pattern(`lwz $a, (I+${i})($s)`, `lwz $b, (I+${i + 4})($s)`, `stw $a, (I+${i})($d)`, `stw $b, (I+${i + 4})($d)`);
+ const m2 = matcher.try_match([...pattern_ext, ...pattern2]);
+ if (m2) {
+ m = m2;
+ i += 8;
+ pattern_ext.push(...pattern2);
+ } else break;
+ }
+
+ const pattern_end_4b = make_pattern(`lwz $b, (I+${i})($s)`, `stw $b, (I+${i})($d)`);
+ let m_end = matcher.try_match([...pattern_ext, ...pattern_end_4b]);
+ if (m_end) {
+ m = m_end;
+ i += 4;
+ pattern_ext.push(...pattern_end_4b);
+ }
+
+ const pattern_end_2b = make_pattern(`lhz $b, (I+${i})($s)`, `sth $b, (I+${i})($d)`);
+ m_end = matcher.try_match([...pattern_ext, ...pattern_end_2b]);
+ if (m_end) {
+ m = m_end;
+ i += 2;
+ pattern_ext.push(...pattern_end_2b);
+ }
+
+ const pattern_end_1b = make_pattern(`lbz $b, (I+${i})($s)`, `stb $b, (I+${i})($d)`);
+ m_end = matcher.try_match([...pattern_ext, ...pattern_end_1b]);
+ if (m_end) {
+ m = m_end;
+ i += 1;
+ }
+
+ return new Replacement([new AsmInstruction("structcopy.fictive", [m.regs.get("d"), m.regs.get("s"), new AsmLiteral(i)])], m.body.length);
+ }
+}
+
+class FloatishToSintIrPattern extends IrPattern {
+ replacement = "fctiwz.fictive $i, $f";
+ parts = ["fctiwz $t, $f", "stfd $t, (N-4)($r1)", "lwz $i, N($r1)"];
+}
+
+// Upstream mixes in CheckConstantMixin *after* IrPattern, so IrPattern.check
+// (always true) wins in the MRO; the mixin's check is never used.
+
+class SintToDoubleIrPattern extends IrPattern {
+ replacement = "cvt.d.i.fictive $f, $i, K($k)";
+ parts = ["lis $a, 0x4330", "stw $a, N($r1)", "xoris $b, $i, 0x8000", "stw $b, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsub $f, $d, $c"];
+}
+
+class UintToDoubleIrPattern extends IrPattern {
+ replacement = "cvt.d.u.fictive $f, $i, K($k)";
+ parts = ["lis $a, 0x4330", "stw $a, N($r1)", "stw $i, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsub $f, $d, $c"];
+}
+
+class SintToFloatIrPattern extends IrPattern {
+ replacement = "cvt.s.i.fictive $f, $i, K($k)";
+ parts = ["lis $a, 0x4330", "stw $a, N($r1)", "xoris $b, $i, 0x8000", "stw $b, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsubs $f, $d, $c"];
+}
+
+class UintToFloatIrPattern extends IrPattern {
+ replacement = "cvt.s.u.fictive $f, $i, K($k)";
+ parts = ["lis $a, 0x4330", "stw $a, N($r1)", "stw $i, (N+4)($r1)", "lfd $d, N($r1)", "lfd $c, K($k)", "fsubs $f, $d, $c"];
+}
+
+class LoopStructCopySetupPattern extends IrPattern {
+ replacement = "loopstructcopy.fictive $a, $b, $x, $y, $z, W, B, B, T";
+ parts = ["addi $a, $x, -B", "addi $b, $y, -B", "loopstructcopy.fictive $a, $b, $a, $b, $z, W, B, 0, 0"];
+
+ static _by_offset(refs) {
+ const ret = new Map();
+ for (const ref of refs) {
+ if (!(ref instanceof InstrRef)) continue;
+ const ins = ref.instruction;
+ if (ins.args.length !== 2) continue;
+ const arg = ins.args[1];
+ if (!(arg instanceof AsmAddressMode)) continue;
+ if (!(arg.addend instanceof AsmLiteral)) continue;
+ ret.set(arg.addend.value, ref);
+ }
+ return ret;
+ }
+
+ check(m, arch, flow_graph) {
+ let offset = m.symbolic_args.get("B");
+ pyassert(offset instanceof AsmLiteral);
+ offset = offset.value;
+ let tail_size = 0;
+
+ const ref = m.body[2];
+ pyassert(ref.instruction.mnemonic === "loopstructcopy.fictive");
+ const dst = m.symbolic_registers.get("a");
+ const src = m.symbolic_registers.get("b");
+ const dst_refs_by_offset = LoopStructCopySetupPattern._by_offset(flow_graph.instr_uses.get(ref).get(dst));
+ const src_refs_by_offset = LoopStructCopySetupPattern._by_offset(flow_graph.instr_uses.get(ref).get(src));
+
+ const tails = [
+ ["lwz", "stw", 4],
+ ["lhz", "sth", 2],
+ ["lbz", "stb", 1],
+ ];
+ for (const [load_mn, store_mn, width] of tails) {
+ const load = src_refs_by_offset.get(offset + tail_size) ?? null;
+ const store = dst_refs_by_offset.get(offset + tail_size) ?? null;
+ if (load === null || store === null || load.instruction.mnemonic !== load_mn || store.instruction.mnemonic !== store_mn) continue;
+ const temp_reg = load.instruction.args[0];
+ pyassert(temp_reg instanceof Register);
+ if (!flow_graph.instr_uses.get(load).get(temp_reg).has(store)) continue;
+ tail_size += width;
+ load.instruction = load.instruction.replace({ in_pattern: true });
+ store.replace_instruction(new AsmInstruction("nop", []), arch);
+ }
+
+ m.symbolic_args.set("T", new AsmLiteral(tail_size));
+ return true;
+ }
+}
+
+const r = (names) => names.map((n) => new Register(n));
+
+const argument_regs = r(["r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13"]);
+const simple_temp_regs = r(["r11", "r12"]);
+const temp_regs = [...argument_regs, ...simple_temp_regs, ...r(["r0", "f0", "cr0_gt", "cr0_lt", "cr0_eq", "cr0_so", "ctr"])];
+const saved_regs = r([
+ "lr",
+ "r2",
+ "r13",
+ "r14",
+ "r15",
+ "r16",
+ "r17",
+ "r18",
+ "r19",
+ "r20",
+ "r21",
+ "r22",
+ "r23",
+ "r24",
+ "r25",
+ "r26",
+ "r27",
+ "r28",
+ "r29",
+ "r30",
+ "r31",
+ "f14",
+ "f15",
+ "f16",
+ "f17",
+ "f18",
+ "f19",
+ "f20",
+ "f21",
+ "f22",
+ "f23",
+ "f24",
+ "f25",
+ "f26",
+ "f27",
+ "f28",
+ "f29",
+ "f30",
+ "f31",
+]);
+const stack_pointer_reg = new Register("r1");
+const all_regs = [...saved_regs, ...temp_regs, stack_pointer_reg, ...r(["zero", "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7"])];
+
+// List of all instructions where `$r0` as certain args is interpreted as `0`
+// instead of the contents of `$r0`. The value is the affected argument index.
+const INSTRS_R0_AS_ZERO = {
+ addi: 1,
+ addis: 1,
+ dcbf: 0,
+ dcbi: 0,
+ dcbst: 0,
+ dcbt: 0,
+ dcbtst: 0,
+ dcbz: 0,
+ dcbz_l: 0,
+ eciwx: 1,
+ ecowx: 1,
+ icbi: 0,
+ lbz: 1,
+ lbzx: 1,
+ lfd: 1,
+ lfdx: 1,
+ lfs: 1,
+ lfsx: 1,
+ lha: 1,
+ lhax: 1,
+ lhbrx: 1,
+ lhz: 1,
+ lhzx: 1,
+ lmw: 1,
+ lswi: 1,
+ lswx: 1,
+ lwarx: 1,
+ lwbrx: 1,
+ lwz: 1,
+ lwzx: 1,
+ psq_lx: 1,
+ psq_stx: 1,
+ stb: 1,
+ stbx: 1,
+ stfd: 1,
+ stfdx: 1,
+ stfiwx: 1,
+ stfs: 1,
+ stfsx: 1,
+ sth: 1,
+ sthbrx: 1,
+ sthx: 1,
+ stmw: 1,
+ stswi: 1,
+ stswx: 1,
+ stw: 1,
+ stwbrx: 1,
+ "stwcx.": 1,
+ stwx: 1,
+};
+
+const instrs_ignore = new Set(["nop", "stmw", "lmw", "crclr", "crset"]);
+
+const instrs_store = {
+ stb: (a) => make_store(a, Type.int_of_size(8)),
+ sth: (a) => make_store(a, Type.int_of_size(16)),
+ stw: (a) => make_store(a, Type.reg32({ likely_float: false })),
+ stbx: (a) => make_storex(a, Type.int_of_size(8)),
+ sthx: (a) => make_storex(a, Type.int_of_size(16)),
+ stwx: (a) => make_storex(a, Type.reg32({ likely_float: false })),
+ stfs: (a) => make_store(a, Type.f32()),
+ stfd: (a) => make_store(a, Type.f64()),
+ stfsx: (a) => make_storex(a, Type.f32()),
+ stfdx: (a) => make_storex(a, Type.f64()),
+ psq_st: () => null,
+};
+const instrs_store_update = {
+ stbu: (a) => make_store(a, Type.int_of_size(8)),
+ sthu: (a) => make_store(a, Type.int_of_size(16)),
+ stwu: (a) => make_store(a, Type.reg32({ likely_float: false })),
+ stbux: (a) => make_storex(a, Type.int_of_size(8)),
+ sthux: (a) => make_storex(a, Type.int_of_size(16)),
+ stwux: (a) => make_storex(a, Type.reg32({ likely_float: false })),
+ stfsu: (a) => make_store(a, Type.f32()),
+ stfdu: (a) => make_store(a, Type.f64()),
+ stfsux: (a) => make_storex(a, Type.f32()),
+ stfdux: (a) => make_storex(a, Type.f64()),
+};
+const instrs_load = {
+ lba: (a) => handle_load(a, Type.s8()),
+ lbz: (a) => handle_load(a, Type.u8()),
+ lha: (a) => handle_load(a, Type.s16()),
+ lhz: (a) => handle_load(a, Type.u16()),
+ lwz: (a) => handle_load(a, Type.reg32({ likely_float: false })),
+ lbax: (a) => handle_loadx(a, Type.s8()),
+ lbzx: (a) => handle_loadx(a, Type.u8()),
+ lhax: (a) => handle_loadx(a, Type.s16()),
+ lhzx: (a) => handle_loadx(a, Type.u16()),
+ lwzx: (a) => handle_loadx(a, Type.reg32({ likely_float: false })),
+ lfs: (a) => handle_load(a, Type.f32()),
+ lfd: (a) => handle_load(a, Type.f64()),
+ lfsx: (a) => handle_loadx(a, Type.f32()),
+ lfdx: (a) => handle_loadx(a, Type.f64()),
+ psq_l: () => new ErrorExpr("psq_l unimplemented"),
+};
+const instrs_load_update = {
+ lbau: (a) => handle_load(a, Type.s8()),
+ lbzu: (a) => handle_load(a, Type.u8()),
+ lhau: (a) => handle_load(a, Type.s16()),
+ lhzu: (a) => handle_load(a, Type.u16()),
+ lwzu: (a) => handle_load(a, Type.reg32({ likely_float: false })),
+ lbaux: (a) => handle_loadx(a, Type.s8()),
+ lbzux: (a) => handle_loadx(a, Type.u8()),
+ lhaux: (a) => handle_loadx(a, Type.s16()),
+ lhzux: (a) => handle_loadx(a, Type.u16()),
+ lwzux: (a) => handle_loadx(a, Type.reg32({ likely_float: false })),
+ lfsu: (a) => handle_load(a, Type.f32()),
+ lfdu: (a) => handle_load(a, Type.f64()),
+ lfsux: (a) => handle_loadx(a, Type.f32()),
+ lfdux: (a) => handle_loadx(a, Type.f64()),
+};
+
+const instrs_branches = {
+ // The `!` indicates that the condition in the register is negated
+ beq: "cr0_eq",
+ bge: "!cr0_lt",
+ bgt: "cr0_gt",
+ ble: "!cr0_gt",
+ blt: "cr0_lt",
+ bne: "!cr0_eq",
+ bns: "!cr0_so",
+ bso: "cr0_so",
+ bdnz: "ctr",
+ bdz: "!ctr",
+ "bdnz.fictive": "ctr",
+ "bdz.fictive": "!ctr",
+};
+const instrs_no_dest = {
+ sync: () => void_fn_op("M2C_SYNC", []),
+ isync: () => void_fn_op("M2C_SYNC", []),
+ "structcopy.fictive": (a) => void_fn_op("M2C_STRUCT_COPY", [a.reg(0), a.reg(1), a.full_imm(2)]),
+};
+
+const intish = () => ({ type: Type.intish() });
+
+const instrs_dest_first_non_load = {
+ // Integer arithmetic
+ add: (a) => handle_add(a),
+ addc: (a) => handle_add(a),
+ adde: (a) => carry_add_to(handle_add(a)),
+ addze: (a) => carry_add_to(a.reg(1)),
+ addi: (a) => handle_addi(a.reg_ref(0), a.reg_ref(1), a.reg(1), a.s16_imm(2), a),
+ addic: (a) => handle_addi(a.reg_ref(0), a.reg_ref(1), a.reg(1), a.s16_imm(2), a),
+ addis: (a) => handle_addis(a),
+ subf: (a) => fold_divmod(BinaryOp.intptr(a.reg(2), "-", a.reg(1))),
+ subfc: (a) => fold_divmod(BinaryOp.intptr(a.reg(2), "-", a.reg(1))),
+ subfe: (a) => carry_sub_from(fold_divmod(BinaryOp.intptr(a.reg(2), "-", a.reg(1)))),
+ subfic: (a) => fold_divmod(BinaryOp.intptr(a.s16_imm(2), "-", a.reg(1))),
+ subfze: (a) => carry_sub_from(fold_mul_chains(UnaryOp.sint("-", a.reg(1)))),
+ neg: (a) => fold_mul_chains(UnaryOp.sint("-", a.reg(1))),
+ divw: (a) => BinaryOp.sint(a.reg(1), "/", a.reg(2)),
+ divwu: (a) => BinaryOp.uint(a.reg(1), "/", a.reg(2)),
+ mulli: (a) => BinaryOp.int(a.reg(1), "*", a.s16_imm(2)),
+ mullw: (a) => BinaryOp.int(a.reg(1), "*", a.reg(2)),
+ mulhw: (a) => fold_divmod(BinaryOp.int(a.reg(1), "MULT_HI", a.reg(2))),
+ mulhwu: (a) => fold_divmod(BinaryOp.int(a.reg(1), "MULTU_HI", a.reg(2))),
+ // Bit arithmetic
+ or: (a) => handle_or(a.reg(1), a.reg(2)),
+ orc: (a) => handle_or(a.reg(1), new UnaryOp("~", a.reg(2), intish())),
+ ori: (a) => handle_or(a.reg(1), a.u16_imm(2)),
+ oris: (a) => handle_or(a.reg(1), a.shifted_u16_imm(2)),
+ and: (a) => BinaryOp.int(a.reg(1), "&", a.reg(2)),
+ andc: (a) => BinaryOp.int(a.reg(1), "&", new UnaryOp("~", a.reg(2), intish())),
+ not: (a) => new UnaryOp("~", a.reg(1), intish()),
+ nor: (a) => new UnaryOp("~", BinaryOp.int(a.reg(1), "|", a.reg(2)), intish()),
+ xor: (a) => BinaryOp.int(a.reg(1), "^", a.reg(2)),
+ eqv: (a) => new UnaryOp("~", BinaryOp.int(a.reg(1), "^", a.reg(2)), intish()),
+ andi: (a) => BinaryOp.int(a.reg(1), "&", a.u16_imm(2)),
+ andis: (a) => BinaryOp.int(a.reg(1), "&", a.shifted_u16_imm(2)),
+ xori: (a) => handle_xor(a.reg(1), a.u16_imm(2)),
+ xoris: (a) => BinaryOp.int(a.reg(1), "^", a.shifted_u16_imm(2)),
+ "cmpnez.fictive": (a) => handle_cmpnez(a.reg(1)),
+ "cmpne.fictive": (a) => BinaryOp.icmp(a.reg(1), "!=", a.reg(2)),
+ "cmple.fictive": (a) => BinaryOp.scmp(a.reg(1), "<=", a.reg(2)),
+ "cmplez.fictive": (a) => BinaryOp.scmp(a.reg(1), "<=", new Literal(0)),
+ "cmplt.fictive": (a) => BinaryOp.scmp(a.reg(1), "<", a.reg(2)),
+ "cmpgtz.fictive": (a) => BinaryOp.scmp(a.reg(1), ">", new Literal(0)),
+ "cmpleu.fictive": (a) => BinaryOp.ucmp(a.reg(1), "<=", a.reg(2)),
+ "cmpltu.fictive": (a) => BinaryOp.ucmp(a.reg(1), "<", a.reg(2)),
+ rlwimi: (a) => handle_rlwimi(a.reg(0), a.reg(1), a.imm_value(2), a.imm_value(3), a.imm_value(4)),
+ rlwinm: (a) => handle_rlwinm(a.reg(1), a.imm_value(2), a.imm_value(3), a.imm_value(4)),
+ rlwnm: (a) => handle_rlwnm(a.reg(1), a.reg(2), a.imm_value(3), a.imm_value(4)),
+ slw: (a) => fold_mul_chains(BinaryOp.int(a.reg(1), "<<", as_intish(a.reg(2)))),
+ srw: (a) => fold_divmod(BinaryOp.ushift(a.reg(1), ">>", a.reg(2))),
+ sraw: (a) => fold_divmod(BinaryOp.sshift(a.reg(1), ">>", a.reg(2))),
+ srawi: (a) => handle_shift_right(a, { signed: true }),
+ extsb: (a) => as_type(a.reg(1), Type.s8(), false),
+ extsh: (a) => as_type(a.reg(1), Type.s16(), false),
+ cntlzw: (a) => new UnaryOp("CLZ", a.reg(1), intish()),
+ // Load Immediate
+ li: (a) => a.full_imm(1),
+ lis: (a) => load_upper(a),
+ // Move from Special Register
+ mflr: (a) => a.regs.get(new Register("lr")),
+ mfctr: (a) => a.regs.get(new Register("ctr")),
+ // Move pseudoinstructions
+ mr: (a) => a.reg(1),
+ "move.fictive": (a) => a.reg(1),
+ // Floating Point Arithmetic
+ fadd: (a) => handle_add_double(a),
+ fadds: (a) => handle_add_float(a),
+ fdiv: (a) => BinaryOp.f64(a.reg(1), "/", a.reg(2)),
+ fdivs: (a) => BinaryOp.f32(a.reg(1), "/", a.reg(2)),
+ fmul: (a) => BinaryOp.f64(a.reg(1), "*", a.reg(2)),
+ fmuls: (a) => BinaryOp.f32(a.reg(1), "*", a.reg(2)),
+ fsub: (a) => BinaryOp.f64(a.reg(1), "-", a.reg(2)),
+ fsubs: (a) => BinaryOp.f32(a.reg(1), "-", a.reg(2)),
+ fneg: (a) => new UnaryOp("-", a.reg(1), { type: Type.floatish() }),
+ fmr: (a) => a.reg(1),
+ frsp: (a) => handle_convert(a.reg(1), Type.f32(), Type.f64()),
+ fctiwz: (a) => handle_convert(a.reg(1), Type.sintish(), Type.floatish()),
+ "fctiwz.fictive": (a) => handle_convert(a.reg(1), Type.sintish(), Type.floatish()),
+ "cvt.u.d.fictive": (a) => handle_convert(a.reg(1), Type.uintish(), Type.floatish()),
+ "cvt.d.i.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.sintish()),
+ "cvt.d.u.fictive": (a) => handle_convert(a.reg(1), Type.f64(), Type.uintish()),
+ "cvt.s.i.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.sintish()),
+ "cvt.s.u.fictive": (a) => handle_convert(a.reg(1), Type.f32(), Type.uintish()),
+ // Floating Point Fused Multiply-{Add,Sub}
+ fmadd: (a) => BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "+", a.reg(3)),
+ fmadds: (a) => BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "+", a.reg(3)),
+ fnmadd: (a) => new UnaryOp("-", BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), { type: Type.f64() }),
+ fnmadds: (a) => new UnaryOp("-", BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "+", a.reg(3)), { type: Type.f32() }),
+ fmsub: (a) => BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "-", a.reg(3)),
+ fmsubs: (a) => BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "-", a.reg(3)),
+ fnmsub: (a) => new UnaryOp("-", BinaryOp.f64(BinaryOp.f64(a.reg(1), "*", a.reg(2)), "-", a.reg(3)), { type: Type.f64() }),
+ fnmsubs: (a) => new UnaryOp("-", BinaryOp.f32(BinaryOp.f32(a.reg(1), "*", a.reg(2)), "-", a.reg(3)), { type: Type.f32() }),
+ fabs: (a) => fn_op("fabs", [a.reg(1)], Type.floatish()),
+ fres: (a) => fn_op("__fres", [a.reg(1)], Type.floatish()),
+ frsqrte: (a) => fn_op("__frsqrte", [a.reg(1)], Type.floatish()),
+ fsel: (a) => new TernaryOp(BinaryOp.fcmp(a.reg(1), ">=", new Literal(0)), a.reg(2), a.reg(3), { type: Type.floatish() }),
+};
+const instrs_destination_first = { ...instrs_dest_first_non_load, ...instrs_load };
+
+const instrs_ppc_compare = {
+ // Integer (signed/unsigned)
+ cmpw: (a, op) => BinaryOp.sintptr_cmp(a.reg(1), op, a.reg(2)),
+ cmpwi: (a, op) => BinaryOp.sintptr_cmp(a.reg(1), op, a.s16_imm(2)),
+ cmplw: (a, op) => BinaryOp.uintptr_cmp(a.reg(1), op, a.reg(2)),
+ cmplwi: (a, op) => BinaryOp.uintptr_cmp(a.reg(1), op, a.s16_imm(2)),
+ // Floating point
+ fcmpo: (a, op) => BinaryOp.fcmp(a.reg(1), op, a.reg(2)),
+ fcmpu: (a, op) => BinaryOp.fcmp(a.reg(1), op, a.reg(2)),
+ "fcmpo.lte.fictive": (a, op) => BinaryOp.fcmp(a.reg(1), op !== "==" ? op : "<=", a.reg(2)),
+ "fcmpo.gte.fictive": (a, op) => BinaryOp.fcmp(a.reg(1), op !== "==" ? op : ">=", a.reg(2)),
+};
+
+const PPC_ATTRS = {
+ arch: Target.ArchEnum.PPC,
+ re_comment: String.raw`[#;].*`,
+ supports_dollar_regs: true,
+ home_space_size: 8,
+ stack_pointer_reg,
+ frame_pointer_regs: r(["r30"]),
+ return_address_reg: new Register("lr"),
+ base_return_regs: [
+ [new Register("r3"), false],
+ [new Register("f1"), true],
+ ],
+ all_return_regs: r(["f1", "r3", "r4"]),
+ argument_regs,
+ simple_temp_regs,
+ temp_regs,
+ saved_regs,
+ all_regs,
+ aliased_regs: {},
+ INSTRS_R0_AS_ZERO,
+ instrs_ignore,
+ instrs_store,
+ instrs_store_update,
+ instrs_load,
+ instrs_load_update,
+ instrs_branches,
+ instrs_no_dest,
+ instrs_dest_first_non_load,
+ instrs_destination_first,
+ instrs_ppc_compare,
+};
+
+export class PpcArch extends Arch {
+ constructor() {
+ super();
+ Object.assign(this, PPC_ATTRS);
+ this.ir_patterns = [
+ new LoopStructCopySetupPattern(),
+ new FloatishToSintIrPattern(),
+ new SintToDoubleIrPattern(),
+ new UintToDoubleIrPattern(),
+ new SintToFloatIrPattern(),
+ new UintToFloatIrPattern(),
+ new CmpnezPattern1(),
+ new CmpnezPattern2(),
+ new CmplezPattern(),
+ new CmpgtzPattern(),
+ new CmpnePattern(),
+ new CmplePattern(),
+ new CmpltPattern1(),
+ new CmpltPattern2(),
+ new CmpleuPattern1(),
+ new CmpleuPattern2(),
+ new CmpltuPattern1(),
+ new CmpltuPattern2(),
+ ];
+ this.asm_patterns = [
+ new FcmpoCrorPattern(),
+ new MfcrPattern(),
+ new TailCallPattern(),
+ new SaveRestoreRegsFnPattern(),
+ new LoopStructCopyPattern(),
+ new BranchCtrPattern(),
+ new FloatishToUintPattern(),
+ new StructCopyPattern(),
+ ];
+ }
+
+ missing_return() {
+ return [this.parse("blr", [], InstructionMeta.missing())];
+ }
+
+ normalize_instruction(instr, asm_state) {
+ // Remove +/- suffix, which indicates branch-(un)likely and can be ignored
+ if (instr.mnemonic.startsWith("b") && (instr.mnemonic.endsWith("+") || instr.mnemonic.endsWith("-"))) {
+ return this.normalize_instruction(new AsmInstruction(instr.mnemonic.slice(0, -1), instr.args), asm_state);
+ }
+
+ const args = instr.args;
+ const base_mnemonic = rstrip(instr.mnemonic, ".");
+ const dot = instr.mnemonic.slice(base_mnemonic.length);
+
+ const sub = (a, b) => (a instanceof AsmLiteral && b instanceof AsmLiteral ? new AsmLiteral(a.value - b.value) : new BinOp("-", a, b));
+ const add = (a, b) => (a instanceof AsmLiteral && b instanceof AsmLiteral ? new AsmLiteral(a.value + b.value) : new BinOp("+", a, b));
+ const make_dotted = (mn, a) => new AsmInstruction(mn + dot, a);
+ const lit = (v) => new AsmLiteral(v);
+
+ const r0_index = has(this.INSTRS_R0_AS_ZERO, instr.mnemonic) ? this.INSTRS_R0_AS_ZERO[instr.mnemonic] : null;
+ if (r0_index !== null && args.length > r0_index) {
+ let r0_arg = args[r0_index];
+ if (r0_arg === new Register("r0")) r0_arg = new Register("zero");
+ else if (r0_arg instanceof AsmAddressMode && r0_arg.base === new Register("r0")) r0_arg = new AsmAddressMode(new Register("zero"), r0_arg.addend, r0_arg.writeback);
+ if (r0_arg !== args[r0_index]) {
+ const new_args = [...args];
+ new_args[r0_index] = r0_arg;
+ return this.normalize_instruction(new AsmInstruction(instr.mnemonic, new_args), asm_state);
+ }
+ }
+ if (args.length === 4) {
+ if (base_mnemonic === "extlwi") return make_dotted("rlwinm", [...args.slice(0, 2), args[3], lit(0), sub(args[2], lit(1))]);
+ if (base_mnemonic === "extrwi") return make_dotted("rlwinm", [...args.slice(0, 2), add(args[2], args[3]), sub(lit(32), args[2]), lit(31)]);
+ if (base_mnemonic === "clrlslwi") {
+ const b = args[2];
+ const n = args[3];
+ return make_dotted("rlwinm", [...args.slice(0, 2), n, sub(b, n), sub(lit(31), n)]);
+ }
+ }
+ if (args.length === 3) {
+ if (
+ instr.mnemonic === "addi" &&
+ args[2] instanceof Macro &&
+ (args[1] === new Register("r2") || args[1] === new Register("r13")) &&
+ (args[2].macro_name === "sda2" || args[2].macro_name === "sda21")
+ ) {
+ return new AsmInstruction("li", [args[0], args[2].argument]);
+ }
+ if (["subi", "subis", "subic"].includes(base_mnemonic) && args[2] instanceof AsmLiteral) {
+ const mn = "add" + base_mnemonic.slice(3);
+ const negated = new AsmLiteral(-args[2].value);
+ return this.normalize_instruction(make_dotted(mn, [...args.slice(0, 2), negated]), asm_state);
+ }
+ if (["sub", "subo", "subc", "subco"].includes(base_mnemonic)) {
+ const mn = "subf" + base_mnemonic.slice(3);
+ return make_dotted(mn, [args[0], args[2], args[1]]);
+ }
+ if (base_mnemonic === "rotlwi") return make_dotted("rlwinm", [...args.slice(0, 2), args[2], lit(0), lit(31)]);
+ if (base_mnemonic === "rotrwi") return make_dotted("rlwinm", [...args.slice(0, 2), sub(lit(32), args[2]), lit(0), lit(31)]);
+ if (base_mnemonic === "slwi") return make_dotted("rlwinm", [...args.slice(0, 2), args[2], lit(0), sub(lit(31), args[2])]);
+ if (base_mnemonic === "srwi") return make_dotted("rlwinm", [...args.slice(0, 2), sub(lit(32), args[2]), args[2], lit(31)]);
+ if (base_mnemonic === "clrlwi") return make_dotted("rlwinm", [...args.slice(0, 2), lit(0), args[2], lit(31)]);
+ if (base_mnemonic === "clrrwi") return make_dotted("rlwinm", [...args.slice(0, 2), lit(0), lit(0), sub(lit(31), args[2])]);
+ }
+ if (args.length === 2) {
+ if (instr.mnemonic === "lis" && args[1] instanceof AsmLiteral) {
+ const val = lit(band(args[1].value, 0xffff) * 0x10000);
+ return new AsmInstruction("li", [args[0], val]);
+ }
+ if (instr.mnemonic === "lis" && args[1] instanceof Macro && args[1].macro_name === "ha" && args[1].argument instanceof AsmLiteral) {
+ let value = args[1].argument.value;
+ if (band(value, 0x8000)) value += 0x10000;
+ const val = lit(band(value, 0xffff0000));
+ return new AsmInstruction("li", [args[0], val]);
+ }
+ if (instr.mnemonic.startsWith("cmp") && !instr.mnemonic.includes("fictive")) {
+ const cr0 = new Register("cr0");
+ return new AsmInstruction(instr.mnemonic, [cr0, ...instr.args]);
+ }
+ }
+ return instr;
+ }
+
+ parse(mnemonic, args, meta) {
+ const cls = this;
+ let inputs = [];
+ let clobbers = [];
+ let outputs = [];
+ let jump_target = null;
+ let function_target = null;
+ let is_conditional = false;
+ let is_return = false;
+ let is_load = false;
+ let is_store = false;
+ let eval_fn = null;
+
+ const instr_str = String(new AsmInstruction(mnemonic, args));
+
+ const cr0_bits = r(["cr0_lt", "cr0_gt", "cr0_eq", "cr0_so"]);
+
+ const memory_sizes = { b: 1, h: 2, w: 4, fs: 4, fd: 8 };
+ let psq_imms = 0;
+ const size_key = rstrip(lstrip(mnemonic, "stl"), "azux");
+ let size = has(memory_sizes, size_key) ? memory_sizes[size_key] : null;
+ if (mnemonic.startsWith("psq_l") || mnemonic.startsWith("psq_st")) {
+ psq_imms = 2;
+ size = 8;
+ }
+
+ const make_memory_access = (arg, size) => {
+ pyassert(size !== null);
+ if (arg instanceof AsmAddressMode && arg.base === cls.stack_pointer_reg) {
+ const loc = StackLocation.from_offset(arg.addend);
+ if (loc === null) return [];
+ else if (size === 8) return [loc, new StackLocation(loc.offset + 4, loc.symbolic_offset)];
+ else {
+ pyassert(size <= 4);
+ return [loc];
+ }
+ }
+ return [];
+ };
+
+ const unreachable_eval = () => {
+ throw new DecompFailure(`Instruction ${instr_str} should be replaced before eval`);
+ };
+
+ const mn_nodot = rstrip(mnemonic, ".");
+
+ if (mnemonic === "blr") {
+ // Return
+ pyassert(args.length === 0);
+ inputs = [new Register("lr")];
+ is_return = true;
+ } else if (["beqlr", "bgelr", "bgtlr", "blelr", "bltlr", "bnelr", "bnglr", "bnllr", "bnslr", "bsolr"].includes(mnemonic)) {
+ // Conditional return
+ pyassert(args.length <= 1);
+ inputs = [...cr0_bits, new Register("lr")];
+ is_return = true;
+ is_conditional = true;
+ eval_fn = unreachable_eval;
+ } else if (mnemonic === "bctr") {
+ // Jump table (switch)
+ pyassert(args.length === 0);
+ inputs = [new Register("ctr")];
+ jump_target = new Register("ctr");
+ is_conditional = true;
+ eval_fn = (s, a) => s.set_switch_expr(a.regs.get(new Register("ctr")));
+ } else if (mnemonic === "bl") {
+ // Function call to label
+ pyassert(args.length === 1);
+ inputs = [...cls.argument_regs];
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = args[0];
+ eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs);
+ } else if (mnemonic === "bctrl" || mnemonic === "blrl") {
+ // Function call to pointer in special reg ($ctr or $lr)
+ pyassert(args.length === 0);
+ const reg = new Register(mnemonic.slice(1, -1));
+ inputs = [...cls.argument_regs];
+ inputs.push(reg);
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = reg;
+ eval_fn = (s, a) => s.make_function_call(a.regs.get(reg), outputs);
+ } else if (mnemonic === "b") {
+ // Unconditional jump
+ pyassert(args.length === 1);
+ jump_target = get_jump_target(args[0]);
+ } else if (has(cls.instrs_branches, mnemonic)) {
+ // Normal branch
+ pyassert(1 <= args.length && args.length <= 2);
+ const raw_name = cls.instrs_branches[mnemonic];
+ const negated = raw_name.startsWith("!");
+ const reg_name = lstrip(raw_name, "!");
+ inputs = [new Register(reg_name)];
+ jump_target = get_jump_target(args[args.length - 1]);
+ is_conditional = true;
+ eval_fn = (s, a) => {
+ let cond = a.cmp_reg(reg_name);
+ if (negated) cond = cond.negated();
+ s.set_branch_condition(cond);
+ };
+ } else if (has(cls.instrs_store, mnemonic)) {
+ pyassert(args[0] instanceof Register && size !== null);
+ is_store = true;
+ if (mnemonic.endsWith("x")) {
+ pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register);
+ inputs = [args[0], args[1], args[2]];
+ } else {
+ pyassert(args.length === 2 + psq_imms && args[1] instanceof AsmAddressMode);
+ outputs = make_memory_access(args[1], size);
+ inputs = new Array(outputs.length || 1).fill(args[0]);
+ inputs.push(args[1].base);
+ }
+ eval_fn = (s, a) => {
+ const store = cls.instrs_store[mnemonic](a);
+ if (store !== null) s.store_memory(store, a.reg_ref(0));
+ };
+ } else if (has(cls.instrs_store_update, mnemonic)) {
+ pyassert(args[0] instanceof Register && size !== null);
+ is_store = true;
+ if (mnemonic.endsWith("x")) {
+ pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register);
+ inputs = [args[0], args[1], args[2]];
+ outputs = [args[1]];
+ eval_fn = (s, a) => {
+ const store = cls.instrs_store_update[mnemonic](a);
+ // Update the register in the second argument
+ const update = a.reg_ref(1);
+ const offset = a.reg(2);
+ s.set_reg(update, add_imm(update, a.regs.get(update), offset, a));
+ if (store !== null) s.store_memory(store, a.reg_ref(0));
+ };
+ } else {
+ pyassert(args.length === 2 + psq_imms && args[1] instanceof AsmAddressMode);
+ inputs = [args[0], args[1].base];
+ outputs = [...make_memory_access(args[1], size), args[1].base];
+ eval_fn = (s, a) => {
+ const store = cls.instrs_store_update[mnemonic](a);
+ // Update the register in the second argument
+ const update = a.memory_ref(1);
+ if (!(update instanceof AddressMode)) throw new DecompFailure(`Unhandled store-and-update arg in ${instr_str}: ${repr(update)}`);
+ s.set_reg(update.base, add_imm(update.base, a.regs.get(update.base), new Literal(update.offset), a));
+ if (store !== null) s.store_memory(store, a.reg_ref(0));
+ };
+ }
+ } else if (has(cls.instrs_load, mnemonic)) {
+ pyassert(args[0] instanceof Register && size !== null);
+ if (mnemonic.endsWith("x")) {
+ pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register);
+ inputs = [args[1], args[2]];
+ } else {
+ pyassert(args.length === 2 + psq_imms);
+ if (args[1] instanceof AsmAddressMode) inputs = [...make_memory_access(args[1], size), args[1].base];
+ }
+ is_load = true;
+ outputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(0), cls.instrs_load[mnemonic](a));
+ } else if (has(cls.instrs_load_update, mnemonic)) {
+ pyassert(args[0] instanceof Register && size !== null);
+ is_load = true;
+ if (mnemonic.endsWith("x")) {
+ pyassert(args.length === 3 + psq_imms && args[1] instanceof Register && args[2] instanceof Register);
+ inputs = [args[1], args[2]];
+ outputs = [args[0], args[1]];
+ eval_fn = (s, a) => {
+ const target = a.reg_ref(0);
+ const val = cls.instrs_load_update[mnemonic](a);
+ s.set_reg(target, val);
+ // In `rD, rA, rB`, update `rA = rA + rB`
+ const update_reg = a.reg_ref(1);
+ const offset = a.reg(2);
+ if (update_reg === target) throw new DecompFailure(`Invalid instruction, rA and rD must be different in ${instr_str}`);
+ s.set_reg(update_reg, add_imm(update_reg, a.regs.get(update_reg), offset, a));
+ };
+ } else {
+ pyassert(args.length === 2 + psq_imms && args[1] instanceof AsmAddressMode);
+ inputs = [...make_memory_access(args[1], size), args[1].base];
+ outputs = [args[0], args[1].base];
+ eval_fn = (s, a) => {
+ const target = a.reg_ref(0);
+ const val = cls.instrs_load_update[mnemonic](a);
+ s.set_reg(target, val);
+ // In `rD, rA(N)`, update `rA = rA + N`
+ const update = a.memory_ref(1);
+ if (!(update instanceof AddressMode)) throw new DecompFailure(`Unhandled load-and-update arg in ${instr_str}: ${repr(update)}`);
+ const update_reg = update.base;
+ const offset = new Literal(update.offset);
+ if (update_reg === target) throw new DecompFailure(`Invalid instruction, rA and rD must be different in ${instr_str}`);
+ s.set_reg(update_reg, add_imm(update_reg, a.regs.get(update_reg), offset, a));
+ };
+ }
+ } else if (mnemonic === "stmw" || mnemonic === "lmw") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof AsmAddressMode && args[0].register_name[0] === "r");
+ is_store = mnemonic === "stmw";
+ let index = int_(args[0].register_name.slice(1));
+ let offset = args[1].addend_as_literal();
+ while (index <= 31) {
+ const reg = new Register(`r${index}`);
+ const mem = make_memory_access(new AsmAddressMode(args[1].base, new AsmLiteral(offset), null), 4);
+ if (mnemonic === "stmw") {
+ inputs.push(reg);
+ outputs.push(...mem);
+ } else {
+ outputs.push(reg);
+ inputs.push(...mem);
+ }
+ index += 1;
+ offset += 4;
+ }
+ inputs.push(args[1].base);
+ // TODO: These are only supported in function prologues/epilogues
+ eval_fn = null;
+ } else if (has(cls.instrs_no_dest, mnemonic)) {
+ pyassert(!args.some((x) => x instanceof AsmAddressMode));
+ inputs = args.filter((x) => x instanceof Register);
+ eval_fn = (s, a) => s.write_statement(cls.instrs_no_dest[mnemonic](a));
+ } else if (has(cls.instrs_destination_first, mn_nodot)) {
+ pyassert(args[0] instanceof Register);
+ outputs = [args[0]];
+ if (mnemonic === "mflr") {
+ pyassert(args.length === 1);
+ inputs = [new Register("lr")];
+ } else if (mnemonic === "mfctr") {
+ pyassert(args.length === 1);
+ inputs = [new Register("ctr")];
+ } else if (mn_nodot === "rlwimi") {
+ const notRegAm = (x) => !(x instanceof Register || x instanceof AsmAddressMode);
+ pyassert(args.length === 5 && args[1] instanceof Register && notRegAm(args[2]) && notRegAm(args[3]) && notRegAm(args[4]));
+ inputs = [args[0], args[1]];
+ } else if (mnemonic.startsWith("cvt.")) {
+ pyassert(args[1] instanceof Register);
+ if (args.length === 2) inputs = [args[1]];
+ else {
+ pyassert(args[2] instanceof AsmAddressMode);
+ size = 8;
+ inputs = [...make_memory_access(args[2], size), args[1], args[2].base];
+ }
+ } else {
+ pyassert(!args.some((x) => x instanceof AsmAddressMode));
+ inputs = args.slice(1).filter((x) => x instanceof Register);
+ }
+ if (["adde", "addme", "addze", "subfe", "subfze"].includes(mn_nodot)) inputs.push(new Register("carry"));
+ if (["addc", "addic", "subfc", "subfic"].includes(mn_nodot)) outputs.push(new Register("carry"));
+ if (mnemonic.endsWith(".")) outputs.push(...cr0_bits);
+
+ eval_fn = (s, a) => {
+ const target = a.reg_ref(0);
+ const val = cls.instrs_destination_first[mn_nodot](a);
+ const target_val = s.set_reg(target, val);
+ // Instructions ending in `.` update the condition reg
+ if (mnemonic.endsWith(".")) {
+ s.set_reg(new Register("cr0_eq"), BinaryOp.icmp(target_val, "==", new Literal(0, { type: target_val.type })));
+ // Use manual casts for cr0_gt/cr0_lt so that the type of target_val is not modified
+ // until the resulting bit is .use()'d.
+ const target_s32 = new Cast(target_val, { reinterpret: true, silent: true, type: Type.s32() });
+ s.set_reg(new Register("cr0_gt"), new BinaryOp(target_s32, ">", new Literal(0), { type: Type.s32() }));
+ s.set_reg(new Register("cr0_lt"), new BinaryOp(target_s32, "<", new Literal(0), { type: Type.s32() }));
+ s.set_reg(new Register("cr0_so"), fn_op("M2C_OVERFLOW", [target_val], Type.s32()));
+ }
+ if (outputs.includes(new Register("carry"))) {
+ s.set_reg(new Register("carry"), fn_op("M2C_CARRY", [target_val], Type.s32()));
+ }
+ };
+ } else if (mnemonic === "mtctr" || mnemonic === "mtlr") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ const dest_reg = new Register(mnemonic.slice(2));
+ inputs = [args[0]];
+ outputs = [dest_reg];
+ eval_fn = (s, a) => s.set_reg(dest_reg, a.reg(0));
+ } else if (mnemonic === "loopstructcopy.fictive") {
+ pyassert(args.length === 9);
+ for (let k = 0; k < 5; k++) pyassert(args[k] instanceof Register);
+ const width = args[5];
+ const bias = args[6];
+ const adj = args[7];
+ const tail_size = args[8];
+ inputs = [args[2], args[3], args[4]];
+ outputs = [args[0], args[1]];
+ eval_fn = (s, a) => {
+ pyassert(width instanceof AsmLiteral);
+ pyassert(bias instanceof AsmLiteral);
+ pyassert(adj instanceof AsmLiteral);
+ pyassert(tail_size instanceof AsmLiteral);
+ const tail = tail_size.value;
+ const offset = bias.value - adj.value;
+ let dst = a.reg(2);
+ let dst_out = dst;
+ let src = a.reg(3);
+ let src_out = src;
+ if (offset !== 0) {
+ dst = BinaryOp.int(dst, "+", new Literal(offset));
+ src = BinaryOp.int(src, "+", new Literal(offset));
+ }
+ if (adj.value !== 0) {
+ dst_out = BinaryOp.int(dst_out, "-", new Literal(adj.value));
+ src_out = BinaryOp.int(src_out, "-", new Literal(adj.value));
+ }
+ const count = a.reg(4);
+ let incr_size, copy_size;
+ if (count instanceof Literal) {
+ incr_size = new Literal(count.value * width.value);
+ copy_size = new Literal(count.value * width.value + tail);
+ } else {
+ incr_size = BinaryOp.int(count, "*", new Literal(width.value));
+ copy_size = incr_size;
+ if (tail !== 0) copy_size = BinaryOp.int(copy_size, "+", new Literal(tail));
+ }
+ s.write_statement(void_fn_op("M2C_STRUCT_COPY", [dst, src, copy_size]));
+ dst_out = handle_add_real(dst_out, incr_size, a);
+ src_out = handle_add_real(src_out, incr_size, a);
+ s.set_reg_real(a.reg_ref(0), dst_out, { function_return: true });
+ s.set_reg_real(a.reg_ref(1), src_out, { function_return: true });
+ };
+ } else if (has(cls.instrs_ppc_compare, mnemonic)) {
+ pyassert(args.length === 3 && args[1] instanceof Register);
+ inputs = args.slice(1).filter((x) => x instanceof Register);
+ outputs = [...cr0_bits];
+ eval_fn = (s, a) => {
+ const base_reg = a.reg_ref(0);
+ if (base_reg !== new Register("cr0")) {
+ const error = `"${instr_str}" is not supported, the first arg is not $cr0`;
+ s.write_statement(error_stmt(error));
+ return;
+ }
+ s.set_reg(new Register("cr0_eq"), cls.instrs_ppc_compare[mnemonic](a, "=="));
+ s.set_reg(new Register("cr0_gt"), cls.instrs_ppc_compare[mnemonic](a, ">"));
+ s.set_reg(new Register("cr0_lt"), cls.instrs_ppc_compare[mnemonic](a, "<"));
+ s.set_reg(new Register("cr0_so"), new Literal(0));
+ };
+ } else if (cls.instrs_ignore.has(mnemonic)) {
+ // pass
+ } else {
+ // If the mnemonic is unsupported, guess if it is destination-first
+ let maybe_dest_first;
+ if (args.length && args[0] instanceof Register) {
+ inputs = args.slice(1).filter((x) => x instanceof Register);
+ outputs = [args[0]];
+ maybe_dest_first = true;
+ } else maybe_dest_first = false;
+ if (mnemonic.endsWith(".")) outputs.push(...cr0_bits);
+
+ eval_fn = (s, a) => {
+ const error = new ErrorExpr(`unknown instruction: ${instr_str}`);
+ if (mnemonic.endsWith(".")) {
+ // Unimplemented instructions that modify CR0
+ s.set_reg(new Register("cr0_eq"), error);
+ s.set_reg(new Register("cr0_gt"), error);
+ s.set_reg(new Register("cr0_lt"), error);
+ s.set_reg(new Register("cr0_so"), error);
+ }
+ if (maybe_dest_first) s.set_reg_real(a.reg_ref(0), error, { emit_exactly_once: true });
+ else s.write_statement(new ExprStmt(error));
+ };
+ }
+
+ return new Instruction({
+ mnemonic,
+ args,
+ meta,
+ inputs,
+ clobbers,
+ outputs,
+ jump_target,
+ function_target,
+ is_conditional,
+ is_return,
+ is_load,
+ is_store,
+ eval_fn,
+ });
+ }
+
+ arg_name(loc) {
+ if (loc.offset !== null) return `arg_sp${format_hex(loc.offset)}`;
+ pyassert(loc.reg !== null);
+ const reg_num = int_(loc.reg.register_name.slice(1));
+ if (loc.reg.register_name.startsWith("r")) return `arg${reg_num - 3}`;
+ return `farg${reg_num - 1}`;
+ }
+
+ // Duplicated by MipseeArch.function_abi
+ function_abi(fn_sig, likely_regs, { for_call }) {
+ void for_call;
+ const known_slots = [];
+ const candidate_slots = [];
+
+ // $rX & $fX regs can be interspersed in function args, unlike in the MIPS O32 ABI
+ const intptr_regs = argument_regs.filter((x) => x.register_name[0] !== "f");
+ const float_regs = argument_regs.filter((x) => x.register_name[0] === "f");
+
+ if (fn_sig.params_known) {
+ let ind = 0;
+ let stack_offset = 0;
+ for (const param of fn_sig.params) {
+ const param_type = param.type.decay();
+ let reg = null;
+ let offset = null;
+ const pool = param_type.is_float() ? float_regs : intptr_regs;
+ if (pool.length) reg = pool.shift();
+ else {
+ // Stack variable
+ offset = stack_offset;
+ stack_offset += 4;
+ }
+ known_slots.push(new AbiArgSlot(new ArgLoc(offset, ind, reg), param_type, { name: param.name }));
+ ind += 1;
+ }
+ if (fn_sig.is_variadic) {
+ for (const reg of intptr_regs) {
+ candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.intptr()));
+ ind += 1;
+ }
+ for (const reg of float_regs) {
+ candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.floatish()));
+ ind += 1;
+ }
+ }
+ } else {
+ argument_regs.forEach((reg, ind) => {
+ if (reg.register_name[0] !== "f") candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.intptr()));
+ else candidate_slots.push(new AbiArgSlot(new ArgLoc(null, ind, reg), Type.floatish()));
+ });
+ }
+
+ const valid_extra_regs = new Set(known_slots.filter((slot) => slot.loc.reg !== null).map((slot) => slot.loc.reg));
+ const possible_slots = [];
+ for (const slot of candidate_slots) {
+ const reg = slot.loc.reg;
+ if (reg === null || !likely_regs.has(reg)) continue;
+
+ // Don't pass this register if lower numbered ones are undefined.
+ if (pyeq(slot, candidate_slots[0])) {
+ // For varargs, a subset of regs may be used.
+ } else {
+ // Only r3-r10/f1-f13 can be used for arguments
+ const regname = reg.register_name;
+ const prev_reg = new Register(`${regname[0]}${int_(regname.slice(1)) - 1}`);
+ if (argument_regs.includes(prev_reg) && !valid_extra_regs.has(prev_reg)) continue;
+ }
+
+ valid_extra_regs.add(reg);
+
+ if (!likely_regs.get(reg)) continue;
+
+ possible_slots.push(slot);
+ }
+
+ return new Abi({ arg_slots: known_slots, possible_slots });
+ }
+
+ function_return(expr) {
+ return new Map([
+ [new Register("f1"), new Cast(expr, { reinterpret: true, silent: true, type: Type.floatish() })],
+ [new Register("r3"), new Cast(expr, { reinterpret: true, silent: true, type: Type.intptr() })],
+ [new Register("r4"), as_u32(new Cast(expr, { reinterpret: true, silent: false, type: Type.u64() }))],
+ ]);
+ }
+}
diff --git a/packages/romdev-m2c/src/arch_sh.js b/packages/romdev-m2c/src/arch_sh.js
new file mode 100644
index 00000000..228bfde2
--- /dev/null
+++ b/packages/romdev-m2c/src/arch_sh.js
@@ -0,0 +1,975 @@
+// Port of m2c/arch_sh.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { DecompFailure } from "./error.js";
+import { Target } from "./options.js";
+import { AsmSymbolicData } from "./asm_file.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, BinOp, JumpTarget, Register, Writeback, get_jump_target } from "./asm_instruction.js";
+import { AsmPattern, Replacement, SimpleAsmPattern, make_pattern } from "./asm_pattern.js";
+import { get_literal_pool_symbol, get_literal_pool_symbolic_data } from "./flow_graph.js";
+import { Instruction, InstructionMeta, StackLocation } from "./instruction.js";
+import { IrPattern } from "./ir_pattern.js";
+import { Abi, AbiArgSlot, Arch, InstrArgs, ArgLoc, BinaryOp, CarryBit, Cast, ErrorExpr, ExprStmt, Literal, UnaryOp, as_s16, as_type, as_u16, as_u32, early_unwrap } from "./translate.js";
+import {
+ condition_from_expr,
+ fn_op,
+ fold_divmod,
+ fold_mul_chains,
+ fold_shift_right,
+ handle_add,
+ handle_add_real,
+ handle_addi,
+ handle_bitinv,
+ handle_load,
+ handle_loadx,
+ handle_or,
+ handle_sub,
+ handle_xor,
+ make_store,
+ make_storex,
+ void_fn_op,
+} from "./evaluate.js";
+import { Type } from "./types.js";
+import { floordiv, format, has, int_, pyassert, pyeq } from "./py.js";
+
+/** dataclasses.replace(instr_args, raw_args=...) */
+function with_raw_args(a, raw_args) {
+ return new InstrArgs(a.instruction_ref, raw_args, a.regs, a.stack_info);
+}
+
+const MOV_TYPES = {
+ "mov.b": () => Type.s8(),
+ "mov.w": () => Type.s16(),
+ "mov.l": () => Type.reg32({ likely_float: false }),
+};
+const MOV_STRIDES = { "mov.b": 1, "mov.w": 2, "mov.l": 4 };
+
+function mov_type(mnemonic) {
+ if (!has(MOV_TYPES, mnemonic)) throw new Error(`KeyError: '${mnemonic}'`);
+ return MOV_TYPES[mnemonic]();
+}
+function mov_stride(mnemonic) {
+ if (!has(MOV_STRIDES, mnemonic)) throw new Error(`KeyError: '${mnemonic}'`);
+ return MOV_STRIDES[mnemonic];
+}
+
+const SH_STACK_POINTER_REG = new Register("r15");
+
+export class FarJumpPattern extends AsmPattern {
+ pattern = make_pattern("mov.l $t,@-$r15", "mov.l _, $t", "jmp @$t", "mov.l @$r15+,$t");
+
+ match(matcher) {
+ const m = matcher.try_match(this.pattern);
+ if (m === null) return null;
+ const load = m.body[1];
+ pyassert(load instanceof Instruction);
+ const target_name = get_literal_pool_symbol(load.args[0], m.asm_data);
+ if (target_name === null || !matcher.is_local_label(target_name)) return null;
+ return new Replacement([new AsmInstruction("bra", [new AsmGlobalSymbol(target_name)]), new AsmInstruction("nop", [])], m.body.length);
+ }
+}
+
+export class JumpTablePattern extends AsmPattern {
+ pattern1 = make_pattern("mova _, $b", "mov.w @($b,$i),$i", "add $i, $b", "jmp @$b", "nop");
+
+ pattern2 = make_pattern("mova _, $b", "mov.w @($b,$i),$i", "add $i, $b", "bra .dispatch", "nop", "nop?", ".dispatch:", "jmp @$b", "nop");
+
+ match(matcher) {
+ for (const pattern of [this.pattern1, this.pattern2]) {
+ const m = matcher.try_match(pattern);
+ if (!m) continue;
+
+ const mova = m.body[0];
+ pyassert(mova instanceof Instruction);
+ pyassert(mova.args[0] instanceof AsmGlobalSymbol);
+
+ const table_name = mova.args[0].symbol_name;
+ const table = m.asm_data.values.get(table_name) ?? null;
+ if (table === null) return null;
+ const targets = [];
+ for (const entry of table.data) {
+ if (
+ !(entry instanceof AsmSymbolicData) ||
+ !(entry.data instanceof BinOp) ||
+ entry.data.op !== "-" ||
+ !(entry.data.lhs instanceof AsmGlobalSymbol) ||
+ entry.data.rhs !== new AsmGlobalSymbol(table_name)
+ ) {
+ return null;
+ }
+ targets.push(entry.data.lhs);
+ }
+ if (!targets.length) return null;
+ const jump = new AsmInstruction("tablejmp.doubled.fictive", [m.regs.get("i"), ...targets]);
+ return new Replacement([jump], m.body.length);
+ }
+ return null;
+ }
+}
+
+export class BrafJumpTablePattern extends SimpleAsmPattern {
+ pattern = make_pattern("mova _, $b", "mov.w @($b,$i),$b", "braf $b", "nop", ".base:");
+
+ replace(m) {
+ const mova = m.body[0];
+ pyassert(mova instanceof Instruction);
+ if (!(mova.args[0] instanceof AsmGlobalSymbol)) return null;
+ const table = m.asm_data.values.get(mova.args[0].symbol_name) ?? null;
+ if (table === null) return null;
+ const base = m.labels.get(".base");
+ const targets = [];
+ for (const entry of table.data) {
+ if (
+ !(entry instanceof AsmSymbolicData) ||
+ !(entry.data instanceof BinOp) ||
+ entry.data.op !== "-" ||
+ !(entry.data.lhs instanceof AsmGlobalSymbol) ||
+ !(entry.data.rhs instanceof AsmGlobalSymbol) ||
+ !base.names.includes(entry.data.rhs.symbol_name)
+ ) {
+ return null;
+ }
+ targets.push(entry.data.lhs);
+ }
+ if (!targets.length) return null;
+ const jump = new AsmInstruction("tablejmp.doubled.fictive", [m.regs.get("i"), ...targets]);
+ return new Replacement([jump, base], m.body.length);
+ }
+}
+
+export class BsrfCallPattern extends SimpleAsmPattern {
+ pattern = make_pattern("mov.l _,$r", "bsrf $r", "*", ".base:");
+
+ replace(m) {
+ const load = m.body[0];
+ pyassert(load instanceof Instruction);
+ const delay = m.wildcard_items[0];
+ if (!(delay instanceof Instruction)) return null;
+ const entry = get_literal_pool_symbolic_data(load.args[0], m.asm_data);
+ if (
+ entry === null ||
+ !(entry.data instanceof BinOp) ||
+ entry.data.op !== "-" ||
+ !(entry.data.lhs instanceof AsmGlobalSymbol) ||
+ !(entry.data.rhs instanceof AsmGlobalSymbol) ||
+ !m.labels.get(".base").names.includes(entry.data.rhs.symbol_name)
+ ) {
+ return null;
+ }
+ return new Replacement([new AsmInstruction("bsr", [entry.data.lhs]), delay, m.labels.get(".base")], m.body.length);
+ }
+}
+
+export class NegateTPattern extends SimpleAsmPattern {
+ pattern = make_pattern("rotcl $r", "xor #1, $r", "rotcr $r");
+
+ replace(m) {
+ return new Replacement([new AsmInstruction("negatet.fictive", [])], m.body.length, []);
+ }
+}
+
+export class Shar31Pattern extends SimpleAsmPattern {
+ pattern = make_pattern("shll $r", "subc $r, $r");
+
+ replace(m) {
+ const reg = m.regs.get("r");
+ const temp = Register.fictive(reg.register_name);
+ return new Replacement(
+ [new AsmInstruction("move.fictive", [temp, reg]), new AsmInstruction("shll", [temp]), new AsmInstruction("shar.fictive", [reg, reg, new AsmLiteral(31)])],
+ m.body.length,
+ );
+ }
+}
+
+/** Replace writebacks in mov address modes by separate add instructions. */
+export class Sh2AddrModeWritebackPattern extends AsmPattern {
+ match(matcher) {
+ const instr = matcher.input[matcher.index];
+ if (!(instr instanceof Instruction) || !instr.args.length) return null;
+ if (!["mov.b", "mov.w", "mov.l"].includes(instr.mnemonic)) return null;
+
+ let addr, addr_arg;
+ if (instr.args[0] instanceof AsmAddressMode) {
+ addr = instr.args[0];
+ addr_arg = 0;
+ } else if (instr.args[1] instanceof AsmAddressMode) {
+ addr = instr.args[1];
+ addr_arg = 1;
+ } else return null;
+
+ if (addr.writeback === null) return null;
+ if (addr.base === SH_STACK_POINTER_REG) return null;
+
+ if (addr.base === instr.args[0] || addr.base === instr.args[1]) {
+ throw new DecompFailure("Writeback with base register also used as load/store value, " + `for instruction: ${instr}`);
+ }
+
+ pyassert(addr.addend === new AsmLiteral(0));
+
+ const new_args = [...instr.args];
+ new_args[addr_arg] = new AsmAddressMode(addr.base, addr.addend, null);
+ const stride = mov_stride(instr.mnemonic);
+ if (addr.writeback === Writeback.PRE) {
+ return new Replacement([new AsmInstruction("add", [new AsmLiteral(-stride), addr.base]), new AsmInstruction(instr.mnemonic, new_args)], 1);
+ }
+ return new Replacement([new AsmInstruction(instr.mnemonic, new_args), new AsmInstruction("add", [new AsmLiteral(stride), addr.base])], 1);
+ }
+}
+
+export class Shar16Pattern extends IrPattern {
+ replacement = "shar16.fictive $i, $o";
+ parts = ["swap.w $i, $t", "exts.w $t, $o"];
+}
+
+const R = (names) => names.map((r) => new Register(r));
+
+const SH2_ARGUMENT_REGS = R(["r4", "r5", "r6", "r7"]);
+const SH2_SIMPLE_TEMP_REGS = R(["r0", "r1", "r2", "r3"]);
+const SH2_TEMP_REGS = [...SH2_ARGUMENT_REGS, ...SH2_SIMPLE_TEMP_REGS, new Register("condition_bit")];
+const SH2_SAVED_REGS = R(["r8", "r9", "r10", "r11", "r12", "r13", "r14", "pr"]);
+const SH2_ALL_REGS = [...SH2_SAVED_REGS, ...SH2_TEMP_REGS, SH_STACK_POINTER_REG, ...R(["mach", "macl", "sr", "gbr", "vbr"])];
+
+const SH2_INSTRS_COMPARE = {
+ "cmp/pl": (a) => BinaryOp.scmp(a.reg(0), ">", new Literal(0)),
+ "cmp/pz": (a) => BinaryOp.scmp(a.reg(0), ">=", new Literal(0)),
+ "cmp/eq": (a) => BinaryOp.icmp(a.reg(1), "==", a.reg_or_s8_imm(0)),
+ "cmp/ge": (a) => BinaryOp.scmp(a.reg(1), ">=", a.reg(0)),
+ "cmp/gt": (a) => BinaryOp.scmp(a.reg(1), ">", a.reg(0)),
+ "cmp/hi": (a) => BinaryOp.ucmp(a.reg(1), ">", a.reg(0)),
+ "cmp/hs": (a) => BinaryOp.ucmp(a.reg(1), ">=", a.reg(0)),
+ "cmp/str": (a) => fn_op("M2C_CMP_STR", [a.reg(1), a.reg(0)], Type.boolean()),
+ tst: (a) =>
+ a.reg_ref(1) === a.raw_arg(0)
+ ? BinaryOp.icmp(a.reg(1), "==", new Literal(0))
+ : BinaryOp.icmp(BinaryOp.intptr(a.reg(1), "&", a.reg_or_s8_imm(0)), "==", new Literal(0)),
+};
+
+const SH2_INSTRS_READ_MODIFY_WRITE = {
+ // sh2 format is src, dst
+ // add handler is dest, left, right
+ add: (a) =>
+ a.raw_arg(0) instanceof Register
+ ? handle_add(with_raw_args(a, [a.raw_arg(1), a.raw_arg(1), a.raw_arg(0)]))
+ : handle_addi(a.reg_ref(1), a.reg_ref(1), a.reg(1), a.s8_imm(0), a),
+ sub: (a) => handle_sub(a.reg(1), a.reg(0)),
+ and: (a) => BinaryOp.int(a.reg(1), "&", a.reg_or_imm(0)),
+ or: (a) => handle_or(a.reg(1), a.reg_or_imm(0)),
+ xor: (a) => handle_xor(a.reg(1), a.reg_or_imm(0)),
+ xtrct: (a) => BinaryOp.uint(BinaryOp.ushift(a.reg(1), ">>", new Literal(16)), "|", BinaryOp.int(a.reg(0), "<<", new Literal(16))),
+};
+
+const SH2_INSTRS_SOURCE_DEST = {
+ not: (a) => handle_bitinv(a.reg(0)),
+ neg: (a) => UnaryOp.sint("-", a.reg(0)),
+ "exts.b": (a) => as_type(a.reg(0), Type.s8(), false),
+ "exts.w": (a) => as_type(a.reg(0), Type.s16(), false),
+ "extu.b": (a) => as_type(a.reg(0), Type.u8(), false),
+ "extu.w": (a) => as_type(a.reg(0), Type.u16(), false),
+ "swap.w": (a) => BinaryOp.int(BinaryOp.ushift(a.reg(0), "<<", new Literal(16)), "|", BinaryOp.ushift(a.reg(0), ">>", new Literal(16))),
+ "swap.b": (a) =>
+ BinaryOp.uint(
+ BinaryOp.uint(BinaryOp.int(a.reg(0), "&", new Literal(0xffff0000)), "|", BinaryOp.int(BinaryOp.int(a.reg(0), "&", new Literal(0xff)), "<<", new Literal(8))),
+ "|",
+ BinaryOp.int(BinaryOp.ushift(a.reg(0), ">>", new Literal(8)), "&", new Literal(0xff)),
+ ),
+ "shar16.fictive": (a) => fold_shift_right(a.reg(0), 16, { signed: true }),
+};
+
+const SH2_INSTRS_INTRINSICS = {
+ "shar.fictive": (a) => fold_shift_right(a.reg(1), a.imm_value(2), { signed: true }),
+ "vshar.fictive": (a) => BinaryOp.sshift(a.reg(1), ">>", a.reg(2)),
+ "vshlr.fictive": (a) => BinaryOp.ushift(a.reg(1), ">>", a.reg(2)),
+ "vshl.fictive": (a) => BinaryOp.int(a.reg(1), "<<", a.reg(2)),
+ "divs.fictive": (a) => BinaryOp.sint(a.reg(1), "/", a.reg(2)),
+ "divu.fictive": (a) => BinaryOp.uint(a.reg(1), "/", a.reg(2)),
+};
+
+const SH2_INSTRS_MULTIPLY = {
+ "mul.l": (a) => BinaryOp.int(a.reg(1), "*", a.reg(0)),
+ muls: (a) => BinaryOp.sint(as_s16(a.reg(1)), "*", as_s16(a.reg(0))),
+ mulu: (a) => BinaryOp.uint(as_u16(a.reg(1)), "*", as_u16(a.reg(0))),
+};
+
+const SH2_INSTRS_SHIFT = {
+ shll: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(1)), { allow_sll_chains: true }),
+ shlr: (a) => fold_shift_right(a.reg(0), 1, { signed: false }),
+ shar: (a) => fold_shift_right(a.reg(0), 1, { signed: true }),
+ shll2: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(2)), { allow_sll_chains: true }),
+ shlr2: (a) => fold_shift_right(a.reg(0), 2, { signed: false }),
+ shll8: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(8)), { allow_sll_chains: true }),
+ shlr8: (a) => fold_shift_right(a.reg(0), 8, { signed: false }),
+ shll16: (a) => fold_mul_chains(BinaryOp.int(a.reg(0), "<<", new Literal(16)), { allow_sll_chains: true }),
+ shlr16: (a) => fold_shift_right(a.reg(0), 16, { signed: false }),
+ rotl: (a) => BinaryOp.uint(BinaryOp.ushift(a.reg(0), "<<", new Literal(1)), "|", BinaryOp.ushift(a.reg(0), ">>", new Literal(31))),
+ rotr: (a) => BinaryOp.uint(BinaryOp.ushift(a.reg(0), ">>", new Literal(1)), "|", BinaryOp.ushift(a.reg(0), "<<", new Literal(31))),
+};
+
+const SH2_ATTRS = {
+ arch: Target.ArchEnum.SH,
+ re_comment: String.raw`!.*`,
+ supports_dollar_regs: false,
+ supports_at_addressing: true,
+ asm_word_size: 2,
+ has_delay_slots: true,
+ home_space_size: 0,
+ stack_pointer_reg: SH_STACK_POINTER_REG,
+ frame_pointer_regs: [new Register("r14")],
+ return_address_reg: new Register("pr"),
+ base_return_regs: [[new Register("r0"), false]],
+ all_return_regs: [new Register("r0"), new Register("r1")],
+ argument_regs: SH2_ARGUMENT_REGS,
+ simple_temp_regs: SH2_SIMPLE_TEMP_REGS,
+ temp_regs: SH2_TEMP_REGS,
+ saved_regs: SH2_SAVED_REGS,
+ all_regs: SH2_ALL_REGS,
+ aliased_regs: {},
+ instrs_compare: SH2_INSTRS_COMPARE,
+ instrs_read_modify_write: SH2_INSTRS_READ_MODIFY_WRITE,
+ instrs_source_dest: SH2_INSTRS_SOURCE_DEST,
+ instrs_intrinsics: SH2_INSTRS_INTRINSICS,
+ instrs_multiply: SH2_INSTRS_MULTIPLY,
+ instrs_shift: SH2_INSTRS_SHIFT,
+};
+
+const SH2_ASM_PATTERNS = () => [
+ new FarJumpPattern(),
+ new JumpTablePattern(),
+ new BrafJumpTablePattern(),
+ new BsrfCallPattern(),
+ new Sh2AddrModeWritebackPattern(),
+ new NegateTPattern(),
+ new Shar31Pattern(),
+];
+
+export class Sh2Arch extends Arch {
+ constructor() {
+ super();
+ // Python class attributes (set after super() so base-class constructors
+ // cannot shadow them with instance fields).
+ Object.assign(this, SH2_ATTRS);
+ this.asm_patterns = SH2_ASM_PATTERNS();
+ this.ir_patterns = [new Shar16Pattern()];
+ }
+
+ static mov_type(mnemonic) {
+ return mov_type(mnemonic);
+ }
+ static mov_stride(mnemonic) {
+ return mov_stride(mnemonic);
+ }
+ mov_type(mnemonic) {
+ return mov_type(mnemonic);
+ }
+ mov_stride(mnemonic) {
+ return mov_stride(mnemonic);
+ }
+
+ c_symbol_name(asm_name) {
+ if (asm_name.length >= 2 && asm_name[0] === "_" && (/^\p{L}$/u.test(asm_name[1]) || asm_name[1] === "_")) return asm_name.slice(1);
+ return asm_name;
+ }
+
+ missing_return() {
+ const meta = InstructionMeta.missing();
+ return [this.parse("rts", [], meta), this.parse("nop", [], meta)];
+ }
+
+ normalize_instruction(instr, asm_state) {
+ const map = { "muls.w": "muls", "mulu.w": "mulu" };
+ const mnemonic = has(map, instr.mnemonic) ? map[instr.mnemonic] : instr.mnemonic;
+ return new AsmInstruction(mnemonic, instr.args);
+ }
+
+ parse(mnemonic, args, meta) {
+ const cls = this;
+ let inputs = [];
+ let clobbers = [];
+ let outputs = [];
+ let is_return = false;
+ let is_load = false;
+ let is_store = false;
+ let has_delay_slot = false;
+ let is_conditional = false;
+ let jump_target = null;
+ let function_target = null;
+ let eval_fn = null;
+
+ if (mnemonic === "rts") {
+ pyassert(args.length === 0);
+ inputs = [new Register("pr")];
+ is_return = true;
+ has_delay_slot = true;
+ } else if (mnemonic === "nop") {
+ pyassert(args.length === 0);
+ } else if (["mov", "lds", "sts"].includes(mnemonic)) {
+ pyassert(args.length === 2 && args[1] instanceof Register);
+ outputs = [args[1]];
+ if (args[0] instanceof Register) {
+ inputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), a.reg(0));
+ } else {
+ pyassert(args[0] instanceof AsmLiteral);
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), a.s8_imm(0));
+ }
+ } else if (mnemonic === "move.fictive") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[1]];
+ outputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(0), a.reg(1));
+ } else if (mnemonic === "mova") {
+ pyassert(args.length === 2 && args[0] instanceof AsmGlobalSymbol && args[1] === new Register("r0"));
+ outputs = [new Register("r0")];
+ eval_fn = (s, a) => s.set_reg(new Register("r0"), a.full_imm(0));
+ } else if (["mov.b", "mov.l", "mov.w"].includes(mnemonic)) {
+ pyassert(args.length === 2);
+ if (args[0] instanceof Register) {
+ pyassert(args[1] instanceof AsmAddressMode);
+ inputs = [args[0], args[1].base];
+ if (args[1].addend instanceof Register) inputs.push(args[1].addend);
+ is_store = true;
+ if (args[1].writeback === null) {
+ eval_fn = (s, a) => {
+ const store_type = cls.mov_type(mnemonic);
+ const address = a.raw_arg(1);
+ pyassert(address instanceof AsmAddressMode);
+ let store;
+ if (address.addend instanceof Register) {
+ store = make_storex(with_raw_args(a, [a.raw_arg(0), address.base, address.addend]), store_type);
+ } else {
+ store = make_store(a, store_type);
+ }
+ if (store !== null) s.store_memory(store, a.reg_ref(0));
+ };
+ } else if (args[1].base === cls.stack_pointer_reg) {
+ pyassert(args[1].writeback === Writeback.PRE);
+ eval_fn = (s, a) => {
+ const source_raw = a.regs.get_raw(a.reg_ref(0));
+ if (source_raw === null || !s.stack_info.should_save(source_raw, null)) s.push_subroutine_arg(a.reg(0));
+ };
+ } else {
+ // writeback on other registers is rewritten into an explicit
+ // add by Sh2AddrModeWritebackPattern, so no eval_fn is needed.
+ }
+ } else {
+ pyassert(args[1] instanceof Register);
+ if (args[0] instanceof AsmAddressMode) {
+ inputs = [args[0].base];
+ if (args[0].addend instanceof Register) inputs.push(args[0].addend);
+ }
+ outputs = [args[1]];
+ is_load = true;
+ const load_type = cls.mov_type(mnemonic);
+ if (args[0] instanceof AsmAddressMode && args[0].addend instanceof Register) {
+ const indexed_base = args[0].base;
+ const indexed_addend = args[0].addend;
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), handle_loadx(with_raw_args(a, [a.raw_arg(1), indexed_base, indexed_addend]), load_type));
+ } else {
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), handle_load(with_raw_args(a, [a.raw_arg(1), a.raw_arg(0)]), load_type));
+ }
+ }
+ } else if (mnemonic === "sts.l" || mnemonic === "stc.l") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof AsmAddressMode && args[1].writeback === Writeback.PRE);
+ const mem = args[1];
+ inputs = [args[0], mem.base];
+ is_store = true;
+ eval_fn = (s, a) => {
+ pyassert(args[0] === new Register("pr"));
+ pyassert(mem.base === cls.stack_pointer_reg);
+ };
+ } else if (mnemonic === "lds.l" || mnemonic === "ldc.l") {
+ pyassert(args.length === 2 && args[0] instanceof AsmAddressMode && args[0].writeback === Writeback.POST && args[1] instanceof Register);
+ const mem = args[0];
+ inputs = [mem.base];
+ outputs = [args[1]];
+ is_load = true;
+ eval_fn = (s, a) => {
+ pyassert(args[1] === new Register("pr"));
+ pyassert(mem.base === cls.stack_pointer_reg);
+ };
+ } else if (mnemonic === "addc") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ const t_reg = new Register("condition_bit");
+ inputs = [args[0], args[1], t_reg];
+ outputs = [args[1], t_reg];
+ eval_fn = (s, a) => {
+ let result = handle_add_real(a.reg(1), a.reg(0), a);
+ result = handle_add_real(result, a.regs.get(t_reg), a);
+ result = s.set_reg(a.reg_ref(1), result);
+ s.set_reg(t_reg, new CarryBit(result));
+ };
+ } else if (mnemonic === "subc") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ const t_reg = new Register("condition_bit");
+ inputs = [args[0], args[1], t_reg];
+ outputs = [args[1], t_reg];
+ eval_fn = (s, a) => {
+ const lhs = a.reg(1);
+ const rhs = a.reg(0);
+ const carry = a.regs.get(t_reg);
+ const result = handle_sub(handle_sub(lhs, rhs), carry);
+ let borrow;
+ if (pyeq(carry, new Literal(0))) borrow = BinaryOp.ucmp(lhs, "<", rhs);
+ else if (pyeq(carry, new Literal(1))) borrow = BinaryOp.ucmp(lhs, "<=", rhs);
+ else {
+ borrow = new BinaryOp({
+ left: BinaryOp.ucmp(lhs, "<", rhs),
+ op: "||",
+ right: new BinaryOp({ left: BinaryOp.icmp(lhs, "==", rhs), op: "&&", right: condition_from_expr(carry), type: Type.boolean() }),
+ type: Type.boolean(),
+ });
+ }
+ s.set_reg(a.reg_ref(1), result);
+ s.set_reg(t_reg, borrow);
+ };
+ } else if (mnemonic === "negc") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ const t_reg = new Register("condition_bit");
+ inputs = [args[0], t_reg];
+ outputs = [args[1], t_reg];
+ eval_fn = (s, a) => {
+ const value = a.reg(0);
+ const carry = a.regs.get(t_reg);
+ const result = handle_sub(UnaryOp.int("-", value), carry);
+ let borrow;
+ if (pyeq(carry, new Literal(0))) borrow = BinaryOp.icmp(value, "!=", new Literal(0));
+ else if (pyeq(carry, new Literal(1))) borrow = new Literal(1);
+ else {
+ borrow = new BinaryOp({ left: BinaryOp.icmp(value, "!=", new Literal(0)), op: "||", right: condition_from_expr(carry), type: Type.boolean() });
+ }
+ s.set_reg(a.reg_ref(1), result);
+ s.set_reg(t_reg, borrow);
+ };
+ } else if (has(cls.instrs_read_modify_write, mnemonic)) {
+ pyassert(args.length === 2 && args[1] instanceof Register);
+ inputs = [args[1]];
+ if (args[0] instanceof Register) inputs.unshift(args[0]);
+ outputs = [args[1]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), cls.instrs_read_modify_write[mnemonic](a));
+ } else if (has(cls.instrs_source_dest, mnemonic)) {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[0]];
+ outputs = [args[1]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(1), cls.instrs_source_dest[mnemonic](a));
+ } else if (has(cls.instrs_intrinsics, mnemonic)) {
+ pyassert(args[0] instanceof Register);
+ inputs = args.slice(1).filter((arg) => arg instanceof Register);
+ outputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(0), cls.instrs_intrinsics[mnemonic](a));
+ } else if (has(cls.instrs_multiply, mnemonic)) {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[0], args[1]];
+ outputs = [new Register("macl")];
+ eval_fn = (s, a) => s.set_reg(new Register("macl"), cls.instrs_multiply[mnemonic](a));
+ } else if (mnemonic === "dmuls.l" || mnemonic === "dmulu.l") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[0], args[1]];
+ outputs = [new Register("mach"), new Register("macl")];
+ const high_op = mnemonic === "dmuls.l" ? "MULT_HI" : "MULTU_HI";
+ eval_fn = (s, a) => {
+ s.set_reg(new Register("mach"), fold_divmod(BinaryOp.int(a.reg(1), high_op, a.reg(0))));
+ s.set_reg(new Register("macl"), BinaryOp.int(a.reg(1), "*", a.reg(0)));
+ };
+ } else if (mnemonic === "clrmac") {
+ pyassert(!args.length);
+ outputs = [new Register("macl"), new Register("mach")];
+ eval_fn = (s, a) => {
+ s.set_reg(new Register("macl"), new Literal(0));
+ s.set_reg(new Register("mach"), new Literal(0));
+ };
+ } else if (mnemonic === "rotcl" || mnemonic === "rotcr") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ const t_reg = new Register("condition_bit");
+ inputs = [args[0], t_reg];
+ outputs = [args[0], t_reg];
+ eval_fn = (s, a) => {
+ const original = a.reg(0);
+ const carry_in = a.regs.get(t_reg);
+ let shifted, incoming_bit, carry_out;
+ if (mnemonic === "rotcl") {
+ shifted = BinaryOp.ushift(original, "<<", new Literal(1));
+ incoming_bit = carry_in;
+ carry_out = new CarryBit(shifted);
+ } else {
+ shifted = BinaryOp.ushift(original, ">>", new Literal(1));
+ incoming_bit = BinaryOp.uint(carry_in, "<<", new Literal(31));
+ carry_out = BinaryOp.int(original, "&", new Literal(1));
+ }
+ const result = pyeq(carry_in, new Literal(0)) ? shifted : BinaryOp.int(shifted, "|", incoming_bit);
+ s.set_reg(a.reg_ref(0), result);
+ s.set_reg(t_reg, carry_out);
+ };
+ } else if (has(cls.instrs_shift, mnemonic)) {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ inputs = [args[0]];
+ outputs = [args[0]];
+ const sets_t = ["shll", "shlr", "shar", "rotl", "rotr"].includes(mnemonic);
+ if (sets_t) outputs.push(new Register("condition_bit"));
+ eval_fn = (s, a) => {
+ const original = a.reg(0);
+ s.set_reg(a.reg_ref(0), cls.instrs_shift[mnemonic](a));
+ if (sets_t) {
+ let carry;
+ if (["shlr", "shar", "rotr"].includes(mnemonic)) {
+ carry = BinaryOp.intptr(original, "&", new Literal(1));
+ } else {
+ const as_u32_ = as_type(original, Type.u32(), true, { unify: false });
+ carry = BinaryOp.int(as_u32_, ">>", new Literal(31));
+ }
+ s.set_reg(new Register("condition_bit"), carry);
+ }
+ };
+ } else if (mnemonic === "dt") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ inputs = [args[0]];
+ outputs = [args[0], new Register("condition_bit")];
+ eval_fn = (s, a) => {
+ const value = s.set_reg(a.reg_ref(0), BinaryOp.intptr(a.reg(0), "-", new Literal(1)));
+ s.set_reg(new Register("condition_bit"), BinaryOp.icmp(value, "==", new Literal(0)));
+ };
+ } else if (has(cls.instrs_compare, mnemonic)) {
+ inputs = args.filter((arg) => arg instanceof Register);
+ outputs = [new Register("condition_bit")];
+ eval_fn = (s, a) => s.set_reg(new Register("condition_bit"), cls.instrs_compare[mnemonic](a));
+ } else if (["bf", "bf.s", "bt", "bt.s"].includes(mnemonic)) {
+ pyassert(args.length === 1);
+ inputs = [new Register("condition_bit")];
+ jump_target = get_jump_target(args[0]);
+ is_conditional = true;
+ has_delay_slot = mnemonic.endsWith(".s");
+ eval_fn = (s, a) => {
+ let condition = condition_from_expr(a.regs.get(new Register("condition_bit")));
+ if (mnemonic.startsWith("bf")) condition = condition.negated();
+ s.set_branch_condition(condition);
+ };
+ } else if (mnemonic === "bsr") {
+ pyassert(args.length === 1);
+ inputs = [...cls.argument_regs];
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = args[0];
+ has_delay_slot = true;
+ eval_fn = (s, a) => s.make_function_call(a.sym_imm(0), outputs);
+ } else if (mnemonic === "bra") {
+ pyassert(args.length === 1);
+ jump_target = get_jump_target(args[0]);
+ has_delay_slot = true;
+ } else if (mnemonic === "jmp") {
+ pyassert(args.length === 1 && args[0] instanceof AsmAddressMode && args[0].addend === new AsmLiteral(0));
+ inputs = [args[0].base];
+ jump_target = args[0].base;
+ is_conditional = true;
+ has_delay_slot = true;
+ eval_fn = (s, a) => {
+ const address = a.raw_arg(0);
+ pyassert(address instanceof AsmAddressMode);
+ s.set_switch_expr(a.regs.get(address.base));
+ };
+ } else if (mnemonic === "jsr") {
+ pyassert(args.length === 1 && args[0] instanceof AsmAddressMode && args[0].addend === new AsmLiteral(0));
+ const target_reg = args[0].base;
+ inputs = [...cls.argument_regs, target_reg];
+ outputs = [...cls.all_return_regs];
+ clobbers = [...cls.temp_regs];
+ function_target = target_reg;
+ has_delay_slot = true;
+ eval_fn = (s, a) => s.make_function_call(a.regs.get(target_reg), outputs);
+ } else if (mnemonic === "tablejmp.doubled.fictive") {
+ pyassert(args.length >= 2 && args[0] instanceof Register);
+ const targets = [];
+ for (const arg of args.slice(1)) {
+ pyassert(arg instanceof AsmGlobalSymbol);
+ targets.push(new JumpTarget(arg.symbol_name));
+ }
+ inputs = [args[0]];
+ jump_target = targets;
+ is_conditional = true;
+ eval_fn = (s, a) => {
+ let index = a.reg(0);
+ const unwrapped = early_unwrap(index);
+ if (unwrapped instanceof BinaryOp && unwrapped.op === "*" && pyeq(early_unwrap(unwrapped.right), new Literal(2))) {
+ index = unwrapped.left;
+ } else {
+ index = BinaryOp.ushift(index, ">>", new Literal(1));
+ }
+ s.set_switch_expr(index, true);
+ };
+ } else if (mnemonic === "movt") {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ inputs = [new Register("condition_bit")];
+ outputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(0), a.regs.get(new Register("condition_bit")));
+ } else if (mnemonic === "clrt" || mnemonic === "sett") {
+ pyassert(!args.length);
+ outputs = [new Register("condition_bit")];
+ const val = mnemonic === "sett" ? 1 : 0;
+ eval_fn = (s, a) => s.set_reg(new Register("condition_bit"), new Literal(val));
+ } else if (mnemonic === "negatet.fictive") {
+ pyassert(!args.length);
+ inputs = outputs = [new Register("condition_bit")];
+ eval_fn = (s, a) => {
+ const condition = condition_from_expr(a.regs.get(new Register("condition_bit")));
+ s.set_reg(new Register("condition_bit"), condition.negated());
+ };
+ } else if (mnemonic === "tas.b") {
+ pyassert(args.length === 1 && args[0] instanceof AsmAddressMode && args[0].addend === new AsmLiteral(0));
+ const base = args[0].base;
+ const t_reg = new Register("condition_bit");
+ inputs = [base];
+ outputs = [t_reg];
+ is_load = is_store = true;
+ eval_fn = (s, a) => {
+ const result = fn_op("M2C_TAS_B", [a.regs.get(base)], Type.intish());
+ s.set_reg(t_reg, result);
+ };
+ } else if (mnemonic === "stc") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ outputs = [args[1]];
+ eval_fn = (s, a) => {
+ const fn_name = "M2C_LOAD_" + a.reg_ref(0).register_name.toUpperCase();
+ s.set_reg(a.reg_ref(1), fn_op(fn_name, [], Type.u32()));
+ };
+ } else if (mnemonic === "ldc") {
+ pyassert(args.length === 2 && args[0] instanceof Register && args[1] instanceof Register);
+ inputs = [args[0]];
+ eval_fn = (s, a) => {
+ const fn_name = "M2C_STORE_" + a.reg_ref(1).register_name.toUpperCase();
+ s.write_statement(void_fn_op(fn_name, [a.reg(0)]));
+ };
+ } else {
+ const instr_str = String(new AsmInstruction(mnemonic, args));
+ eval_fn = (s, a) => {
+ const error = new ErrorExpr(`unknown instruction: ${instr_str}`);
+ s.write_statement(new ExprStmt(error));
+ };
+ }
+
+ return new Instruction({
+ mnemonic,
+ args,
+ meta,
+ inputs,
+ clobbers,
+ outputs,
+ eval_fn,
+ jump_target,
+ function_target,
+ is_conditional,
+ is_return,
+ is_load,
+ is_store,
+ has_delay_slot,
+ });
+ }
+
+ process_flowgraph(asm_data, flow_graph) {
+ // Find intrinsic functions and replace them by fake instructions (see upstream).
+ const seen = new Set();
+
+ const make_intrinsic_instruction = (fn_name) => {
+ const table = {
+ ___sdivsi3: "divs.fictive",
+ ___udivsi3: "divu.fictive",
+ ___ashrsi3: "vshar.fictive",
+ ___ashlsi3: "vshl.fictive",
+ ___lshrsi3: "vshlr.fictive",
+ };
+ const mn = has(table, fn_name) ? table[fn_name] : null;
+ if (mn !== null) return new AsmInstruction(mn, [new Register("r0"), new Register("r4"), new Register("r5")]);
+ if (fn_name.startsWith("___ashiftrt_r4_")) {
+ const shift = int_(fn_name.slice("___ashiftrt_r4_".length));
+ return new AsmInstruction("shar.fictive", [new Register("r4"), new Register("r4"), new AsmLiteral(shift)]);
+ }
+ return null;
+ };
+
+ const loc_from_mov_operand = (arg, stack_regs) => {
+ if (arg instanceof Register) return arg;
+ if (arg instanceof AsmAddressMode && stack_regs.has(arg.base) && arg.writeback === null) return StackLocation.from_offset(arg.addend);
+ return null;
+ };
+
+ const rec = (node, reg_sym_values, stack_regs) => {
+ if (seen.has(node)) return;
+ seen.add(node);
+ for (const ref of node.block.instruction_refs) {
+ const ins = ref.instruction;
+ if (ins.mnemonic === "mov" && ins.args[0] === this.stack_pointer_reg) {
+ pyassert(ins.args[1] instanceof Register);
+ stack_regs = new Set([...stack_regs, ins.args[1]]);
+ continue;
+ }
+ if (ins.mnemonic === "mov.l") {
+ const src = ins.args[0];
+ const dst = ins.args[1];
+ if (dst instanceof Register) {
+ const target = get_literal_pool_symbol(src, asm_data);
+ if (target !== null) {
+ const intrinsic = make_intrinsic_instruction(target);
+ if (intrinsic !== null) {
+ reg_sym_values.set(dst, intrinsic);
+ ref.instruction = ins.replace({ in_pattern: true });
+ continue;
+ }
+ }
+ }
+ const src_loc = loc_from_mov_operand(src, stack_regs);
+ const dst_loc = loc_from_mov_operand(dst, stack_regs);
+ if (src_loc !== null && dst_loc !== null) {
+ if (reg_sym_values.has(src_loc)) {
+ reg_sym_values.set(dst_loc, reg_sym_values.get(src_loc));
+ ref.instruction = ins.replace({ in_pattern: true });
+ } else if (reg_sym_values.has(dst_loc)) {
+ reg_sym_values.delete(dst_loc);
+ }
+ continue;
+ }
+ }
+ if (ins.mnemonic === "jsr") {
+ pyassert(ins.function_target instanceof Register);
+ const new_ins = reg_sym_values.get(ins.function_target) ?? null;
+ if (new_ins !== null) {
+ ref.replace_instruction(new_ins, this);
+ ref.instruction.clobbers.length = 0;
+ continue;
+ }
+ }
+ for (const loc of [...ins.clobbers, ...ins.outputs]) {
+ if (loc instanceof Register) {
+ if (reg_sym_values.has(loc)) reg_sym_values.delete(loc);
+ if (stack_regs.has(loc) && loc !== this.stack_pointer_reg) {
+ stack_regs = new Set([...stack_regs].filter((r) => r !== loc));
+ }
+ }
+ }
+ }
+ for (const child of node.children()) rec(child, new Map(reg_sym_values), stack_regs);
+ };
+
+ rec(flow_graph.entry_node(), new Map(), new Set([this.stack_pointer_reg]));
+ }
+
+ arg_name(loc) {
+ if (loc.offset !== null) return `arg${floordiv(loc.offset, 4) + 4}`;
+ pyassert(loc.reg !== null);
+ const reg_num = int_(loc.reg.register_name.slice(1));
+ return `arg${reg_num - 4}`;
+ }
+
+ function_abi(fn_sig, likely_regs, { for_call }) {
+ void for_call;
+ const known_slots = [];
+ let candidate_slots = [];
+ const possible_slots = [];
+
+ if (fn_sig.params_known) {
+ if (fn_sig.return_type.is_struct() && fn_sig.return_type.get_parameter_size_align_bytes()[0] > 8) {
+ known_slots.push(new AbiArgSlot(new ArgLoc(null, -1, new Register("r2")), Type.ptr(fn_sig.return_type), { name: "__return__", comment: "return" }));
+ }
+
+ let reg_num = 0;
+ for (const param of fn_sig.params) {
+ const param_type = param.type.decay();
+ const [size] = param_type.get_parameter_size_align_bytes();
+ const size_regs = floordiv(size + 3, 4);
+ const name = param.name;
+ for (let i = reg_num; i < reg_num + size_regs; i++) {
+ const unk_offset = 4 * (i - reg_num);
+ const reg = i < 4 ? new Register(`r${i + 4}`) : null;
+ const stack_loc = reg !== null ? null : (i - 4) * 4;
+ let name2, sub_type, comment;
+ if (size_regs > 1) {
+ name2 = name ? `${name}_unk${format(unk_offset, "X")}` : null;
+ sub_type = Type.any();
+ comment = `${param_type}+${format(unk_offset, "#x")}`;
+ } else {
+ pyassert(unk_offset === 0);
+ name2 = name;
+ sub_type = param_type;
+ comment = null;
+ }
+ known_slots.push(new AbiArgSlot(new ArgLoc(stack_loc, i, reg), sub_type, { name: name2, comment }));
+ }
+ reg_num += size_regs;
+ }
+
+ if (fn_sig.is_variadic) {
+ for (let i = reg_num; i < 4; i++) candidate_slots.push(new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i + 4}`)), Type.intptr()));
+ }
+ } else {
+ candidate_slots = [0, 1, 2, 3].map((i) => new AbiArgSlot(new ArgLoc(null, i, new Register(`r${i + 4}`)), Type.intptr()));
+ }
+
+ let highest_likely = -1;
+ for (let i = 4; i < 8; i++) {
+ if (!likely_regs.has(new Register(`r${i}`))) break;
+ if (likely_regs.get(new Register(`r${i}`))) highest_likely = i;
+ }
+
+ for (const slot of candidate_slots) {
+ pyassert(slot.loc.reg !== null);
+ if (int_(slot.loc.reg.register_name.slice(1)) <= highest_likely) possible_slots.push(slot);
+ }
+
+ return new Abi({ arg_slots: known_slots, possible_slots });
+ }
+
+ function_return(expr) {
+ return new Map([
+ [new Register("r0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.intptr() })],
+ [new Register("r1"), as_u32(new Cast(expr, { reinterpret: true, silent: false, type: Type.u64() }))],
+ ]);
+ }
+}
+
+const SH4_FP_ARGUMENT_REGS = [4, 5, 6, 7, 8, 9, 10, 11].map((i) => new Register(`fr${i}`));
+const SH4_FP_TEMP_REGS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => new Register(`fr${i}`));
+const SH4_FP_SAVED_REGS = [12, 13, 14, 15].map((i) => new Register(`fr${i}`));
+
+const SH4_ATTRS = {
+ base_return_regs: [
+ [new Register("r0"), false],
+ [new Register("fr0"), true],
+ ],
+ all_return_regs: [new Register("r0"), new Register("r1"), new Register("fr0")],
+ fp_argument_regs: SH4_FP_ARGUMENT_REGS,
+ fp_temp_regs: SH4_FP_TEMP_REGS,
+ fp_saved_regs: SH4_FP_SAVED_REGS,
+ argument_regs: [...SH2_ARGUMENT_REGS, ...SH4_FP_ARGUMENT_REGS],
+ temp_regs: [...SH2_TEMP_REGS, ...SH4_FP_TEMP_REGS, new Register("fpul")],
+ saved_regs: [...SH2_SAVED_REGS, ...SH4_FP_SAVED_REGS],
+ all_regs: [...SH2_ALL_REGS, ...SH4_FP_TEMP_REGS, ...SH4_FP_SAVED_REGS, new Register("fpul"), new Register("fpscr")],
+ instrs_load_const: {
+ fldi0: (a) => new Literal(0x00000000, Type.f32()),
+ fldi1: (a) => new Literal(0x3f800000, Type.f32()),
+ },
+};
+
+export class Sh4Arch extends Sh2Arch {
+ constructor() {
+ super();
+ Object.assign(this, SH4_ATTRS);
+ }
+
+ parse(mnemonic, args, meta) {
+ const cls = this;
+ const inputs = [];
+ const clobbers = [];
+ let outputs = [];
+ let eval_fn = null;
+
+ if (has(cls.instrs_load_const, mnemonic)) {
+ pyassert(args.length === 1 && args[0] instanceof Register);
+ outputs = [args[0]];
+ eval_fn = (s, a) => s.set_reg(a.reg_ref(0), cls.instrs_load_const[mnemonic](a));
+ }
+
+ if (eval_fn !== null) return new Instruction({ mnemonic, args, meta, inputs, clobbers, outputs, eval_fn });
+
+ return super.parse(mnemonic, args, meta);
+ }
+
+ function_return(expr) {
+ const ret = Sh2Arch.prototype.function_return.call(this, expr);
+ ret.set(new Register("fr0"), new Cast(expr, { reinterpret: true, silent: true, type: Type.floatish() }));
+ return ret;
+ }
+}
diff --git a/packages/romdev-m2c/src/asm_file.js b/packages/romdev-m2c/src/asm_file.js
new file mode 100644
index 00000000..f4f2509e
--- /dev/null
+++ b/packages/romdev-m2c/src/asm_file.js
@@ -0,0 +1,779 @@
+// Port of m2c/asm_file.py
+import fs from "node:fs";
+import path from "node:path";
+import { DecompFailure } from "./error.js";
+import { CodingStyle } from "./options.js";
+import { AsmGlobalSymbol, AsmLiteral, AsmState, RegFormatter, parse_arg, traverse_arg } from "./asm_instruction.js";
+import { Instruction, InstructionMeta, parse_instruction } from "./instruction.js";
+import { AssertionError, DefaultMap, IndexError, ValueError, band, format, int_, intern, isspace, pyassert, pymod, split_ws, str as pystr } from "./py.js";
+import { print } from "./io.js";
+
+const RE_COMMA_OR_STRING = /,|"(?:\\.|[^\\"])*"/g;
+
+export class Label {
+ // Various pattern matching code assumes that there cannot be consecutive
+ // labels, and to deal with this we allow for consecutive labels to be
+ // merged together. As a consequence, we allow a Label to have more than one
+ // name. When we need a single name to refer to one, we use the first one.
+ constructor(names) {
+ this.names = names;
+ return intern(this, [names]);
+ }
+ static new(name) {
+ return new Label([name]);
+ }
+ toString() {
+ return this.names[0];
+ }
+}
+
+export class Function {
+ constructor({ name, body = [], reg_formatter = new RegFormatter() }) {
+ this.name = name;
+ this.body = body;
+ this.reg_formatter = reg_formatter;
+ }
+ new_label(name) {
+ const label = Label.new(name);
+ if (this.body.length && this.body[this.body.length - 1] === label) return;
+ this.body.push(label);
+ }
+ new_instruction(instruction) {
+ this.body.push(instruction);
+ }
+ bodyless_copy() {
+ return new Function({ name: this.name, reg_formatter: this.reg_formatter });
+ }
+ toString() {
+ const body = this.body.map((item) => (item instanceof Instruction ? String(item) : ` ${item}:`)).join("\n");
+ return `glabel ${this.name}\n${body}`;
+ }
+}
+
+export class AsmSymbolicData {
+ constructor(data, size) {
+ this.data = data;
+ this.size = size;
+ }
+ as_symbol_without_addend() {
+ if (this.data instanceof AsmGlobalSymbol && this.size === 4) return this.data.symbol_name;
+ return null;
+ }
+}
+
+export function concatBytes(a, b) {
+ const out = new Uint8Array(a.length + b.length);
+ out.set(a, 0);
+ out.set(b, a.length);
+ return out;
+}
+
+export class AsmDataEntry {
+ constructor(sort_order, { data = [], is_string = false, is_readonly = false, is_bss = false, is_text = false, is_jtbl = false, used_as_literal = false } = {}) {
+ this.sort_order = sort_order;
+ this.data = data;
+ this.is_string = is_string;
+ this.is_readonly = is_readonly;
+ this.is_bss = is_bss;
+ this.is_text = is_text;
+ this.is_jtbl = is_jtbl;
+ // Mutable state:
+ this.used_as_literal = used_as_literal;
+ }
+
+ /** Return the range of possible sizes, if padding were stripped. */
+ size_range_bytes() {
+ let max_size = 0;
+ for (const x of this.data) {
+ if (x instanceof AsmSymbolicData) max_size += x.size;
+ else max_size += x.length;
+ }
+ let padding_size = 0;
+ if (this.data.length && this.data[this.data.length - 1] instanceof Uint8Array) {
+ pyassert(this.data.length === 1 || this.data[this.data.length - 2] instanceof AsmSymbolicData);
+ const last = this.data[this.data.length - 1];
+ for (let i = last.length - 1; i >= 0; i--) {
+ if (last[i] !== 0) break;
+ padding_size += 1;
+ }
+ }
+ padding_size = Math.min(padding_size, 15);
+ pyassert(padding_size <= max_size);
+ if (max_size === padding_size && max_size !== 0) return [1, max_size];
+ return [max_size - padding_size, max_size];
+ }
+
+ data_at_offset(offset, size) {
+ for (let data of this.data) {
+ const subsize = data instanceof Uint8Array ? data.length : data.size;
+ if (offset >= subsize) {
+ offset -= subsize;
+ continue;
+ }
+ if (data instanceof Uint8Array) {
+ data = data.slice(offset, offset + size);
+ if (data.length !== size) return null;
+ return data;
+ } else {
+ if (data.size !== size) return null;
+ return data;
+ }
+ }
+ return null;
+ }
+}
+
+export class AsmData {
+ constructor({ values = new Map(), mentioned_labels = new Set() } = {}) {
+ this.values = values;
+ this.mentioned_labels = mentioned_labels;
+ }
+ merge_into(other) {
+ for (const [sym, value] of this.values) other.values.set(sym, value);
+ for (const label of this.mentioned_labels) other.mentioned_labels.add(label);
+ }
+ is_likely_char(c) {
+ return (0x20 <= c && c < 0x7f) || [0, 7, 8, 9, 10, 13, 27].includes(c);
+ }
+ detect_heuristic_strings() {
+ for (const ent of this.values.values()) {
+ if (
+ ent.is_readonly &&
+ ent.data.length === 1 &&
+ ent.data[0] instanceof Uint8Array &&
+ ent.data[0].length > 1 &&
+ ent.data[0][0] !== 0 &&
+ [...ent.data[0]].every((x) => this.is_likely_char(x))
+ ) {
+ ent.is_string = true;
+ }
+ }
+ }
+}
+
+export class AsmFile {
+ constructor(filename, reg_formatter) {
+ this.filename = filename;
+ this.reg_formatter = reg_formatter;
+ this.functions = [];
+ this.asm_data = new AsmData();
+ this.current_function = null;
+ this.current_data = null;
+ }
+ new_function(name) {
+ this.current_function = new Function({ name, reg_formatter: this.reg_formatter });
+ this.functions.push(this.current_function);
+ }
+ new_instruction(instruction) {
+ if (this.current_function === null) {
+ if (instruction.mnemonic === "nop") return;
+ throw new DecompFailure(`unsupported non-nop instruction outside of function (${instruction})`);
+ }
+ this.current_function.new_instruction(instruction);
+ this.current_data = null;
+ }
+ new_label(label_name) {
+ pyassert(this.current_function !== null);
+ this.current_function.new_label(label_name);
+ }
+ new_data_label(symbol_name, { is_readonly = false, is_bss = false, is_text = false } = {}) {
+ const sort_order = [this.filename, this.asm_data.values.size];
+ this.current_data = new AsmDataEntry(sort_order, { is_readonly, is_bss, is_text });
+ this.asm_data.values.set(symbol_name, this.current_data);
+ }
+ new_symbolic_data(data, size) {
+ if (this.current_data !== null) this.current_data.data.push(new AsmSymbolicData(data, size));
+ for (const subexpr of traverse_arg(data)) {
+ if (subexpr instanceof AsmGlobalSymbol) this.asm_data.mentioned_labels.add(subexpr.symbol_name);
+ }
+ }
+ new_data_bytes(data, { is_string }) {
+ if (this.current_data === null) return;
+ const d = this.current_data.data;
+ if (!d.length && is_string) this.current_data.is_string = true;
+ if (d.length && d[d.length - 1] instanceof Uint8Array) d[d.length - 1] = concatBytes(d[d.length - 1], data);
+ else d.push(data);
+ }
+ toString() {
+ const functions_str = this.functions.map((f) => String(f)).join("\n\n");
+ return `# ${this.filename}\n${functions_str}`;
+ }
+}
+
+/**
+ * Split a string of comma-separated arguments, handling quotes. Mirrors
+ * Python's csv.reader(delimiter=",", doublequote=False, escapechar="\\",
+ * quotechar='"', skipinitialspace=True) on a single line.
+ */
+export function split_quotable_arg_list(args) {
+ if (args === "") return [];
+ const fields = [];
+ let field = "";
+ let state = "START_FIELD";
+ for (const c of args) {
+ switch (state) {
+ case "START_FIELD":
+ if (c === '"') state = "IN_QUOTED_FIELD";
+ else if (c === "\\") state = "ESCAPED_CHAR";
+ else if (c === " ") {
+ /* skipinitialspace */
+ } else if (c === ",") {
+ fields.push(field);
+ field = "";
+ } else {
+ field += c;
+ state = "IN_FIELD";
+ }
+ break;
+ case "ESCAPED_CHAR":
+ field += c;
+ state = "IN_FIELD";
+ break;
+ case "IN_FIELD":
+ if (c === "\\") state = "ESCAPED_CHAR";
+ else if (c === ",") {
+ fields.push(field);
+ field = "";
+ state = "START_FIELD";
+ } else field += c;
+ break;
+ case "IN_QUOTED_FIELD":
+ if (c === "\\") state = "ESCAPE_IN_QUOTED_FIELD";
+ else if (c === '"') state = "IN_FIELD";
+ else field += c;
+ break;
+ case "ESCAPE_IN_QUOTED_FIELD":
+ field += c;
+ state = "IN_QUOTED_FIELD";
+ break;
+ }
+ }
+ fields.push(field);
+ return fields.map((a) => a.trim());
+}
+
+export function split_arg_list(args) {
+ if (!args.includes('"')) return args.split(",").map((a) => a.trim());
+ const commas = [];
+ for (const m of args.matchAll(RE_COMMA_OR_STRING)) if (m[0] === ",") commas.push(m.index);
+ const starts = [-1, ...commas];
+ const ends = [...commas, args.length];
+ return starts.map((a, i) => args.slice(a + 1, ends[i]).trim());
+}
+
+const utf8 = new TextEncoder();
+
+export function parse_ascii_directive(line, z) {
+ // This is wrong wrt encodings; the assembler really operates on bytes and
+ // not chars. But for our purposes it should be good enough.
+ let in_quote = false;
+ let num_parts = 0;
+ const ret = [];
+ const chars = [...line];
+ let i = 0;
+ const digits = "0123456789";
+ while (i < chars.length) {
+ let c = chars[i];
+ i += 1;
+ if (!in_quote) {
+ if (c === '"') {
+ in_quote = true;
+ num_parts += 1;
+ }
+ } else {
+ if (c === '"') {
+ in_quote = false;
+ if (z) ret.push(0);
+ continue;
+ }
+ if (c !== "\\") {
+ ret.push(...utf8.encode(c));
+ continue;
+ }
+ if (i === chars.length) throw new DecompFailure("backslash at end of .ascii line not supported: " + line);
+ c = chars[i];
+ i += 1;
+ const char_escapes = { b: 8, f: 12, n: 10, r: 13, t: 9, v: 11 };
+ if (Object.prototype.hasOwnProperty.call(char_escapes, c)) ret.push(char_escapes[c]);
+ else if (c === "x") {
+ let value = 0;
+ while (i < chars.length && (digits + "abcdefABCDEF").includes(chars[i])) {
+ value = value * 16 + parseInt(chars[i], 16);
+ i += 1;
+ }
+ ret.push(value % 256);
+ } else if (digits.includes(c)) {
+ let it = 0;
+ let value = parseInt(c, 10);
+ while (i < chars.length && digits.includes(chars[i]) && it < 2) {
+ value = value * 8 + parseInt(chars[i], 10);
+ i += 1;
+ it += 1;
+ }
+ ret.push(value & 0xff);
+ } else {
+ ret.push(...utf8.encode(c));
+ }
+ }
+ }
+ if (in_quote) throw new DecompFailure("unterminated string literal: " + line);
+ if (num_parts === 0) throw new DecompFailure(".ascii with no string: " + line);
+ return Uint8Array.from(ret);
+}
+
+function add_warning(warnings, n) {
+ if (!warnings.includes(n)) warnings.push(n);
+}
+
+function pyListRepr(arr) {
+ return "[" + arr.map((s) => `'${s.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`).join(", ") + "]";
+}
+
+export function parse_incbin(args, options, warnings) {
+ let filename, offset, size;
+ try {
+ if (args.length === 3) {
+ filename = args[0];
+ offset = int_(args[1], 0);
+ size = int_(args[2], 0);
+ } else if (args.length === 1) {
+ filename = args[0];
+ offset = 0;
+ size = -1;
+ } else throw new ValueError();
+ } catch (e) {
+ if (e instanceof ValueError) throw new DecompFailure(`Could not parse asm_data .incbin directive: ${pyListRepr(args)}`);
+ throw e;
+ }
+ if (!options.incbin_dirs.length) {
+ add_warning(warnings, `Skipping .incbin directive for ${filename}, pass --incbin-dir to set a search directory`);
+ return null;
+ }
+ for (const incbin_dir of options.incbin_dirs) {
+ const full_path = path.join(incbin_dir, filename);
+ let data;
+ try {
+ const buf = fs.readFileSync(full_path);
+ data = size < 0 ? buf.subarray(offset) : buf.subarray(offset, offset + size);
+ data = new Uint8Array(data);
+ } catch {
+ continue;
+ }
+ if (size >= 0 && data.length !== size) {
+ add_warning(warnings, `Unable to read ${size} bytes from ${full_path} at ${format(offset, "#x")} (got ${data.length} bytes)`);
+ return null;
+ }
+ return data;
+ }
+ add_warning(warnings, `Unable to find ${filename} in any of ${options.incbin_dirs.length} search paths`);
+ return null;
+}
+
+function check_ifdef(macro_name, asm_state, warnings, directive) {
+ if (!asm_state.defines.has(macro_name)) {
+ asm_state.defines.set(macro_name, null);
+ add_warning(warnings, `Note: assuming ${macro_name} is unset for ${directive}, ` + `pass -D${macro_name}/-U${macro_name} to set/unset explicitly.`);
+ }
+ return asm_state.defines.get(macro_name) !== null;
+}
+
+function eval_cpp_if(expr, asm_state, warnings, directive) {
+ const token_re = /[a-zA-Z0-9_]+|&&|\|\||./gs;
+ const tokens = [...expr.matchAll(token_re)].map((m) => m[0]).filter((t) => !isspace(t));
+ let i = 0;
+ const tok_at = (j) => {
+ if (j >= tokens.length) throw new IndexError("list index out of range");
+ return tokens[j];
+ };
+ const parse1 = () => {
+ const tok = tok_at(i);
+ i += 1;
+ if (tok === "!") return !parse1();
+ if (tok === "(") {
+ const r = parse3();
+ pyassert(tok_at(i) === ")");
+ i += 1;
+ return r;
+ }
+ if (tok === "defined") {
+ pyassert(tok_at(i) === "(");
+ const w = tok_at(i + 1);
+ pyassert(tok_at(i + 2) === ")");
+ i += 3;
+ return check_ifdef(w, asm_state, warnings, directive);
+ }
+ if (/^\p{N}/u.test(tok)) return Boolean(int_(tok, 0));
+ const value = asm_state.defines.get(tok) ?? null;
+ if (value === null) {
+ check_ifdef(tok, asm_state, warnings, directive);
+ return false;
+ }
+ if (!(value instanceof AsmLiteral)) throw new DecompFailure(`Unable to evaluate if condition: ${value}`);
+ return Boolean(value.value);
+ };
+ const parse2 = () => {
+ let r = parse1();
+ while (i < tokens.length && tokens[i] === "&&") {
+ i += 1;
+ r = parse1() && r;
+ }
+ return r;
+ };
+ const parse3 = () => {
+ let r = parse2();
+ while (i < tokens.length && tokens[i] === "||") {
+ i += 1;
+ r = parse2() || r;
+ }
+ return r;
+ };
+ let ret;
+ try {
+ ret = parse3();
+ pyassert(i === tokens.length);
+ } catch (e) {
+ if (e instanceof AssertionError || e instanceof IndexError || e instanceof ValueError) throw new DecompFailure(`Failed to parse #if condition: ${expr}`);
+ throw e;
+ }
+ return ret;
+}
+
+/** Python float() on a string. */
+export function py_float(s) {
+ const t = s.trim().replace(/(?<=\d)_(?=\d)/g, "");
+ if (/^[+-]?(inf|infinity)$/i.test(t)) return t.startsWith("-") ? -Infinity : Infinity;
+ if (/^[+-]?nan$/i.test(t)) return NaN;
+ if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(t)) throw new ValueError(`could not convert string to float: '${s}'`);
+ return Number(t);
+}
+
+function intToBytes(v, size, big) {
+ let b = BigInt(v);
+ const out = new Uint8Array(size);
+ for (let k = 0; k < size; k++) {
+ out[big ? size - 1 - k : k] = Number(b & 0xffn);
+ b >>= 8n;
+ }
+ return out;
+}
+
+/** Read a text file as Python's open(..., encoding="utf-8-sig") line iterator would. */
+export function read_lines(text) {
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
+ text = text.replace(/\r\n?/g, "\n");
+ const lines = [];
+ let start = 0;
+ for (;;) {
+ const j = text.indexOf("\n", start);
+ if (j < 0) {
+ if (start < text.length) lines.push(text.slice(start));
+ break;
+ }
+ lines.push(text.slice(start, j + 1));
+ start = j + 1;
+ }
+ return lines;
+}
+
+/**
+ * @param {{name:string, text:string}} f file name and contents
+ */
+export function parse_file(f, arch, options) {
+ const filename = path.basename(f.name);
+ const reg_formatter = new RegFormatter();
+ const asm_file = new AsmFile(filename, reg_formatter);
+ let curr_section = ".text";
+ const section_sizes = new DefaultMap(() => 0);
+ const warnings = [];
+ const preproc_defines = new Map();
+ for (const [key, value] of options.preproc_defines) preproc_defines.set(key, value === null ? null : new AsmLiteral(value));
+ // NULL is a non-standard but common asm macro that expands to 0
+ preproc_defines.set("NULL", new AsmLiteral(0));
+ const asm_state = new AsmState({ defines: preproc_defines, reg_formatter });
+
+ let ifdef_level = 0;
+ const ifdef_levels = [];
+
+ const re_comment_replacer = (s) => (s[0] === '"' ? s : " ");
+ const re_whitespace_or_string = /\s+|"(?:\\.|[^\\"])*"/g;
+ const re_local_glabel = /^L(_.*_)?[0-9A-F]{7,8}/;
+ const re_local_label = /^(?:loc_|locret_|def_|lbl_|LAB_|switchD_|jump_|LF?[0-9]+$|_[0-9A-Fa-f]{7,8}(?:_.*)?$)/;
+ const re_label = /^(?:([a-zA-Z0-9_.$]+)|"([a-zA-Z0-9_.$<>@,-]+)"):/;
+
+ const data_directives = {
+ ".word": arch.asm_word_size,
+ ".gpword": 4,
+ ".4byte": 4,
+ ".long": 4,
+ ".short": 2,
+ ".half": 2,
+ ".2byte": 2,
+ ".byte": 1,
+ };
+ const LabelKind = { GLOBAL: "global", LOCAL: "local", JUMP_TARGET: "jump_target" };
+
+ let directive;
+ let line;
+ const fail_parse = () => {
+ throw new DecompFailure(`Could not parse asm_data ${directive} in ${curr_section}: ${line}`);
+ };
+ const try_parse = (parser) => {
+ try {
+ return parser();
+ } catch {
+ fail_parse();
+ }
+ };
+ const parse_int = (w) => {
+ const value = try_parse(() => parse_arg(w, arch, asm_state));
+ if (!(value instanceof AsmLiteral)) fail_parse();
+ return value.value;
+ };
+ const pack = (fmt, val) => {
+ const little = !options.target.is_big_endian();
+ if (fmt === "f") {
+ if (Number.isFinite(val) && Math.abs(val) > 3.4028235677973366e38) throw new Error("OverflowError: float too large to pack with f format");
+ const dv = new DataView(new ArrayBuffer(4));
+ dv.setFloat32(0, val, little);
+ return new Uint8Array(dv.buffer);
+ }
+ const dv = new DataView(new ArrayBuffer(8));
+ dv.setFloat64(0, val, little);
+ return new Uint8Array(dv.buffer);
+ };
+ const emit_bytes = (data, { is_string = false } = {}) => {
+ asm_file.new_data_bytes(data, { is_string });
+ section_sizes.set(curr_section, section_sizes.get(curr_section) + data.length);
+ };
+ const emit_word = (w, size) => {
+ const value = try_parse(() => parse_arg(w, arch, asm_state));
+ if (value instanceof AsmLiteral) {
+ const ival = BigInt.asUintN(size * 8, BigInt(value.value));
+ emit_bytes(intToBytes(ival, size, options.target.is_big_endian()));
+ } else {
+ asm_file.new_symbolic_data(value, size);
+ section_sizes.set(curr_section, section_sizes.get(curr_section) + size);
+ }
+ };
+
+ const re_comment_or_string = new RegExp(arch.re_comment + String.raw`|/\*.*?\*/|"(?:\\.|[^\\"])*"`, "g");
+ const lines = read_lines(f.text);
+ for (let idx = 0; idx < lines.length; idx++) {
+ const lineno = idx + 1;
+ line = lines[idx];
+ const emit_goto = options.goto_patterns.some((pattern) => line.includes(pattern));
+
+ // Convert C preprocessor directives into asm ones
+ let is_c_preproc_command = false;
+ const ws = split_ws(line);
+ if (ws.length && ["#ifdef", "#ifndef", "#else", "#if", "#elif", "#elifdef", "#elifndef", "#endif", "#define"].includes(ws[0])) {
+ is_c_preproc_command = true;
+ line = "." + line.slice(1);
+ }
+
+ // Strip comments and whitespace (but not within strings)
+ line = line.replace(re_comment_or_string, re_comment_replacer);
+ line = line.replace(re_whitespace_or_string, re_comment_replacer);
+ line = line.trim();
+
+ const process_label = (label, { kind }) => {
+ if (curr_section === ".rodata") asm_file.new_data_label(label, { is_readonly: true });
+ else if (curr_section === ".data") asm_file.new_data_label(label);
+ else if (curr_section === ".bss") asm_file.new_data_label(label, { is_bss: true });
+ else if (curr_section === ".text") {
+ asm_file.new_data_label(label, { is_readonly: true, is_text: true });
+ if (label.startsWith(".") || kind === LabelKind.JUMP_TARGET) {
+ if (asm_file.current_function !== null) asm_file.new_label(label);
+ } else if ((re_local_glabel.test(label) || (kind !== LabelKind.GLOBAL && re_local_label.test(label))) && asm_file.current_function !== null) {
+ asm_file.new_label(label);
+ } else {
+ asm_file.new_function(label);
+ }
+ }
+ };
+
+ // Check for labels
+ for (;;) {
+ const g = re_label.exec(line);
+ if (!g) break;
+ const label = g[1] || g[2];
+ if (ifdef_level === 0) process_label(label, { kind: LabelKind.LOCAL });
+ line = line.slice(g[0].length).trim();
+ }
+
+ if (!line) continue;
+
+ if (line.includes("=") && !is_c_preproc_command) {
+ const k = line.indexOf("=");
+ const key = line.slice(0, k).trim();
+ const value = line.slice(k + 1);
+ if (!key.includes(" ")) line = `.set ${key}, ${value}`;
+ }
+
+ directive = split_ws(line)[0];
+ if (directive.startsWith(".")) {
+ // Assembler directive.
+ const sp = line.indexOf(" ");
+ const args_str = sp < 0 ? "" : line.slice(sp + 1);
+ if (is_c_preproc_command) {
+ line = "#" + line.slice(1);
+ directive = split_ws(line)[0];
+ }
+ if ([".ifdef", ".ifndef", "#ifdef", "#ifndef"].includes(directive)) {
+ let active = check_ifdef(args_str, asm_state, warnings, directive);
+ if (directive.slice(1) === "ifndef") active = !active;
+ const level = 1 - Number(active);
+ ifdef_level += level;
+ ifdef_levels.push(level);
+ } else if (directive === ".if") {
+ const parts = split_ws(line);
+ if (parts.length < 2) throw new IndexError("list index out of range");
+ const macro_name = parts[1];
+ let active;
+ if (macro_name === "0") active = false;
+ else if (macro_name === "1") active = true;
+ else {
+ active = true;
+ add_warning(warnings, `Note: ignoring .if ${macro_name} directive`);
+ }
+ const level = 1 - Number(active);
+ ifdef_level += level;
+ ifdef_levels.push(level);
+ } else if (directive === "#if") {
+ const active = eval_cpp_if(args_str, asm_state, warnings, directive);
+ const level = 1 - Number(active);
+ ifdef_level += level;
+ ifdef_levels.push(level);
+ } else if (["#elif", "#elifdef", "#elifndef", "#else", ".else"].includes(directive)) {
+ if (!ifdef_levels.length) throw new IndexError("pop from empty list");
+ let level = ifdef_levels.pop();
+ ifdef_level -= level;
+ if (level === 1) {
+ let active;
+ if (directive === "#elifdef") active = check_ifdef(args_str, asm_state, warnings, directive);
+ else if (directive === "#elifndef") active = !check_ifdef(args_str, asm_state, warnings, directive);
+ else if (directive === "#elif") active = eval_cpp_if(args_str, asm_state, warnings, directive);
+ else active = true;
+ level = 1 - Number(active);
+ } else level = 2;
+ ifdef_level += level;
+ ifdef_levels.push(level);
+ } else if (directive === ".endif" || directive === "#endif") {
+ if (!ifdef_levels.length) throw new IndexError("pop from empty list");
+ ifdef_level -= ifdef_levels.pop();
+ } else if (directive === ".macro") {
+ ifdef_level += 1;
+ } else if (directive === ".endm") {
+ ifdef_level -= 1;
+ } else if (directive === ".fn") {
+ const args = split_quotable_arg_list(args_str);
+ asm_file.new_function(args[0]);
+ } else if (ifdef_level === 0) {
+ if (directive === ".section") {
+ curr_section = split_ws(line)[1].split(",")[0];
+ if ([".rdata", ".late_rodata", ".sdata2"].includes(curr_section)) curr_section = ".rodata";
+ else if (curr_section === ".sdata") curr_section = ".data";
+ else if (curr_section.startsWith(".text")) curr_section = ".text";
+ } else if (directive === ".rdata" || directive === ".rodata" || directive === ".late_rodata") {
+ curr_section = ".rodata";
+ } else if (directive === ".data") curr_section = ".data";
+ else if (directive === ".bss") curr_section = ".bss";
+ else if (directive === ".text") curr_section = ".text";
+ else if (directive === ".set") {
+ const args = split_quotable_arg_list(args_str);
+ if (args.length === 1) {
+ // ".set noreorder" or similar, just ignore
+ } else if (args.length === 2) asm_state.defines.set(args[0], parse_arg(args[1], arch, asm_state));
+ else throw new DecompFailure(`Could not parse ${directive}: ${line}`);
+ } else if (directive === "#define") {
+ const args = split_ws(args_str, 1);
+ if (args.length === 2) asm_state.defines.set(args[0], parse_arg(args[1], arch, asm_state));
+ else asm_state.defines.set(args[0], new AsmLiteral(1));
+ } else if (directive === ".syntax") {
+ if (args_str.trim() === "unified") asm_state.is_unified = true;
+ else if (args_str.trim() === "divided") asm_state.is_unified = false;
+ } else if (directive === ".thumb" || directive === ".thumb_func") asm_state.is_thumb = true;
+ else if (directive === ".arm") asm_state.is_thumb = false;
+ else if (directive === ".code") {
+ if (args_str.trim() === "16") asm_state.is_thumb = true;
+ else if (args_str.trim() === "32") asm_state.is_thumb = false;
+ } else if ([".rodata", ".data", ".bss", ".text"].includes(curr_section)) {
+ if (Object.prototype.hasOwnProperty.call(data_directives, directive)) {
+ const size = data_directives[directive];
+ const args = split_arg_list(args_str);
+ for (const w of args) emit_word(w, size);
+ } else if (directive === ".rel") {
+ const args = split_arg_list(args_str);
+ pyassert(args.length === 2);
+ emit_word(args[1], 4);
+ } else if (directive === ".obj") {
+ const args = split_quotable_arg_list(args_str);
+ pyassert(args.length === 2);
+ const kind = args[1] === "local" ? LabelKind.LOCAL : LabelKind.GLOBAL;
+ process_label(args[0], { kind });
+ } else if (directive === ".float") {
+ const args = split_arg_list(args_str);
+ for (const w of args) {
+ const fval = try_parse(() => py_float(w));
+ emit_bytes(pack("f", fval));
+ }
+ } else if (directive === ".double") {
+ const args = split_arg_list(args_str);
+ for (const w of args) {
+ const fval = try_parse(() => py_float(w));
+ emit_bytes(pack("d", fval));
+ }
+ } else if ([".asci", ".asciz", ".ascii", ".asciiz", ".string"].includes(directive)) {
+ const z = directive.endsWith("z") || directive === ".string";
+ emit_bytes(parse_ascii_directive(line, z), { is_string: true });
+ } else if ([".space", ".skip", ".align", ".balign", ".p2align"].includes(directive)) {
+ const args = split_arg_list(args_str);
+ let fill;
+ if (args.length === 2) fill = band(parse_int(args[1]), 0xff);
+ else if (args.length === 1) fill = 0;
+ else throw new DecompFailure(`Could not parse asm_data ${directive} in ${curr_section}: ${line}`);
+ let size = parse_int(args[0]);
+ if (directive === ".balign") size = pymod(-section_sizes.get(curr_section), size);
+ else if (directive === ".align" || directive === ".p2align") size = pymod(-section_sizes.get(curr_section), 2 ** size);
+ emit_bytes(new Uint8Array(Math.max(size, 0)).fill(fill));
+ } else if (directive === ".incbin") {
+ const args = split_quotable_arg_list(args_str);
+ const data = parse_incbin(args, options, warnings);
+ if (data !== null) emit_bytes(data);
+ }
+ }
+ }
+ } else if (ifdef_level === 0) {
+ if (["jlabel", "alabel", "ehlabel"].includes(directive)) {
+ const sp = line.indexOf(" ");
+ const args_str = sp < 0 ? "" : line.slice(sp + 1);
+ const args = split_quotable_arg_list(args_str);
+ if (args.length) process_label(args[0], { kind: LabelKind.JUMP_TARGET });
+ } else if (
+ ["glabel", "dlabel", "arm_func_start", "thumb_func_start", "non_word_aligned_thumb_func_start", "ARM_FUNC_START", "THUMB_FUNC_START", "NON_WORD_ALIGNED_THUMB_FUNC_START"].includes(directive)
+ ) {
+ if (directive.toLowerCase().includes("thumb")) asm_state.is_thumb = true;
+ else if (directive.toLowerCase().includes("arm")) asm_state.is_thumb = false;
+ const sp = line.indexOf(" ");
+ const args_str = sp < 0 ? "" : line.slice(sp + 1);
+ const args = split_quotable_arg_list(args_str);
+ if (args.length) process_label(args[0], { kind: LabelKind.GLOBAL });
+ } else if (["arm_func_end", "thumb_func_end", "ARM_FUNC_END", "THUMB_FUNC_END", "endlabel", "enddlabel", "nonmatching"].includes(directive)) {
+ // pass
+ } else if (curr_section === ".text") {
+ const meta = new InstructionMeta({ emit_goto, filename, lineno, synthetic: false });
+ const ins = parse_instruction(line, meta, arch, asm_state);
+ asm_file.new_instruction(ins);
+ }
+ }
+ }
+
+ if (warnings.length && options.coding_style.comment_style !== CodingStyle.CommentStyle.NONE) {
+ print("/*");
+ print(warnings.join("\n"));
+ print("*/");
+ }
+ return asm_file;
+}
+
+export { pystr };
diff --git a/packages/romdev-m2c/src/asm_instruction.js b/packages/romdev-m2c/src/asm_instruction.js
new file mode 100644
index 00000000..eeae94fc
--- /dev/null
+++ b/packages/romdev-m2c/src/asm_instruction.js
@@ -0,0 +1,610 @@
+// Port of m2c/asm_instruction.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+// Functions and classes useful for parsing an arbitrary assembly instruction.
+import { DecompFailure, assert_never } from "./error.js";
+import { IndexError, band, bor, bxor, hex, int_, intern, isspace, pyassert, shl, shr, compare, repr } from "./py.js";
+import { PyEnum } from "./options.js";
+
+export const ARM_BARREL_SHIFTER_OPS = ["lsl", "lsr", "asr", "ror", "rrx"];
+export const OP_PRECEDENCE = { "*": 0, "+": 1, "-": 1, "<<": 2, ">>": 2, "&": 3, "^": 4, "|": 5 };
+export const MAX_PRECEDENCE = 6;
+
+export class Register {
+ constructor(register_name) {
+ this.register_name = register_name;
+ return intern(this, [register_name]);
+ }
+ is_float() {
+ const name = this.register_name;
+ return Boolean(name) && name[0] === "f" && name !== "fp";
+ }
+ arm_regtype_index() {
+ const index = { sp: 13, lr: 14, pc: 15 }[this.register_name];
+ if (index !== undefined) return ["r", index];
+ pyassert("rsdq".includes(this.register_name[0]), this.register_name);
+ return [this.register_name[0], int_(this.register_name.slice(1))];
+ }
+ static fictive(name, suffix = "") {
+ return new Register(`${name}_fictive_${suffix}`);
+ }
+ toString() {
+ return `$${this.register_name}`;
+ }
+ __repr__() {
+ return `Register(register_name=${repr(this.register_name)})`;
+ }
+}
+
+export class RegisterList {
+ constructor(regs) {
+ this.regs = regs;
+ return intern(this, [regs]);
+ }
+ toString() {
+ return "{" + this.regs.map((r) => String(r)).join(",") + "}";
+ }
+}
+
+export class AsmGlobalSymbol {
+ constructor(symbol_name) {
+ this.symbol_name = symbol_name;
+ if (new.target === AsmGlobalSymbol) return intern(this, [symbol_name]);
+ }
+ toString() {
+ return this.symbol_name;
+ }
+}
+
+export class AsmSectionGlobalSymbol extends AsmGlobalSymbol {
+ constructor(symbol_name, section_name, addend) {
+ super(symbol_name);
+ this.section_name = section_name;
+ this.addend = addend;
+ return intern(this, [symbol_name, section_name, addend]);
+ }
+}
+
+export function asm_section_global_symbol(section_name, addend) {
+ return new AsmSectionGlobalSymbol(`__${section_name}${hex(addend).slice(2).toUpperCase()}`, section_name, addend);
+}
+
+export class Macro {
+ constructor(macro_name, argument) {
+ this.macro_name = macro_name;
+ this.argument = argument;
+ return intern(this, [macro_name, argument]);
+ }
+ toString() {
+ if (this.macro_name === "eqsign") return `=${this.argument}`;
+ return `%${this.macro_name}(${this.argument})`;
+ }
+}
+
+export class AsmLiteral {
+ constructor(value) {
+ this.value = value;
+ return intern(this, [value]);
+ }
+ as_s16() {
+ return band(this.value + 0x8000, 0xffff) - 0x8000;
+ }
+ as_s8() {
+ return band(this.value + 0x80, 0xff) - 0x80;
+ }
+ toString() {
+ return hex(this.value);
+ }
+}
+
+export class Writeback extends PyEnum {}
+PyEnum.define(Writeback, { PRE: "pre", POST: "post" });
+
+export class AsmAddressMode {
+ constructor(base, addend, writeback) {
+ this.base = base;
+ this.addend = addend;
+ this.writeback = writeback;
+ return intern(this, [base, addend, writeback]);
+ }
+ addend_as_literal() {
+ pyassert(this.addend instanceof AsmLiteral);
+ return this.addend.value;
+ }
+ toString() {
+ if (this.writeback !== null && this.writeback !== undefined) {
+ // (upstream bug preserved: the addend is not interpolated)
+ const add_str = this.addend !== new AsmLiteral(0) ? ", {self.addend}" : "";
+ if (this.writeback === Writeback.PRE) return `[${this.base}${add_str}]!`;
+ return `[${this.base}]${add_str}`;
+ }
+ if (this.addend === new AsmLiteral(0)) return `(${this.base})`;
+ return `${this.addend}(${this.base})`;
+ }
+}
+
+export class BinOp {
+ constructor(op, lhs, rhs) {
+ this.op = op;
+ this.lhs = lhs;
+ this.rhs = rhs;
+ return intern(this, [op, lhs, rhs]);
+ }
+ toString() {
+ return `${this.lhs} ${this.op} ${this.rhs}`;
+ }
+}
+
+export class JumpTarget {
+ constructor(target) {
+ this.target = target;
+ return intern(this, [target]);
+ }
+ toString() {
+ return this.target;
+ }
+}
+
+export class AsmInstruction {
+ constructor(mnemonic, args) {
+ this.mnemonic = mnemonic;
+ this.args = args;
+ return intern(this, [mnemonic, args]);
+ }
+ toString() {
+ if (!this.args.length) return this.mnemonic;
+ return `${this.mnemonic} ${this.args.map((a) => String(a)).join(", ")}`;
+ }
+}
+
+/** Arch-specific information needed to parse asm. */
+export class ArchAsmParsing {
+ normalize_instruction(instr, asm_state) {
+ throw new Error("abstract");
+ }
+}
+ArchAsmParsing.prototype.supports_at_addressing = false;
+ArchAsmParsing.prototype.has_delay_slots = false;
+
+/** A fake arch that can parse asm in a naive fashion. */
+export class NaiveParsingArch extends ArchAsmParsing {
+ constructor() {
+ super();
+ this.all_regs = [];
+ this.aliased_regs = {};
+ this.supports_dollar_regs = true;
+ this.supports_at_addressing = true;
+ }
+ normalize_instruction(instr, asm_state) {
+ return instr;
+ }
+}
+
+function aliased(arch, name) {
+ return Object.prototype.hasOwnProperty.call(arch.aliased_regs, name) ? arch.aliased_regs[name] : undefined;
+}
+
+/** Converts register names used in input assembly to the internal register representation. */
+export class RegFormatter {
+ constructor() {
+ this.used_names = new Map();
+ }
+ parse(reg_name, arch) {
+ return aliased(arch, reg_name) ?? new Register(reg_name);
+ }
+ parse_and_store(reg_name, arch) {
+ reg_name = reg_name.toLowerCase();
+ const internal_reg = aliased(arch, reg_name) ?? new Register(reg_name);
+ const existing_reg_name = this.used_names.get(internal_reg);
+ if (existing_reg_name === undefined) this.used_names.set(internal_reg, reg_name);
+ else if (existing_reg_name !== reg_name) {
+ throw new DecompFailure(`Source uses multiple names for ${internal_reg} (${existing_reg_name}, ${reg_name})`);
+ }
+ return internal_reg;
+ }
+ format(reg) {
+ return this.used_names.get(reg) ?? reg.register_name;
+ }
+}
+
+export class AsmState {
+ constructor({ defines = new Map(), reg_formatter = new RegFormatter(), is_thumb = false, is_unified = false, is_pattern = false } = {}) {
+ // null means "explicitly undefined"
+ this.defines = defines;
+ this.reg_formatter = reg_formatter;
+ this.is_thumb = is_thumb;
+ this.is_unified = is_unified;
+ this.is_pattern = is_pattern;
+ }
+}
+
+const ASCII_LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+const DIGITS = "0123456789";
+export const valid_word = ASCII_LETTERS + DIGITS + "_$.";
+
+const inStr = (c, s) => c !== undefined && s.includes(c);
+
+export function parse_word(elems, valid = valid_word) {
+ let ret = "";
+ while (elems.length && inStr(elems[0], valid)) ret += elems.shift();
+ return ret;
+}
+
+export function parse_quoted(elems, quote_char) {
+ let ret = "";
+ while (elems.length && elems[0] !== quote_char) {
+ if (elems[0] === "\\") {
+ elems.shift();
+ if (!elems.length) break;
+ }
+ ret += elems.shift();
+ }
+ return ret;
+}
+
+export function parse_number(number_str) {
+ if (number_str[0] === "0") pyassert(number_str.length === 1 || "xX".includes(number_str[1]));
+ return int_(number_str, 0);
+}
+
+export function constant_fold(arg, asm_state) {
+ if (arg instanceof AsmGlobalSymbol) {
+ const value = asm_state.defines.get(arg.symbol_name);
+ if (value !== undefined && value !== null) return constant_fold(value, asm_state);
+ }
+ if (!(arg instanceof BinOp)) return arg;
+ const lhs = constant_fold(arg.lhs, asm_state);
+ const rhs = constant_fold(arg.rhs, asm_state);
+ if (lhs instanceof AsmLiteral && rhs instanceof AsmLiteral) {
+ switch (arg.op) {
+ case "+": return new AsmLiteral(lhs.value + rhs.value);
+ case "-": return new AsmLiteral(lhs.value - rhs.value);
+ case "*": return new AsmLiteral(lhs.value * rhs.value);
+ case ">>": return new AsmLiteral(shr(lhs.value, rhs.value));
+ case "<<": return new AsmLiteral(shl(lhs.value, rhs.value));
+ case "&": return new AsmLiteral(band(lhs.value, rhs.value));
+ case "|": return new AsmLiteral(bor(lhs.value, rhs.value));
+ case "^": return new AsmLiteral(bxor(lhs.value, rhs.value));
+ }
+ }
+ return new BinOp(arg.op, lhs, rhs);
+}
+
+/** If `arg` is an AsmGlobalSymbol whose name matches a known or aliased register, convert it. */
+export function replace_bare_reg(arg, arch, asm_state) {
+ if (arg instanceof AsmGlobalSymbol) {
+ const reg_name = arg.symbol_name.toLowerCase();
+ if (arch.all_regs.includes(new Register(reg_name)) || aliased(arch, reg_name) !== undefined) {
+ return asm_state.reg_formatter.parse_and_store(reg_name, arch);
+ }
+ }
+ return arg;
+}
+
+export function get_jump_target(label) {
+ pyassert(label instanceof AsmGlobalSymbol, "invalid branch target");
+ return new JumpTarget(label.symbol_name);
+}
+
+// Main parser.
+export function parse_arg_elems(arg_elems, arch, asm_state, { top_level, do_constant_fold = true, do_replace_bare_reg = true, precedence_cap = MAX_PRECEDENCE }) {
+ let value = null;
+ const supports_dollar_regs = arch.supports_dollar_regs || asm_state.is_pattern;
+
+ const consume_ws = () => {
+ while (arg_elems.length && isspace(arg_elems[0])) arg_elems.shift();
+ };
+ const expect = (n) => {
+ pyassert(arg_elems.length, `Expected one of ${repr([...n])}, but reached end of string`);
+ const g = arg_elems.shift();
+ pyassert(n.includes(g), `Expected one of ${repr([...n])}, got ${g} (rest: ${repr(arg_elems)})`);
+ return g;
+ };
+ const parse_sh_register = () => {
+ const word = parse_word(arg_elems);
+ if (word.startsWith("$") && supports_dollar_regs) return asm_state.reg_formatter.parse_and_store(word.slice(1), arch);
+ const reg = replace_bare_reg(new AsmGlobalSymbol(word), arch, asm_state);
+ pyassert(reg instanceof Register);
+ return reg;
+ };
+
+ for (;;) {
+ consume_ws();
+ if (!arg_elems.length) break;
+ const tok = arg_elems[0];
+ if (tok === ",") {
+ break;
+ } else if (tok === "$" && supports_dollar_regs) {
+ // Register.
+ pyassert(value === null);
+ const word = parse_word(arg_elems);
+ const reg = word.slice(1);
+ if (reg.includes("$")) value = new AsmGlobalSymbol(word);
+ else value = asm_state.reg_formatter.parse_and_store(reg, arch);
+ } else if (tok === "#") {
+ // ARM immediate.
+ pyassert(value === null);
+ expect("#");
+ } else if (tok === "{") {
+ // ARM register list.
+ pyassert(value === null);
+ arg_elems.shift();
+ const li = [];
+ for (;;) {
+ consume_ws();
+ if (li.length) {
+ if (expect(",}") === "}") break;
+ consume_ws();
+ }
+ let word = parse_word(arg_elems);
+ const reg1 = asm_state.reg_formatter.parse_and_store(word, arch);
+ consume_ws();
+ if (arg_elems[0] !== "-") {
+ if (arg_elems.length === 0) throw new IndexError("list index out of range");
+ li.push(reg1);
+ continue;
+ }
+ arg_elems.shift();
+ consume_ws();
+ word = parse_word(arg_elems);
+ const reg2 = asm_state.reg_formatter.parse_and_store(word, arch);
+ const [tp1, ind1] = reg1.arm_regtype_index();
+ const [tp2, ind2] = reg2.arm_regtype_index();
+ pyassert(tp1 === tp2);
+ for (let i = ind1; i < ind2 + 1; i++) li.push(asm_state.reg_formatter.parse(`${tp1}${i}`, arch));
+ }
+ consume_ws();
+ if (arg_elems.length && arg_elems[0] === "^") expect("^");
+ if (li.length > 1) {
+ const keyed = li.map((r, i) => [r.arm_regtype_index(), i, r]);
+ keyed.sort((a, b) => compare(a[0], b[0]) || a[1] - b[1]);
+ li.splice(0, li.length, ...keyed.map((k) => k[2]));
+ }
+ value = new RegisterList(li);
+ } else if (tok === ".") {
+ // Either a jump target (i.e. a label), or a section reference.
+ pyassert(value === null);
+ arg_elems.shift();
+ const word = parse_word(arg_elems);
+ if (["data", "sdata", "rodata", "rdata", "bss", "sbss", "text"].includes(word)) value = asm_section_global_symbol(word, 0);
+ else value = new AsmGlobalSymbol("." + word);
+ } else if (tok === "%") {
+ // A MIPS reloc macro, e.g. %hi(...) or %lo(...).
+ pyassert(value === null);
+ arg_elems.shift();
+ const macro_name = parse_word(arg_elems);
+ pyassert(macro_name);
+ expect("(");
+ const m = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_replace_bare_reg: false });
+ expect(")");
+ value = new Macro(macro_name, m);
+ } else if (tok === ")" || tok === "]") {
+ break;
+ } else if (DIGITS.includes(tok)) {
+ // Try a number.
+ pyassert(value === null);
+ const word = parse_word(arg_elems, valid_word);
+ value = new AsmLiteral(parse_number(word));
+ } else if (tok === "-" && value === null) {
+ // Negated number, or ARM negated register.
+ expect("-");
+ consume_ws();
+ const word = parse_word(arg_elems, valid_word);
+ pyassert(word);
+ if (DIGITS.includes(word[0])) value = new AsmLiteral(-parse_number(word));
+ else {
+ const val = replace_bare_reg(new AsmGlobalSymbol(word), arch, asm_state);
+ value = new BinOp("-", new AsmLiteral(0), val);
+ }
+ } else if (tok === "(") {
+ if (value !== null && !top_level) break;
+ // Address mode or binary operation.
+ expect("(");
+ let rhs = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_constant_fold: false });
+ expect(")");
+ if (rhs instanceof BinOp) {
+ pyassert(value === null);
+ value = constant_fold(rhs, asm_state);
+ } else {
+ if (rhs === new AsmLiteral(0)) rhs = new Register("zero");
+ if (rhs instanceof AsmGlobalSymbol) {
+ pyassert(value === null);
+ value = constant_fold(rhs, asm_state);
+ } else {
+ pyassert(top_level);
+ pyassert(rhs instanceof Register);
+ value = constant_fold(value || new AsmLiteral(0), asm_state);
+ value = new AsmAddressMode(rhs, value, null);
+ }
+ }
+ } else if (tok === "[") {
+ // ARM address mode
+ pyassert(value === null);
+ expect("[");
+ const val = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false });
+ pyassert(val instanceof Register);
+ let addend = null;
+ if (expect(",]") === ",") {
+ addend = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false });
+ if (expect(",]") === ",") {
+ consume_ws();
+ const op = parse_word(arg_elems).toLowerCase();
+ pyassert(ARM_BARREL_SHIFTER_OPS.includes(op));
+ let shift;
+ if (op === "rrx") shift = new AsmLiteral(1);
+ else shift = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false });
+ addend = new BinOp(op, addend, constant_fold(shift, asm_state));
+ expect("]");
+ }
+ }
+ consume_ws();
+ let writeback = null;
+ if (arg_elems.length && arg_elems[0] === "!") {
+ expect("!");
+ writeback = Writeback.PRE;
+ } else if (arg_elems.length && arg_elems[0] === ",") {
+ expect(",");
+ pyassert(addend === null);
+ addend = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false });
+ writeback = Writeback.POST;
+ }
+ if (addend === null) addend = new AsmLiteral(0);
+ value = new AsmAddressMode(val, addend, writeback);
+ } else if (tok === "!") {
+ // ARM writeback indicator
+ expect("!");
+ if (value !== null) value = replace_bare_reg(value, arch, asm_state);
+ pyassert(value instanceof Register);
+ value = new AsmAddressMode(value, new AsmLiteral(0), Writeback.PRE);
+ } else if (tok === '"') {
+ // Quoted global symbol.
+ expect('"');
+ pyassert(value === null);
+ const word = parse_quoted(arg_elems, '"');
+ value = new AsmGlobalSymbol(word);
+ expect('"');
+ } else if (valid_word.includes(tok)) {
+ // Global symbol.
+ pyassert(value === null);
+ const word = parse_word(arg_elems);
+ value = new AsmGlobalSymbol(word);
+
+ const op = word.toLowerCase();
+ if (top_level && ARM_BARREL_SHIFTER_OPS.includes(op)) {
+ consume_ws();
+ if (arg_elems.length && !",)@".includes(arg_elems[0])) {
+ const shift = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false });
+ value = new BinOp(op, new AsmLiteral(0), shift);
+ pyassert(!arg_elems.length);
+ } else if (op === "rrx") {
+ value = new BinOp(op, new AsmLiteral(0), new AsmLiteral(1));
+ pyassert(!arg_elems.length);
+ }
+ }
+ } else if ("<>+-*&|^".includes(tok)) {
+ // Binary operators
+ pyassert(value instanceof AsmLiteral || value instanceof AsmGlobalSymbol || value instanceof BinOp);
+ const op = "<>".includes(tok) ? tok + tok : tok;
+ const precedence = OP_PRECEDENCE[op];
+ if (precedence >= precedence_cap) break;
+ for (const c of op) expect(c);
+ if (op === "-" && arg_elems[0] === "_") {
+ const reloc_name = parse_word(arg_elems);
+ if (reloc_name !== "_SDA_BASE_" && reloc_name !== "_SDA2_BASE_") {
+ throw new DecompFailure(`Unexpected symbol ${reloc_name} in subtraction expression`);
+ }
+ value = new Macro("sda21", value);
+ } else {
+ const rhs = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_replace_bare_reg: false, precedence_cap: precedence });
+ if (op === "+" && rhs instanceof AsmLiteral && value instanceof AsmSectionGlobalSymbol) {
+ value = asm_section_global_symbol(value.section_name, value.addend + rhs.value);
+ } else {
+ value = new BinOp(op, value, rhs);
+ }
+ }
+ } else if (tok === "@") {
+ if (value === null && arch.supports_at_addressing) {
+ // SuperH indirect addressing: @Rn, @-Rn, @Rn+, and @(disp,Rn).
+ expect("@");
+ if (arg_elems.length && arg_elems[0] === "(") {
+ expect("(");
+ const addend = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false });
+ expect(",");
+ consume_ws();
+ const base = parse_sh_register();
+ expect(")");
+ value = new AsmAddressMode(base, addend, null);
+ continue;
+ }
+ let sh_writeback = null;
+ if (arg_elems.length && arg_elems[0] === "-") {
+ expect("-");
+ sh_writeback = Writeback.PRE;
+ }
+ const base = parse_sh_register();
+ if (arg_elems.length && arg_elems[0] === "+") {
+ pyassert(sh_writeback === null);
+ expect("+");
+ sh_writeback = Writeback.POST;
+ }
+ value = new AsmAddressMode(base, new AsmLiteral(0), sh_writeback);
+ } else {
+ // A relocation (e.g. (...)@ha or (...)@l).
+ if (!top_level) break;
+ arg_elems.shift();
+ const reloc_name = parse_word(arg_elems);
+ pyassert(["h", "ha", "l", "sda2", "sda21"].includes(reloc_name));
+ pyassert(value);
+ value = new Macro(reloc_name, value);
+ }
+ } else if (tok === "=") {
+ // ARM reference to symbol
+ pyassert(top_level);
+ pyassert(!value);
+ expect("=");
+ const ref = parse_arg_elems(arg_elems, arch, asm_state, { top_level: false, do_constant_fold: true });
+ value = new Macro("eqsign", ref);
+ } else {
+ pyassert(false, `Unknown token ${tok} in ${repr(arg_elems)}`);
+ }
+ }
+
+ pyassert(value !== null);
+ if (do_constant_fold) value = constant_fold(value, asm_state);
+ if (do_replace_bare_reg) value = replace_bare_reg(value, arch, asm_state);
+ return value;
+}
+
+export function parse_args(args, arch, asm_state) {
+ const arg_elems = [...args.trim()];
+ const output = [];
+ while (arg_elems.length) {
+ const ret = parse_arg_elems(arg_elems, arch, asm_state, { top_level: true });
+ if (ret instanceof BinOp && ARM_BARREL_SHIFTER_OPS.includes(ret.op)) {
+ pyassert(output.length);
+ output[output.length - 1] = new BinOp(ret.op, output[output.length - 1], ret.rhs);
+ continue;
+ }
+ output.push(ret);
+ if (arg_elems.length) {
+ const comma = arg_elems.shift();
+ pyassert(comma === ",");
+ }
+ }
+ return output;
+}
+
+export function parse_arg(arg, arch, asm_state) {
+ const chars = [...arg];
+ const value = parse_arg_elems(chars, arch, asm_state, { top_level: false, do_replace_bare_reg: false });
+ if (chars.length) throw new Error(`Failed to parse value: ${arg}`);
+ return value;
+}
+
+export function parse_asm_instruction(line, arch, asm_state) {
+ line = line.trim();
+ const i = line.indexOf(" ");
+ const mnemonic = i < 0 ? line : line.slice(0, i);
+ const args_str = i < 0 ? "" : line.slice(i + 1);
+ const args = parse_args(args_str, arch, asm_state);
+ const instr = new AsmInstruction(mnemonic.toLowerCase(), args);
+ return arch.normalize_instruction(instr, asm_state);
+}
+
+export function* traverse_arg(arg) {
+ yield arg;
+ if (arg instanceof Register || arg instanceof AsmLiteral || arg instanceof AsmGlobalSymbol) {
+ // pass
+ } else if (arg instanceof RegisterList) {
+ for (const reg of arg.regs) yield reg;
+ } else if (arg instanceof AsmAddressMode) {
+ yield arg.base;
+ yield* traverse_arg(arg.addend);
+ } else if (arg instanceof Macro) {
+ yield* traverse_arg(arg.argument);
+ } else if (arg instanceof BinOp) {
+ yield* traverse_arg(arg.lhs);
+ yield* traverse_arg(arg.rhs);
+ } else {
+ assert_never(arg);
+ }
+}
diff --git a/packages/romdev-m2c/src/asm_pattern.js b/packages/romdev-m2c/src/asm_pattern.js
new file mode 100644
index 00000000..f29a9e36
--- /dev/null
+++ b/packages/romdev-m2c/src/asm_pattern.js
@@ -0,0 +1,275 @@
+// Port of m2c/asm_pattern.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { Label } from "./asm_file.js";
+import {
+ ARM_BARREL_SHIFTER_OPS,
+ AsmAddressMode,
+ AsmGlobalSymbol,
+ AsmInstruction,
+ AsmLiteral,
+ AsmState,
+ BinOp,
+ Macro,
+ NaiveParsingArch,
+ Register,
+ RegisterList,
+ parse_asm_instruction,
+} from "./asm_instruction.js";
+import { Instruction, InstructionMeta } from "./instruction.js";
+import { DefaultMap, pyassert, rstrip, shl } from "./py.js";
+import { print } from "./io.js";
+
+/** Python str.isupper(). */
+export function isupper(s) {
+ return s !== s.toLowerCase() && s === s.toUpperCase();
+}
+
+export function make_pattern(...parts) {
+ const ret = [];
+ for (let part of parts) {
+ const optional = part.endsWith("?");
+ part = rstrip(part, "?");
+ if (part === "*") ret.push([null, optional]);
+ else if (part.endsWith(":")) ret.push([Label.new(part.slice(0, -1)), optional]);
+ else {
+ const ins = parse_asm_instruction(part, new NaiveParsingArch(), new AsmState());
+ ret.push([ins, optional]);
+ }
+ }
+ return ret;
+}
+
+export class Replacement {
+ constructor(new_body, num_consumed, clobbers = null) {
+ this.new_body = new_body;
+ this.num_consumed = num_consumed;
+ this.clobbers = clobbers;
+ }
+}
+
+export class AsmMatch {
+ constructor(body, wildcard_items, regs, literals, labels, asm_data) {
+ this.body = body;
+ this.wildcard_items = wildcard_items;
+ this.regs = regs; // Map
+ this.literals = literals; // Map
+ this.labels = labels; // Map
+ this.asm_data = asm_data;
+ }
+}
+
+export class AsmPattern {
+ match(matcher) {
+ throw new Error("abstract");
+ }
+}
+
+export class SimpleAsmPattern extends AsmPattern {
+ // subclasses define `pattern` and replace(m)
+ match(matcher) {
+ const m = matcher.try_match(this.pattern);
+ if (!m) return null;
+ return this.replace(m);
+ }
+}
+
+export class TryMatchState {
+ constructor() {
+ this.symbolic_registers = new Map();
+ this.symbolic_labels_def = new Map();
+ this.symbolic_labels_uses = new DefaultMap(() => new Set());
+ this.symbolic_literals = new Map();
+ this.wildcard_items = [];
+ }
+ match_var(var_map, key, value) {
+ if (var_map.has(key)) {
+ if (var_map.get(key) !== value) return false;
+ } else var_map.set(key, value);
+ return true;
+ }
+ match_reg(actual, exp) {
+ if (exp.register_name.length <= 1) return this.match_var(this.symbolic_registers, exp.register_name, actual);
+ return exp.register_name === actual.register_name;
+ }
+ match_label_def(key, defn) {
+ pyassert(!this.symbolic_labels_def.has(key));
+ this.symbolic_labels_def.set(key, defn);
+ const uses = this.symbolic_labels_uses.get(key);
+ for (const u of uses) if (!defn.names.includes(u)) return false;
+ return true;
+ }
+ match_label_use(key, use) {
+ const defn = this.symbolic_labels_def.get(key) ?? null;
+ if (defn !== null && !defn.names.includes(use)) return false;
+ this.symbolic_labels_uses.get(key).add(use);
+ return true;
+ }
+ eval_math(e) {
+ if (e instanceof AsmLiteral) return e.value;
+ if (e instanceof BinOp) {
+ if (e.op === "+") return this.eval_math(e.lhs) + this.eval_math(e.rhs);
+ if (e.op === "-") return this.eval_math(e.lhs) - this.eval_math(e.rhs);
+ if (e.op === "<<") return shl(this.eval_math(e.lhs), this.eval_math(e.rhs));
+ pyassert(false, `bad binop in math pattern: ${e}`);
+ } else if (e instanceof AsmGlobalSymbol) {
+ pyassert(this.symbolic_literals.has(e.symbol_name), `undefined variable in math pattern: ${e.symbol_name}`);
+ return this.symbolic_literals.get(e.symbol_name);
+ } else {
+ pyassert(false, `bad pattern part in math pattern: ${e}`);
+ }
+ }
+ match_arg(a, e) {
+ if (e instanceof AsmLiteral) return a instanceof AsmLiteral && a.value === e.value;
+ if (e instanceof Register) return a instanceof Register && this.match_reg(a, e);
+ if (e instanceof AsmGlobalSymbol) {
+ if (e.symbol_name.startsWith(".")) return a instanceof AsmGlobalSymbol && this.match_label_use(e.symbol_name, a.symbol_name);
+ else if (isupper(e.symbol_name)) return a instanceof AsmLiteral && this.match_var(this.symbolic_literals, e.symbol_name, a.value);
+ else if (e.symbol_name === "_") return true;
+ else return a instanceof AsmGlobalSymbol && a.symbol_name === e.symbol_name;
+ }
+ if (e instanceof AsmAddressMode) {
+ return a instanceof AsmAddressMode && this.match_reg(a.base, e.base) && this.match_arg(a.addend, e.addend) && a.writeback === e.writeback;
+ }
+ if (e instanceof BinOp) {
+ if (ARM_BARREL_SHIFTER_OPS.includes(e.op)) {
+ return a instanceof BinOp && a.op === e.op && this.match_arg(a.lhs, e.lhs) && this.match_arg(a.rhs, e.rhs);
+ }
+ return a instanceof AsmLiteral && a.value === this.eval_math(e);
+ }
+ if (e instanceof Macro) return a instanceof Macro && a.macro_name === e.macro_name && this.match_arg(a.argument, e.argument);
+ if (e instanceof RegisterList) {
+ return a instanceof RegisterList && a.regs.length === e.regs.length && a.regs.every((ar, i) => this.match_reg(ar, e.regs[i]));
+ }
+ pyassert(false, `bad pattern part: ${e}`);
+ }
+ match_one(actual, exp) {
+ if (exp === null) {
+ this.wildcard_items.push(actual);
+ return true;
+ }
+ if (exp instanceof Label) {
+ pyassert(exp.names.length === 1);
+ return actual instanceof Label && this.match_label_def(exp.names[0], actual);
+ }
+ if (!(actual instanceof Instruction)) return false;
+ const ins = actual;
+ if (ins.mnemonic !== exp.mnemonic) return false;
+ if (exp.args.length) {
+ if (ins.args.length !== exp.args.length) return false;
+ for (let i = 0; i < ins.args.length; i++) if (!this.match_arg(ins.args[i], exp.args[i])) return false;
+ }
+ return true;
+ }
+ match_meta(ins) {
+ if (ins.mnemonic === ".eq") {
+ const res = this.eval_math(ins.args[1]);
+ return this.match_arg(new AsmLiteral(res), ins.args[0]);
+ } else if (ins.mnemonic === ".set") {
+ const sym = ins.args[0];
+ pyassert(sym instanceof AsmGlobalSymbol);
+ pyassert(isupper(sym.symbol_name));
+ this.symbolic_literals.set(sym.symbol_name, this.eval_math(ins.args[1]));
+ return true;
+ } else if (ins.mnemonic === ".forget") {
+ const arg = ins.args[0];
+ if (arg instanceof Register) this.symbolic_registers.delete(arg.register_name);
+ else pyassert(false, ".forget arg of unsupported type");
+ return true;
+ } else {
+ pyassert(false, ins.mnemonic);
+ }
+ }
+}
+
+export class AsmMatcher {
+ constructor(arch, asm_data, input, labels) {
+ this.arch = arch;
+ this.asm_data = asm_data;
+ this.input = input;
+ this.labels = labels;
+ this.output = [];
+ this.index = 0;
+ }
+ try_match(pattern) {
+ const state = new TryMatchState();
+ const start_index = this.index;
+ let index = this.index;
+ for (const [pat, optional] of pattern) {
+ if (pat instanceof AsmInstruction && pat.mnemonic[0] === ".") {
+ if (!state.match_meta(pat) && !optional) return null;
+ } else if (index < this.input.length && state.match_one(this.input[index], pat)) {
+ index += 1;
+ } else if (!optional) return null;
+ }
+ return new AsmMatch(this.input.slice(start_index, index), state.wildcard_items, state.symbolic_registers, state.symbolic_literals, state.symbolic_labels_def, this.asm_data);
+ }
+ derived_meta() {
+ for (const part of this.input.slice(this.index)) if (part instanceof Instruction) return part.meta.derived();
+ return InstructionMeta.missing();
+ }
+ is_local_label(name) {
+ return this.labels.has(name);
+ }
+ apply(repl, arch) {
+ const repl_writes = [];
+ let final_instr = null;
+ for (let part of repl.new_body) {
+ if (part instanceof AsmInstruction) part = arch.parse(part.mnemonic, part.args, this.derived_meta());
+ if (part instanceof Instruction) {
+ repl_writes.push(...part.outputs);
+ repl_writes.push(...part.clobbers);
+ final_instr = part;
+ }
+ this.output.push(part);
+ }
+ if (repl.clobbers === null) {
+ for (const part of this.input.slice(this.index, this.index + repl.num_consumed)) {
+ if (part instanceof Instruction) {
+ for (const arg of [...part.outputs, ...part.clobbers]) {
+ pyassert(final_instr !== null);
+ if (!repl_writes.includes(arg) && !final_instr.clobbers.includes(arg)) final_instr.clobbers.push(arg);
+ }
+ }
+ }
+ } else if (repl.clobbers.length) {
+ pyassert(final_instr !== null);
+ final_instr.clobbers.push(...repl.clobbers);
+ }
+ this.index += repl.num_consumed;
+ }
+}
+
+function label_names(body) {
+ const s = new Set();
+ for (const item of body) if (item instanceof Label) for (const name of item.names) s.add(name);
+ return s;
+}
+
+/** Detect and simplify asm standard patterns emitted by known compilers. */
+export function simplify_patterns(body, patterns, asm_data, arch, { debug_patterns }) {
+ let labels = label_names(body);
+ for (const pattern of patterns) {
+ const matcher = new AsmMatcher(arch, asm_data, body, labels);
+ let matched_any = false;
+ while (matcher.index < matcher.input.length) {
+ const m = pattern.match(matcher);
+ if (m) {
+ matcher.apply(m, arch);
+ matched_any = true;
+ } else {
+ matcher.output.push(matcher.input[matcher.index]);
+ matcher.index += 1;
+ }
+ }
+ if (!matched_any) continue;
+ body = matcher.output;
+ labels = label_names(body);
+ if (debug_patterns) {
+ print(`Rewrote asm using ${pattern.constructor.name}:`);
+ print();
+ for (const part of body) print(String(part));
+ print();
+ }
+ }
+ return body;
+}
diff --git a/packages/romdev-m2c/src/c_types.js b/packages/romdev-m2c/src/c_types.js
new file mode 100644
index 00000000..141b50a0
--- /dev/null
+++ b/packages/romdev-m2c/src/c_types.js
@@ -0,0 +1,759 @@
+// Port of m2c/c_types.py
+// This file handles variable types, function signatures and struct layouts
+// based on a C AST. Based on the pycparser library.
+import fs from "node:fs";
+import { c_ast as ca, CGenerator, CParser, ParseError } from "romdev-pycparser";
+import { DecompFailure } from "./error.js";
+import { DefaultMap, ValueError, band, bnot, bor, bxor, count, deepcopy, floordiv, hex, int_, pyassert, pymod, rstrip, shl, shr } from "./py.js";
+import { print, popts } from "./io.js";
+
+const { ArrayDecl, FuncDecl, IdentifierType, PtrDecl, TypeDecl } = ca;
+
+/** Arch-specific information needed to extract types from C. */
+export class ArchC {}
+ArchC.prototype.base_struct_align = 1;
+
+export class StructField {
+ constructor(type, size, name) {
+ this.type = type;
+ this.size = size;
+ this.name = name;
+ }
+}
+
+export class BitField {
+ constructor(width, name) {
+ this.width = width;
+ this.name = name;
+ }
+}
+
+export class Struct {
+ constructor({ type, fields, bitfields, has_bitfields, size, align }) {
+ this.type = type;
+ this.fields = fields; // Map
+ this.bitfields = bitfields; // Map
+ this.has_bitfields = has_bitfields;
+ this.size = size;
+ this.align = align;
+ }
+}
+
+export class Array_ {
+ constructor(subtype, subctype, subsize, dim) {
+ this.subtype = subtype;
+ this.subctype = subctype;
+ this.subsize = subsize;
+ this.dim = dim;
+ }
+}
+
+export class Param {
+ constructor(type, name) {
+ this.type = type;
+ this.name = name;
+ }
+}
+
+export class Function {
+ constructor({ type, ret_type, params, is_variadic }) {
+ this.type = type;
+ this.ret_type = ret_type;
+ this.params = params;
+ this.is_variadic = is_variadic;
+ }
+}
+
+export class Enum {
+ constructor(tag, names) {
+ this.tag = tag;
+ this.names = names; // Map
+ }
+}
+
+export class TypeMap {
+ static VERSION = 10;
+ constructor({ source_hash, base_struct_align, cparser_scope = null }) {
+ this.source_hash = source_hash;
+ this.base_struct_align = base_struct_align;
+ this.cparser_scope = cparser_scope;
+ this.typedefs = new Map(); // name -> [CType, align]
+ this.var_types = new Map();
+ this.vars_with_initializers = new Set();
+ this.functions = new Map();
+ this.structs = new Map(); // str | ca.Struct/Union -> Struct
+ this.struct_typedefs = new Map();
+ this.pragma_packs = new Map();
+ this.enums = new Map();
+ this.enum_values = new Map();
+ }
+}
+
+export function to_c(node) {
+ return new CGenerator().visit(node);
+}
+
+export function basic_type(names) {
+ const idtype = new IdentifierType(names);
+ return new TypeDecl(null, [], [], idtype);
+}
+
+export function pointer(type) {
+ return new PtrDecl([], type);
+}
+
+export function get_align_override(decl, typemap) {
+ const aligns = [];
+ for (const attr of decl.gcc_attributes) {
+ if (attr.name === "packed") aligns.push(1);
+ if (attr.name === "aligned") {
+ let align_to;
+ if (!attr.args || !attr.args.length) align_to = 0x10;
+ else align_to = parse_constant_int(attr.args[0], typemap);
+ aligns.push(align_to);
+ }
+ }
+ if (decl instanceof ca.Decl) {
+ for (const alignas of decl.align) {
+ let align_to;
+ if (alignas.alignment instanceof ca.Typename) {
+ const [, tp_align] = parse_struct_member(alignas.alignment.type, "referenced in _Alignas", typemap, { allow_unsized: false });
+ align_to = get_align_override(alignas.alignment, typemap) || tp_align;
+ } else align_to = parse_constant_int(alignas.alignment, typemap);
+ aligns.push(align_to);
+ }
+ }
+ let align = 0;
+ for (const align_to of aligns) {
+ if (align_to <= 0 || band(align_to, align_to - 1) !== 0) throw new DecompFailure(`Alignment ${align_to} is not a power of two`);
+ align = Math.max(align, align_to);
+ }
+ return align;
+}
+
+export function has_128bit_attr(attrs) {
+ return attrs.some((attr) => attr.name === "mode" && attr.args && attr.args.length && attr.args[0] instanceof ca.ID && attr.args[0].name === "TI");
+}
+
+export function resolve_typedefs(type, typemap) {
+ if (type instanceof TypeDecl) {
+ if (type.type instanceof IdentifierType && type.type.names.length === 1 && typemap.typedefs.has(type.type.names[0])) {
+ const [t, align_override] = typemap.typedefs.get(type.type.names[0]);
+ const [t2, base_align_override] = resolve_typedefs(t, typemap);
+ return [t2, align_override || base_align_override];
+ }
+ if (type.type instanceof ca.Typeof) {
+ const typeof_ = type.type;
+ if (typeof_.expr instanceof ca.Typename) {
+ return [typeof_.expr.type, get_align_override(typeof_.expr, typemap)];
+ } else {
+ const expr = typeof_.expr;
+ if (expr instanceof ca.UnaryOp && expr.op === "sizeof") {
+ const size_t = new ca.IdentifierType(["unsigned", "int"]);
+ return [new TypeDecl(null, [], [], size_t), 0];
+ }
+ throw new DecompFailure("typeof() is not supported");
+ }
+ }
+ }
+ return [type, 0];
+}
+
+export function type_of_var_decl(decl) {
+ pyassert(!(decl.type instanceof ca.Struct || decl.type instanceof ca.Union || decl.type instanceof ca.Enum), "decls that declare variables have CType types");
+ return decl.type;
+}
+
+/** Get the CType of a global Decl, stripping names of function parameters. */
+export function type_from_global_decl(decl) {
+ const tp = type_of_var_decl(decl);
+ if (!(tp instanceof ca.FuncDecl) || !tp.args) return tp;
+ const anonymize_param = (param) => {
+ param = deepcopy(param);
+ param.name = null;
+ set_decl_name(param);
+ return new ca.Typename(null, param.quals, null, [], type_of_var_decl(param));
+ };
+ const new_params = tp.args.params.map((param) => (param instanceof ca.Decl ? anonymize_param(param) : param));
+ return new ca.FuncDecl(new ca.ParamList(new_params), tp.type);
+}
+
+function namesEq(names, arr) {
+ return names.length === arr.length && names.every((n, i) => n === arr[i]);
+}
+
+export function is_void(type) {
+ return type instanceof ca.TypeDecl && type.type instanceof ca.IdentifierType && namesEq(type.type.names, ["void"]);
+}
+
+export function primitive_size(type) {
+ if (type instanceof ca.Enum) return 4;
+ const names = type.names;
+ if (names.includes("double")) return 8;
+ if (names.includes("float")) return 4;
+ if (names.includes("__int128")) return 16;
+ if (names.includes("short")) return 2;
+ if (names.includes("char")) return 1;
+ if (names.includes("void")) return 0;
+ if (names.filter((n) => n === "long").length === 2) return 8;
+ return 4;
+}
+
+/** Returns [start, stop] (Python range) or null. */
+export function primitive_range(type) {
+ let bits = 8 * primitive_size(type);
+ let signed = true;
+ if (!(type instanceof ca.Enum)) {
+ const names = type.names;
+ if (names.includes("double") || names.includes("float") || names.includes("void")) return null;
+ if (names.includes("unsigned")) signed = false;
+ }
+ if (signed) {
+ bits -= 1;
+ return [-(2 ** bits), 2 ** bits];
+ }
+ return [0, 2 ** bits];
+}
+
+/** Return true if `type` represents an unknown type, or undetermined struct padding. */
+export function is_unk_type(type, typemap) {
+ if (type instanceof ArrayDecl && type.type instanceof TypeDecl && type.type.type instanceof IdentifierType && type.type.declname !== null && type.type.declname !== undefined && namesEq(type.type.type.names, ["char"])) {
+ const declname = type.type.declname;
+ if (declname.startsWith("unk_") || declname.startsWith("pad")) return true;
+ }
+ for (;;) {
+ if (type instanceof TypeDecl && type.type instanceof IdentifierType && type.type.names.length === 1 && typemap.typedefs.has(type.type.names[0])) {
+ const type_name = type.type.names[0];
+ if (type_name.startsWith("UNK_") || type_name.startsWith("M2C_UNK")) return true;
+ type = typemap.typedefs.get(type_name)[0];
+ } else if (type instanceof PtrDecl || type instanceof ArrayDecl) type = type.type;
+ else return false;
+ }
+}
+
+export function parse_function(fn) {
+ if (!(fn instanceof FuncDecl)) return null;
+ const params = [];
+ let is_variadic = false;
+ let has_void = false;
+ if (fn.args) {
+ for (const arg of fn.args.params) {
+ if (arg instanceof ca.EllipsisParam) is_variadic = true;
+ else if (arg instanceof ca.Decl) params.push(new Param(type_of_var_decl(arg), arg.name));
+ else if (arg instanceof ca.ID) throw new DecompFailure("K&R-style function header is not supported: " + to_c(fn));
+ else {
+ pyassert(arg instanceof ca.Typename);
+ if (is_void(arg.type)) has_void = true;
+ else params.push(new Param(arg.type, null));
+ }
+ }
+ }
+ let maybe_params = params;
+ if (!params.length && !has_void && !is_variadic) maybe_params = null;
+ const ret_type = is_void(fn.type) ? null : fn.type;
+ return new Function({ type: fn, ret_type, params: maybe_params, is_variadic });
+}
+
+export function divmod_towards_zero(lhs, rhs, op) {
+ if (rhs < 0) {
+ rhs = -rhs;
+ lhs = -lhs;
+ }
+ if (lhs < 0) return -divmod_towards_zero(-lhs, rhs, op);
+ if (op === "/") return floordiv(lhs, rhs);
+ return pymod(lhs, rhs);
+}
+
+export function parse_constant_int(expr, typemap) {
+ if (expr instanceof ca.Constant) {
+ try {
+ return int_(rstrip(expr.value, "lLuU"), 0);
+ } catch (e) {
+ if (e instanceof ValueError) throw new DecompFailure(`Failed to parse ${to_c(expr)} as an int literal`);
+ throw e;
+ }
+ }
+ if (expr instanceof ca.ID) {
+ if (typemap.enum_values.has(expr.name)) return typemap.enum_values.get(expr.name);
+ }
+ if (expr instanceof ca.BinaryOp) {
+ const op = expr.op;
+ const lhs = parse_constant_int(expr.left, typemap);
+ if (op === "&&" && lhs === 0) return 0;
+ if (op === "||" && lhs !== 0) return 1;
+ const rhs = parse_constant_int(expr.right, typemap);
+ if (op === "+") return lhs + rhs;
+ if (op === "-") return lhs - rhs;
+ if (op === "*") return lhs * rhs;
+ if (op === "<<") return shl(lhs, rhs);
+ if (op === ">>") return shr(lhs, rhs);
+ if (op === "&") return band(lhs, rhs);
+ if (op === "|") return bor(lhs, rhs);
+ if (op === "^") return bxor(lhs, rhs);
+ if (op === ">=") return lhs >= rhs ? 1 : 0;
+ if (op === "<=") return lhs <= rhs ? 1 : 0;
+ if (op === ">") return lhs > rhs ? 1 : 0;
+ if (op === "<") return lhs < rhs ? 1 : 0;
+ if (op === "==") return lhs === rhs ? 1 : 0;
+ if (op === "!=") return lhs !== rhs ? 1 : 0;
+ if (op === "&&" || op === "||") return rhs !== 0 ? 1 : 0;
+ if (op === "/" || op === "%") {
+ if (rhs === 0) throw new DecompFailure(`Division by zero when evaluating expression ${to_c(expr)}`);
+ return divmod_towards_zero(lhs, rhs, op);
+ }
+ }
+ if (expr instanceof ca.TernaryOp) {
+ const cond = parse_constant_int(expr.cond, typemap) !== 0;
+ return parse_constant_int(cond ? expr.iftrue : expr.iffalse, typemap);
+ }
+ if (expr instanceof ca.ExprList) {
+ const last_expr = expr.exprs[expr.exprs.length - 1];
+ if (!(last_expr instanceof ca.Typename)) return parse_constant_int(last_expr, typemap);
+ }
+ if (expr instanceof ca.UnaryOp && !(expr.expr instanceof ca.Typename)) {
+ const sub = parse_constant_int(expr.expr, typemap);
+ if (expr.op === "+") return sub;
+ if (expr.op === "-") return -sub;
+ if (expr.op === "~") return bnot(sub);
+ if (expr.op === "!") return sub === 0 ? 1 : 1;
+ }
+ if (expr instanceof ca.UnaryOp && expr.expr instanceof ca.Typename) {
+ const [size, align] = parse_struct_member(expr.expr.type, `referenced in ${expr.op}`, typemap, { allow_unsized: false });
+ if (expr.op === "sizeof") return size;
+ if (expr.op === "_Alignof") return get_align_override(expr.expr, typemap) || align;
+ }
+ if (expr instanceof ca.Cast) {
+ const value = parse_constant_int(expr.expr, typemap);
+ const [type] = resolve_typedefs(expr.to_type.type, typemap);
+ if (type instanceof ca.TypeDecl && (type.type instanceof ca.Enum || type.type instanceof ca.IdentifierType)) {
+ const rng = primitive_range(type.type);
+ if (rng !== null) {
+ const [start, stop] = rng;
+ const width = stop - start;
+ if (Number.isSafeInteger(width) && Number.isSafeInteger(value - start)) return start + pymod(value - start, width);
+ return Number(BigInt(start) + (((BigInt(value) - BigInt(start)) % BigInt(width)) + BigInt(width)) % BigInt(width));
+ }
+ }
+ }
+ throw new DecompFailure(`Failed to evaluate expression ${to_c(expr)} at compile time; only simple arithmetic is supported for now`);
+}
+
+/** Parse an enum and compute the values of all its enumerators. */
+export function parse_enum(enum_, typemap) {
+ if (enum_.values === null || enum_.values === undefined) return;
+ const typemap_enum = new Enum(enum_.name, new Map());
+ typemap.enums.set(enum_, typemap_enum);
+ if (enum_.name !== null && enum_.name !== undefined && !typemap.enums.has(enum_.name)) typemap.enums.set(enum_.name, typemap_enum);
+ let next_value = 0;
+ for (const enumerator of enum_.values.enumerators) {
+ let value;
+ if (enumerator.value) value = parse_constant_int(enumerator.value, typemap);
+ else value = next_value;
+ next_value = value + 1;
+ typemap.enum_values.set(enumerator.name, value);
+ typemap_enum.names.set(value, enumerator.name);
+ }
+}
+
+export function get_struct(struct, typemap) {
+ if (struct.name) return typemap.structs.get(struct.name) ?? null;
+ return typemap.structs.get(struct) ?? null;
+}
+
+export class UndefinedStructError extends DecompFailure {
+ constructor(message) {
+ super(message);
+ this.name = "UndefinedStructError";
+ }
+}
+
+export function parse_struct(struct, typemap) {
+ const existing = get_struct(struct, typemap);
+ if (existing) return existing;
+ if (struct.decls === null || struct.decls === undefined) {
+ throw new UndefinedStructError(`Tried to use struct ${struct.name ?? "None"} before it is defined (does it have a definition?).`);
+ }
+ const ret = do_parse_struct(struct, typemap);
+ if (struct.name) typemap.structs.set(struct.name, ret);
+ typemap.structs.set(struct, ret);
+ return ret;
+}
+
+/** Returns [size, align, DetailedStructMember]. */
+export function parse_struct_member(type, field_name, typemap, { allow_unsized }) {
+ let align_override;
+ [type, align_override] = resolve_typedefs(type, typemap);
+ if (type instanceof PtrDecl) return [4, align_override || 4, null];
+ if (type instanceof ArrayDecl) {
+ let dim;
+ if (type.dim !== null && type.dim !== undefined) dim = parse_constant_int(type.dim, typemap);
+ else dim = 1;
+ const [size, align, substr] = parse_struct_member(type.type, field_name, typemap, { allow_unsized: false });
+ return [size * dim, align_override || align, new Array_(substr, type.type, size, dim)];
+ }
+ if (type instanceof FuncDecl) {
+ pyassert(allow_unsized, "Struct can not contain a function");
+ return [0, 0, null];
+ }
+ const inner_type = type.type;
+ if (inner_type instanceof ca.Struct || inner_type instanceof ca.Union) {
+ const substr = parse_struct(inner_type, typemap);
+ return [substr.size, align_override || substr.align, substr];
+ }
+ if (inner_type instanceof ca.Enum) parse_enum(inner_type, typemap);
+ pyassert(!(inner_type instanceof ca.Typeof), "handled by resolve_typedefs");
+ const size = primitive_size(inner_type);
+ if (size === 0 && !allow_unsized) throw new DecompFailure(`Field ${field_name} cannot be void`);
+ return [size, align_override || size, null];
+}
+
+function do_parse_struct(struct, typemap) {
+ const is_union = struct instanceof ca.Union;
+ pyassert(struct.decls !== null && struct.decls !== undefined, "enforced by caller");
+
+ const fields = new DefaultMap(() => []);
+ const bitfields = new DefaultMap(() => []);
+ let union_size = 0;
+ let offset = 0;
+ let bit_offset = 0;
+ let has_bitfields = false;
+ let align = get_align_override(struct, typemap) || typemap.base_struct_align;
+ const pack_struct = struct.gcc_attributes.some((attr) => attr.name === "packed");
+ const pragma_pack = typemap.pragma_packs.get(struct) ?? 0;
+
+ const flush_bitfields = () => {
+ if (!is_union && bit_offset !== 0) {
+ bit_offset = 0;
+ offset += 1;
+ }
+ };
+
+ for (const decl of struct.decls) {
+ if (is_union) pyassert(offset === 0);
+ if (!(decl instanceof ca.Decl)) continue;
+
+ let pack_decl;
+ if (pack_struct || decl.gcc_attributes.some((attr) => attr.name === "packed")) pack_decl = get_align_override(decl, typemap) || 1;
+ else pack_decl = 0;
+ if (pragma_pack && (!pack_decl || pack_decl > pragma_pack)) pack_decl = pragma_pack;
+
+ const type = decl.type;
+ if (type instanceof ca.Struct || type instanceof ca.Union) {
+ if (type.decls === null || type.decls === undefined) continue;
+ const substruct = parse_struct(type, typemap);
+ const subalign = pack_decl || get_align_override(decl, typemap) || substruct.align;
+ if (type.name !== null && type.name !== undefined) {
+ // Struct defined within another; parse_struct already registered it.
+ } else {
+ flush_bitfields();
+ align = Math.max(align, subalign);
+ offset = band(offset + subalign - 1, -subalign);
+ for (const [off, sfields] of substruct.fields) for (const field of sfields) fields.get(offset + off).push(field);
+ if (is_union) union_size = Math.max(union_size, substruct.size);
+ else offset += substruct.size;
+ }
+ continue;
+ }
+
+ if (type instanceof ca.Enum) {
+ parse_enum(type, typemap);
+ continue;
+ }
+
+ const field_name = `${struct.name ?? "None"}.${decl.name ?? "None"}`;
+ if (decl.bitsize !== null && decl.bitsize !== undefined) {
+ has_bitfields = true;
+ const width = parse_constant_int(decl.bitsize, typemap);
+ const [ssize, salign, substr] = parse_struct_member(type, field_name, typemap, { allow_unsized: false });
+ if (ssize !== salign || substr !== null) throw new DecompFailure(`Bitfield ${field_name} is not of primitive type`);
+ if (get_align_override(decl, typemap)) throw new DecompFailure(`Alignment directive not supported for bitfield ${field_name}`);
+ align = Math.max(align, salign);
+ if (width === 0) continue;
+ if (width > ssize * 8) throw new DecompFailure(`Width of bitfield ${field_name} exceeds its type`);
+ if (floordiv(offset, ssize) !== floordiv(offset + floordiv(bit_offset + width - 1, 8), ssize) && !pack_decl) {
+ bit_offset = 0;
+ offset = band(offset + ssize, -ssize);
+ }
+ if (decl.name !== null && decl.name !== undefined) bitfields.get(offset * 8 + bit_offset).push(new BitField(width, decl.name));
+ if (is_union) union_size = Math.max(union_size, ssize);
+ else {
+ bit_offset += width;
+ offset += floordiv(bit_offset, 8);
+ bit_offset &= 7;
+ }
+ continue;
+ }
+
+ if (decl.name === null || decl.name === undefined) continue;
+
+ flush_bitfields();
+ let [ssize, salign] = parse_struct_member(type, field_name, typemap, { allow_unsized: false });
+ salign = pack_decl || Math.max(salign, get_align_override(decl, typemap));
+ align = Math.max(align, salign);
+ offset = band(offset + salign - 1, -salign);
+ fields.get(offset).push(new StructField(type, ssize, decl.name));
+ if (is_union) union_size = Math.max(union_size, ssize);
+ else offset += ssize;
+ }
+
+ flush_bitfields();
+
+ let ctype;
+ if (typemap.struct_typedefs.has(struct)) ctype = typemap.struct_typedefs.get(struct);
+ else if (struct.name && typemap.struct_typedefs.has(struct.name)) ctype = typemap.struct_typedefs.get(struct.name);
+ else ctype = new TypeDecl(null, [], [], struct);
+
+ let size = is_union ? union_size : offset;
+ size = band(size + align - 1, -align);
+ return new Struct({ type: ctype, fields: new Map(fields), bitfields: new Map(bitfields), has_bitfields, size, align });
+}
+
+/** Add built-in typedefs to the source code. */
+export function add_builtin_typedefs(source) {
+ const typedefs = {
+ u8: "unsigned char",
+ s8: "char",
+ u16: "unsigned short",
+ s16: "short",
+ u32: "unsigned int",
+ s32: "int",
+ u64: "unsigned long long",
+ s64: "long long",
+ f32: "float",
+ f64: "double",
+ };
+ const line = Object.entries(typedefs)
+ .map(([k, v]) => `typedef ${v} ${k};`)
+ .join(" ");
+ return line + "\n" + source;
+}
+
+export function strip_comments(text) {
+ const pattern = /\/\/.*?$|\/\*[\s\S]*?\*\/|'(?:\\[\s\S]|[^\\'])*'|"(?:\\[\s\S]|[^\\"])*"/gm;
+ return text.replace(pattern, (s) => (s.startsWith("/") ? " " + "\n".repeat(count(s, "\n")) : s));
+}
+
+export function process_ifdef(text) {
+ const pattern = /^[ \t]*#if(?n?)def[ \t]+M2C\s+(?[\s\S]*?)(?:^[ \t]*#else\s+(?[\s\S]*?))?^[ \t]*#endif[\s\S]*?$/gm;
+ return text.replace(pattern, (...args) => {
+ const groups = args[args.length - 1];
+ const whole = args[0];
+ let ret;
+ if (groups.neg === "n") ret = groups.else_body || "";
+ else ret = groups.if_body;
+ return ret + "\n".repeat(Math.max(0, count(whole, "\n") - count(ret, "\n")));
+ });
+}
+
+/** Strip macro definitions from C source (m2c does not run the preprocessor). */
+export function strip_macro_defs(text) {
+ const pattern = /^[ \t]*#[ \t]*(?:define|undef)[ \t](\\\n|.)*/gm;
+ return text.replace(pattern, (m) => "\n".repeat(count(m, "\n")));
+}
+
+export function remove_backslashes_at_eol(text) {
+ const string_pat = /'(?:\\[\s\S]|[^\\'])*'?|"(?:\\[\s\S]|[^\\"])*"?/g;
+ let continued_string_start_ind = -1;
+ let continued_string_delim = "";
+ return text.replace(/\\\n/gm, (match, ind) => {
+ const line_start = text.lastIndexOf("\n", ind - 1) + 1;
+ let prev_line = text.slice(line_start, ind);
+ if (line_start === continued_string_start_ind) prev_line = continued_string_delim + prev_line;
+ const strings = (prev_line + "$").match(string_pat) ?? [];
+ if (strings.length && strings[strings.length - 1].endsWith("$")) {
+ const delim = strings[strings.length - 1][0];
+ continued_string_start_ind = ind + 2;
+ continued_string_delim = delim;
+ if (delim === "'") return "";
+ return delim + "\n" + delim;
+ }
+ continued_string_start_ind = -1;
+ return "\n";
+ });
+}
+
+export function parse_c(source, initial_scope) {
+ const c_parser = new CParser();
+ c_parser.clex.filename = "";
+ c_parser.clex.reset_lineno();
+ if (initial_scope !== null) c_parser._scope_stack = [new Map(initial_scope)];
+ c_parser._last_yielded_token = null;
+ let ast;
+ try {
+ ast = c_parser.cparser.parse(source, c_parser.clex);
+ } catch (e) {
+ if (e instanceof ParseError) {
+ let msg = String(e.message);
+ const coord = e.coord;
+ const i = msg.indexOf(": ");
+ msg = msg.slice(i + 2);
+ let posstr;
+ if (typeof coord === "string") posstr = " " + coord[0].toLowerCase() + coord.slice(1);
+ else {
+ const src = coord.source_line();
+ posstr = ` at line ${coord.line - 1}, column ${coord.column}\n\n${src}`;
+ }
+ throw new DecompFailure(`Syntax error when parsing C context.\n${msg}${posstr}`);
+ }
+ throw e;
+ }
+ return [ast, new Map(c_parser._scope_stack[0])];
+}
+
+/**
+ * Build the TypeMap for the given context files.
+ *
+ * Upstream has two caches, and neither changes the output, so the port parses
+ * every time (`--no-cache` / use_cache is accepted and ignored):
+ * - an lru_cache on _build_typemap keyed by (paths, arch object, use_cache).
+ * main.run() makes a fresh arch object per run, so it never hits across runs.
+ * - a pickle of the finished TypeMap beside each context ("foo.c.m2c"), reused
+ * when sha256(parent hash + source) matches. A hit returns the same TypeMap a
+ * fresh parse builds (object identity inside it is preserved by pickle), and
+ * upstream's own test runner relies on this: it runs the gba cases with
+ * --no-cache and the rest with the cache, against the same expected outputs,
+ * all of which the port reproduces without a cache. The one observable side
+ * effect, a "Warning: Unable to write cache file" line when the context's
+ * directory is read-only, exists only because of the file write, so it is not
+ * reproduced. Parsing a 160 KB decomp context takes about 0.15 s in the port,
+ * and Python's .m2c pickles cannot be read from JS anyway.
+ */
+export function build_typemap(source_paths, arch, use_cache) {
+ void use_cache;
+ const sources = source_paths.map((p) => fs.readFileSync(p, "utf8"));
+ return _build_typemap(source_paths, sources, arch);
+}
+
+function _build_typemap(source_paths, sources, arch) {
+ const typemap = new TypeMap({ source_hash: `root:${TypeMap.VERSION},${arch.base_struct_align}`, base_struct_align: arch.base_struct_align });
+
+ for (let source of sources) {
+ if (source.charCodeAt(0) === 0xfeff) source = source.slice(1);
+ source = source.replace(/\r\n?/g, "\n");
+ source = add_builtin_typedefs(source);
+ source = strip_comments(source);
+ source = process_ifdef(source);
+ source = strip_macro_defs(source);
+ source = remove_backslashes_at_eol(source);
+
+ const [ast, result_scope] = parse_c(source, typemap.cparser_scope);
+ typemap.cparser_scope = result_scope;
+
+ for (const item of ast.ext) {
+ if (item instanceof ca.Typedef) {
+ let [target, align] = resolve_typedefs(item.type, typemap);
+ align = get_align_override(item, typemap) || align;
+ if (has_128bit_attr(item.gcc_attributes) && target instanceof TypeDecl && target.type instanceof ca.IdentifierType) {
+ const sign = target.type.names.includes("unsigned") ? ["unsigned"] : [];
+ target = basic_type([...sign, "__int128"]);
+ }
+ typemap.typedefs.set(item.name, [target, align]);
+ if (item.type instanceof TypeDecl && (item.type.type instanceof ca.Struct || item.type.type instanceof ca.Union) && !get_align_override(item, typemap)) {
+ const typedef = basic_type([item.name]);
+ if (item.type.type.name) typemap.struct_typedefs.set(item.type.type.name, typedef);
+ typemap.struct_typedefs.set(item.type.type, typedef);
+ }
+ }
+ if (item instanceof ca.FuncDef) {
+ pyassert(item.decl.name !== null && item.decl.name !== undefined, "cannot define anonymous function");
+ const fn = parse_function(type_of_var_decl(item.decl));
+ pyassert(fn !== null);
+ typemap.functions.set(item.decl.name, fn);
+ }
+ if (item instanceof ca.Decl && item.type instanceof FuncDecl) {
+ pyassert(item.name !== null && item.name !== undefined, "cannot define anonymous function");
+ const fn = parse_function(item.type);
+ pyassert(fn !== null);
+ typemap.functions.set(item.name, fn);
+ }
+ }
+
+ let cur_pack = 0;
+ const pack_stack = [];
+
+ class Visitor extends ca.NodeVisitor {
+ visit_Pragma(node) {
+ const parts = node.string.split("(");
+ if (parts.length >= 2 && parts[0].trim() === "pack") {
+ const args = parts[1].split(")")[0].split(",");
+ const arg = args[0].trim();
+ if (!arg) cur_pack = 0;
+ else if (args[0].trim() === "pop") {
+ if (!pack_stack.length) throw new Error("IndexError: pop from empty list");
+ cur_pack = pack_stack.pop();
+ } else if (args[0].trim() === "push") {
+ pack_stack.push(cur_pack);
+ if (args.length >= 2) cur_pack = int_(args[1], 0);
+ } else cur_pack = int_(args[0], 0);
+ }
+ }
+ visit_Struct(node) {
+ if (cur_pack) typemap.pragma_packs.set(node, cur_pack);
+ if (node.decls !== null && node.decls !== undefined) parse_struct(node, typemap);
+ }
+ visit_Union(node) {
+ if (cur_pack) typemap.pragma_packs.set(node, cur_pack);
+ if (node.decls !== null && node.decls !== undefined) parse_struct(node, typemap);
+ }
+ visit_Decl(node) {
+ if (node.name !== null && node.name !== undefined) {
+ typemap.var_types.set(node.name, type_from_global_decl(node));
+ if (node.init !== null && node.init !== undefined) typemap.vars_with_initializers.add(node.name);
+ }
+ if (!(node.type instanceof FuncDecl)) this.visit(node.type);
+ }
+ visit_Enum(node) {
+ parse_enum(node, typemap);
+ }
+ visit_FuncDef(node) {
+ if (node.decl.name !== null && node.decl.name !== undefined) typemap.var_types.set(node.decl.name, type_from_global_decl(node.decl));
+ }
+ }
+ new Visitor().visit(ast);
+ }
+ void source_paths;
+ return typemap;
+}
+
+export function set_decl_name(decl) {
+ const name = decl.name;
+ let type = type_of_var_decl(decl);
+ while (!(type instanceof TypeDecl)) type = type.type;
+ type.declname = name;
+}
+
+export function type_to_string(type, name = "") {
+ if (type instanceof TypeDecl && (type.type instanceof ca.Struct || type.type instanceof ca.Union || type.type instanceof ca.Enum)) {
+ let su;
+ if (type.type instanceof ca.Struct) su = "struct";
+ else su = type.type instanceof ca.Union ? "union" : "enum";
+ if (type.type.name) return `${su} ${type.type.name}`;
+ return `anon ${su}`;
+ }
+ const decl = new ca.Decl(name, [], [], [], [], [], deepcopy(type), null, null, null);
+ set_decl_name(decl);
+ return to_c(decl);
+}
+
+export function dump_typemap(typemap) {
+ print("Variables:");
+ for (const [v, type] of typemap.var_types) print(`${type_to_string(type, v)};`);
+ print();
+ print("Functions:");
+ for (const [name, fn] of typemap.functions) print(`${type_to_string(fn.type, name)};`);
+ print();
+ print("Structs:");
+ for (const [name_or_id, struct] of typemap.structs) {
+ if (typeof name_or_id !== "string") continue;
+ print(`${name_or_id}: size ${hex(struct.size)}, align ${struct.align}`);
+ for (const [offset, fields] of struct.fields) {
+ print(` ${hex(offset)}:`, popts({ end: "" }));
+ for (const field of fields) print(` ${field.name} (${type_to_string(field.type)})`, popts({ end: "" }));
+ print();
+ }
+ }
+ print();
+ print("Enums:");
+ for (const [name, value] of typemap.enum_values) print(`${name}: ${value}`);
+ print();
+}
diff --git a/packages/romdev-m2c/src/cli.js b/packages/romdev-m2c/src/cli.js
new file mode 100755
index 00000000..b77c7459
--- /dev/null
+++ b/packages/romdev-m2c/src/cli.js
@@ -0,0 +1,8 @@
+#!/usr/bin/env node
+// Command-line entry point taking the same flags as upstream m2c's CLI.
+import { decompile } from "./main.js";
+
+const r = await decompile(process.argv.slice(2));
+process.stdout.write(r.stdout);
+process.stderr.write(r.stderr);
+process.exitCode = r.code;
diff --git a/packages/romdev-m2c/src/demangle_codewarrior.js b/packages/romdev-m2c/src/demangle_codewarrior.js
new file mode 100644
index 00000000..c310dbad
--- /dev/null
+++ b/packages/romdev-m2c/src/demangle_codewarrior.js
@@ -0,0 +1,525 @@
+// demangle_codewarrior.js - CodeWarrior C++ symbol demangler (port of
+// m2c/demangle_codewarrior.py), supporting operators, templates (including
+// literals), and arrays.
+//
+// CodeWarrior's symbol mangling and C++ ABI seems to be based on the
+// Macintosh spec, section 3.4.1.2 (page 18) of
+// https://mirror.informatimago.com/next/developer.apple.com/tools/mpw-tools/compilers/docs/abi_spec.pdf
+// It deviates from this spec in a few key ways:
+// - The in is an unterminated (no '_' separator)
+// - Parameterized types use '<', ',' and '>' characters instead of the "__PT" prefix
+//
+// Like the rest of m2c this file is licensed under the GPL v3. It is based on
+// `demangler.cs` by arookas, provided under the 3-clause BSD License:
+// https://gist.github.com/arookas/0c0cd842c9ca836d7a9ed06a655b1a22
+//
+// Copyright (c) 2017, arookas
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+import { ValueError, pyassert, repr } from "./py.js";
+
+// These substitutions are performed by the doldisasm.py decomp tool, and not by
+// the CodeWarrior compiler directly. Undo them for convience.
+const DOLDISASM_SUBSTITUTIONS = [
+ ["<", "$$0"],
+ [">", "$$1"],
+ ["@", "$$2"],
+ ["\\", "$$3"],
+ [",", "$$4"],
+ ["-", "$$5"],
+];
+
+/** Minimal io.StringIO: read(n), tell(), seek(pos). */
+class StringIO {
+ constructor(s) {
+ this.s = s;
+ this.pos = 0;
+ }
+ read(n = -1) {
+ const start = this.pos;
+ const end = n < 0 ? this.s.length : Math.min(this.s.length, start + n);
+ this.pos = end;
+ return this.s.slice(start, end);
+ }
+ tell() {
+ return this.pos;
+ }
+ seek(p) {
+ this.pos = p;
+ }
+}
+
+/** Read exactly `size` chars from `src`, or raise a ValueError. */
+function read_exact(src, size) {
+ const value = src.read(size);
+ if (value.length !== size) throw new ValueError(`Unable to read ${size} bytes; got ${repr(value)}`);
+ return value;
+}
+
+/** Run fn, restoring the offset of `src` afterwards. */
+function peeking(src, fn) {
+ const ptr = src.tell();
+ try {
+ return fn();
+ } finally {
+ src.seek(ptr);
+ }
+}
+
+/** Read up to `n` chars from `src` without advancing the offset. */
+function peek(src, n = 1) {
+ return peeking(src, () => src.read(n));
+}
+
+/** Wrap `s` in a StringIO for fn, and assert it was fully consumed after fn returns. */
+function as_stringio(s, fn) {
+ const buf = new StringIO(s);
+ const result = fn(buf);
+ const leftover = buf.read();
+ if (leftover) throw new ValueError(`Unable to parse full input, leftover chars: ${repr(leftover)}`);
+ return result;
+}
+
+// Python int(str) for base 10 (optional sign, digits); ValueError otherwise.
+function pyInt(s) {
+ const t = s.trim();
+ if (!/^[+-]?[0-9]+(_[0-9]+)*$/.test(t)) throw new ValueError(`invalid literal for int() with base 10: ${repr(s)}`);
+ return parseInt(t.replaceAll("_", ""), 10);
+}
+
+/**
+ * The name of a C++ symbol, class, or namespace, optionally parameterized
+ * with `template_params`.
+ */
+export class CxxName {
+ constructor(name, template_params = null) {
+ this.name = name;
+ this.template_params = template_params;
+ }
+ static parse(src) {
+ // Numbers: either a template literal, or a length prefix
+ let number_str = "";
+ while (CxxName.NUMBER_CHARS.has(peek(src))) number_str += read_exact(src, 1);
+ if (number_str === "") throw new ValueError("Unable to parse CxxName, input did not start with a number");
+ const number = pyInt(number_str);
+
+ // Check if the number represents a template literal
+ const p = peek(src);
+ if (p === "," || p === ">") return new CxxName(number_str);
+
+ // Otherwise, it is the length of the name
+ if (number <= 0) throw new ValueError("length must be positive");
+ const name = read_exact(src, number);
+
+ // Simple case: plain identifier
+ if (!name.includes("<")) return new CxxName(name);
+
+ // Otherwise, parse the template parameters between the `<...>` brackets
+ if (name[name.length - 1] !== ">") throw new ValueError("unpaired '<'");
+ const idx = name.indexOf("<");
+ const base_name = name.slice(0, idx);
+ const param_strs = name.slice(idx + 1);
+
+ const template_params = as_stringio(param_strs, (buf) => {
+ const params = [];
+ for (;;) {
+ params.push(CxxType.parse(buf));
+ const sep = read_exact(buf, 1);
+ if (sep === ">") break;
+ if (sep === ",") continue;
+ throw new ValueError(`Unexpected character while parsing CxxName: ${sep}`);
+ }
+ return params;
+ });
+ return new CxxName(base_name, template_params);
+ }
+ __str__() {
+ if (this.template_params === null) return this.name;
+ return `${this.name}<${this.template_params.map((p) => p.__str__()).join(", ")}>`;
+ }
+ toString() {
+ return this.__str__();
+ }
+}
+CxxName.NUMBER_CHARS = new Set("-0123456789");
+
+const KIND_VALUES = {
+ CONST: "C",
+ POINTER: "P",
+ REFERENCE: "R",
+ SIGNED: "S",
+ UNSIGNED: "U",
+ ELLIPSIS: "e",
+ VOID: "v",
+ BOOL: "b",
+ CHAR: "c",
+ SHORT: "s",
+ INT: "i",
+ LONG: "l",
+ LONG_LONG: "x",
+ WIDE_CHAR: "w",
+ FLOAT: "f",
+ DOUBLE: "d",
+ LONG_DOUBLE: "r",
+ ARRAY: "A",
+ QUALIFIED: "Q",
+ FUNCTION: "F",
+ SYMBOL_REFERENCE: "&",
+};
+
+/** CxxTerm.Kind: an Enum whose members have .name and .value. */
+class Kind {
+ constructor(name, value) {
+ this.name = name;
+ this.value = value;
+ }
+ /** Kind(value) lookup, raising ValueError for an unknown value like Python's Enum. */
+ static of(value) {
+ const k = Kind.byValue.get(value);
+ if (!k) throw new ValueError(`${repr(value)} is not a valid Kind`);
+ return k;
+ }
+}
+Kind.byValue = new Map();
+for (const [name, value] of Object.entries(KIND_VALUES)) {
+ const k = new Kind(name, value);
+ Kind[name] = k;
+ Kind.byValue.set(value, k);
+}
+
+/**
+ * A part of a C++ type, like a token: usually a single letter of a mangled
+ * type, or an ARRAY / FUNCTION / QUALIFIED name / SYMBOL_REFERENCE.
+ */
+export class CxxTerm {
+ constructor(kind, { array_dim = null, function_params = null, function_return = null, qualified_name = null, symbol_reference = null } = {}) {
+ this.kind = kind;
+ this.array_dim = array_dim;
+ this.function_params = function_params;
+ this.function_return = function_return;
+ this.qualified_name = qualified_name;
+ this.symbol_reference = symbol_reference;
+ }
+ static parse(src) {
+ if (CxxName.NUMBER_CHARS.has(peek(src))) {
+ return new CxxTerm(Kind.QUALIFIED, { qualified_name: [CxxName.parse(src)] });
+ }
+ const kind = Kind.of(read_exact(src, 1));
+ if (kind === Kind.QUALIFIED) {
+ const count = pyInt(read_exact(src, 1));
+ const qualified_name = [];
+ for (let i = 0; i < count; i++) qualified_name.push(CxxName.parse(src));
+ return new CxxTerm(kind, { qualified_name });
+ }
+ if (kind === Kind.FUNCTION) {
+ const function_params = [];
+ let function_return = null;
+ while (!["", "_", ",", ">"].includes(peek(src))) function_params.push(CxxType.parse(src));
+ if (peek(src, 1) === "_") {
+ read_exact(src, 1);
+ function_return = CxxType.parse(src);
+ }
+ return new CxxTerm(kind, { function_params, function_return });
+ }
+ if (kind === Kind.ARRAY) {
+ let array_dim = 0;
+ for (;;) {
+ const c = read_exact(src, 1);
+ if (c === "_") break;
+ array_dim = array_dim * 10 + pyInt(c);
+ }
+ return new CxxTerm(kind, { array_dim });
+ }
+ if (kind === Kind.SYMBOL_REFERENCE) {
+ return new CxxTerm(kind, { symbol_reference: CxxSymbol.parse(src) });
+ }
+ return new CxxTerm(kind);
+ }
+ __str__() {
+ if (this.kind === Kind.ARRAY) {
+ pyassert(this.array_dim !== null);
+ return `[${this.array_dim}]`;
+ }
+ if (this.kind === Kind.QUALIFIED) {
+ pyassert(this.qualified_name !== null);
+ const names = this.qualified_name.map((q) => q.__str__());
+ const last = names[names.length - 1];
+ if (Object.prototype.hasOwnProperty.call(CxxTerm.OPS, last)) {
+ names[names.length - 1] = "operator" + CxxTerm.OPS[last];
+ } else if (last === "__ct") {
+ pyassert(names.length >= 2);
+ names[names.length - 1] = names[names.length - 2];
+ } else if (last === "__dt") {
+ pyassert(names.length >= 2);
+ names[names.length - 1] = `~${names[names.length - 2]}`;
+ }
+ return names.join("::");
+ }
+ if (this.kind === Kind.FUNCTION) {
+ pyassert(this.function_params !== null);
+ let prefix = "";
+ if (this.function_return !== null) prefix = `${this.function_return.__str__()} (*) `;
+ const args = this.function_params.map((p) => p.__str__()).join(", ");
+ return `${prefix}(${args})`;
+ }
+ if (this.kind === Kind.SYMBOL_REFERENCE) {
+ pyassert(this.symbol_reference !== null);
+ return `&${this.symbol_reference.__str__()}`;
+ }
+ if (this.kind === Kind.POINTER) return "*";
+ if (this.kind === Kind.REFERENCE) return "&";
+ if (this.kind === Kind.LONG_LONG) return "long long";
+ if (this.kind === Kind.LONG_DOUBLE) return "long double";
+ if (this.kind === Kind.WIDE_CHAR) return "wchar_t";
+ if (this.kind === Kind.ELLIPSIS) return "...";
+ return this.kind.name.toLowerCase();
+ }
+ toString() {
+ return this.__str__();
+ }
+}
+CxxTerm.Kind = Kind;
+CxxTerm.NONTERMINATING_KINDS = new Set([Kind.CONST, Kind.POINTER, Kind.REFERENCE, Kind.SIGNED, Kind.UNSIGNED, Kind.ARRAY]);
+CxxTerm.OPS = {
+ __nw: " new",
+ __nwa: " new[]",
+ __dl: " delete",
+ __dla: " delete[]",
+ __pl: "+",
+ __mi: "-",
+ __ml: "*",
+ __dv: "/",
+ __md: "%",
+ __er: "^",
+ __adv: "/=",
+ __ad: "&",
+ __or: "|",
+ __co: "~",
+ __nt: "!",
+ __as: "=",
+ __lt: "<",
+ __gt: ">",
+ __apl: "+=",
+ __ami: "-=",
+ __amu: "*=",
+ __amd: "%=",
+ __aer: "^=",
+ __aad: "&=",
+ __aor: "|=",
+ __ls: "<<",
+ __rs: ">>",
+ __ars: ">>=",
+ __als: "<<=",
+ __eq: "==",
+ __ne: "!=",
+ __le: "<=",
+ __ge: ">=",
+ __aa: "&&",
+ __oo: "||",
+ __pp: "++",
+ __mm: "--",
+ __cl: "()",
+ __vc: "[]",
+ __rf: "->",
+ __cm: ",",
+ __rm: "->*",
+};
+
+/**
+ * A complete C++ type. The final element in `terms` is the primitive type;
+ * working from the end, each previous term modifies the type.
+ */
+export class CxxType {
+ constructor(terms = []) {
+ this.terms = terms;
+ }
+ static parse(src) {
+ const terms = [];
+ for (;;) {
+ const p = peek(src);
+ if (p === "," || p === ">") break;
+ const term = CxxTerm.parse(src);
+ terms.push(term);
+ if (!CxxTerm.NONTERMINATING_KINDS.has(term.kind)) break;
+ }
+ return new CxxType(terms);
+ }
+ __str__() {
+ return this.terms.slice().reverse().map((a) => a.__str__()).join(" ").trim();
+ }
+ toString() {
+ return this.__str__();
+ }
+}
+
+/** A C++ symbol and its type. */
+export class CxxSymbol {
+ constructor(name, type) {
+ this.name = name;
+ this.type = type;
+ }
+ static parse(src) {
+ // Find the `base_name`: the prefix of `src` which usually represents the
+ // original, unmangled name, typically separated from the type information
+ // by the rightmost "__" (with many edge cases).
+ let strip_underscores = 0;
+ let template_depth = 0;
+ let base_name = peeking(src, () => src.read());
+ peeking(src, () => {
+ let chars = "";
+ for (;;) {
+ const c = src.read(1);
+ if (!c) break;
+ if ((c === "," || c === ">") && template_depth === 0) {
+ if (strip_underscores === 0) base_name = chars;
+ break;
+ } else if (c === "<") {
+ template_depth += 1;
+ } else if (c === ">") {
+ template_depth -= 1;
+ }
+ chars += c;
+ if (CxxSymbol.STATIC_FUNCTIONS.has(chars)) {
+ base_name = chars;
+ strip_underscores = 1;
+ break;
+ } else if (c === "_" && peek(src) === "_") {
+ const lookahead = peek(src, 2);
+ if (lookahead.length < 2 || "CFQ0123456789".includes(lookahead[1])) {
+ base_name = chars.slice(0, -1);
+ strip_underscores = 2;
+ }
+ }
+ }
+ });
+
+ read_exact(src, base_name.length + strip_underscores);
+
+ if (CxxSymbol.STATIC_FUNCTIONS.has(base_name)) {
+ // `__sinit_Foo_cpp` is the static constructor for "Foo.cpp":
+ // "demangle" it into `void Foo_cpp::__sinit(void)`.
+ const type = as_stringio("Fv_v", (buf) => CxxType.parse(buf));
+ return new CxxSymbol(new CxxTerm(Kind.QUALIFIED, { qualified_name: [new CxxName(src.read()), new CxxName(base_name)] }), type);
+ }
+
+ // After the "__", the base_name is followed by the (optional) qualified class name, then the type.
+ let class_name = CxxType.parse(src);
+ let type;
+ if (!["", ",", ">"].includes(peek(src))) {
+ type = CxxType.parse(src);
+ } else {
+ pyassert(class_name !== null);
+ type = class_name;
+ class_name = null;
+ }
+
+ const qualified_name = [];
+ if (class_name !== null) {
+ pyassert(class_name.terms.length === 1);
+ pyassert(class_name.terms[0].kind === Kind.QUALIFIED);
+ pyassert(class_name.terms[0].qualified_name !== null);
+ qualified_name.push(...class_name.terms[0].qualified_name);
+ }
+ as_stringio(String(base_name.length) + base_name, (buf) => qualified_name.push(CxxName.parse(buf)));
+
+ const name = new CxxTerm(Kind.QUALIFIED, { qualified_name });
+ return new CxxSymbol(name, type);
+ }
+ __str__() {
+ return `${this.name.__str__()} ${this.type.__str__()}`;
+ }
+ toString() {
+ return this.__str__();
+ }
+}
+CxxSymbol.STATIC_FUNCTIONS = new Set(["__sinit", "__sterm"]);
+
+/** Parse a mangled CodeWarrior symbol. */
+export function parse(mangled) {
+ for (const [old, neu] of DOLDISASM_SUBSTITUTIONS) mangled = mangled.replaceAll(neu, old);
+ return as_stringio(mangled, (buf) => CxxSymbol.parse(buf));
+}
+
+/** Demangle `mangled`, returning it unchanged when it does not parse. */
+export function demangle(mangled) {
+ try {
+ return parse(mangled).__str__();
+ } catch (e) {
+ if (e instanceof ValueError) return mangled;
+ throw e;
+ }
+}
+
+/** The module's self-test table: [mangled, expected demangled]. */
+export const TEST_CASES = [
+ // Unmangled, but with underscores
+ ["__foo_bar", "__foo_bar"],
+ // Namespacing
+ ["get__6FoobarFi", "Foobar::get (int)"],
+ // Constructor / Destructor
+ ["__ct__10FooBarFoosFP7ArgPtrsUsPCc", "FooBarFoos::FooBarFoos (ArgPtrs *, short unsigned, char const *)"],
+ ["__dt__10FooBarFoosFv", "FooBarFoos::~FooBarFoos (void)"],
+ // Overloaded operators
+ ["__dl__FPv", "operator delete (void *)"],
+ ["__nw__FUl", "operator new (long unsigned)"],
+ ["__eq__3FooCFRC3Foo", "Foo::operator== (Foo const &) const"],
+ // Namespacing & templated arguments
+ [
+ "do__Q214GrandFooSystem8MiniFoosFUlPC3VecP3VecfUlUlPP8LateBazzUlUc",
+ "GrandFooSystem::MiniFoos::do (long unsigned, Vec const *, Vec *, float, long unsigned, long unsigned, LateBazz * *, long unsigned, char unsigned)",
+ ],
+ [
+ "spin__11ThingieBaseFRCQ29MyLibrary8FVec3$$0f$$1RCQ29MyLibrary8FVec3$$0f$$1RCQ29MyLibrary8FVec3$$0f$$1",
+ "ThingieBase::spin (MyLibrary::FVec3 const &, MyLibrary::FVec3 const &, MyLibrary::FVec3 const &)",
+ ],
+ // Templated function names
+ ["function<&alpha,&beta,&GAMMA>__FR5Class_i", "function<&alpha, &beta, &GAMMA> int (*) (Class &)"],
+ ["function<&m0__5Class,&mf0__5ClassFi>__FR5Class_i", "function<&m0 Class, &Class::mf0 (int)> int (*) (Class &)"],
+ // Static functions
+ ["__sinit_Foo_cpp", "Foo_cpp::__sinit void (*) (void)"],
+ ["__sterm_Foo_cpp", "Foo_cpp::__sterm void (*) (void)"],
+ // Confusing function names (check that we split on the last valid "__")
+ ["foo__3BarFv", "Bar::foo (void)"],
+ ["foo__3BarFv__3BarFv", "Bar::foo__3BarFv (void)"],
+ ["foo__Q23Bar3BarFv__3BarFv", "Bar::foo__Q23Bar3BarFv (void)"],
+ ["copy__Q23std14__copy$$0Pv$$41$$40$$1FPPvPPvPPv", "std::__copy::copy (void * *, void * *, void * *)"],
+ ["__init__bar__9Bar$$03Foo$$1", "__init__bar Bar"],
+ ["bar__5__BarFv", "__Bar::bar (void)"],
+ // These examples we fail to demangle correctly
+ ["bar__5__FooFv", "bar__5__FooFv"], // should be "__Foo::bar (void)"
+ ["foo__Ul", "foo__Ul"], // should be "foo long unsigned" (or "long unsigned foo")
+];
+
+/** Run the self-test table; returns true when every case matches. */
+export function test() {
+ let all_pass = true;
+ for (const [mangled, demangled] of TEST_CASES) {
+ const output = demangle(mangled);
+ if (output !== demangled) all_pass = false;
+ }
+ return all_pass;
+}
diff --git a/packages/romdev-m2c/src/error.js b/packages/romdev-m2c/src/error.js
new file mode 100644
index 00000000..e3448eb7
--- /dev/null
+++ b/packages/romdev-m2c/src/error.js
@@ -0,0 +1,17 @@
+// Port of m2c/error.py
+import { repr } from "./py.js";
+
+export class DecompFailure extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "DecompFailure";
+ this.message = message;
+ }
+ __str__() {
+ return this.message;
+ }
+}
+
+export function assert_never(x) {
+ throw new Error(`Unreachable: ${repr(x)}`);
+}
diff --git a/packages/romdev-m2c/src/evaluate.js b/packages/romdev-m2c/src/evaluate.js
new file mode 100644
index 00000000..66990898
--- /dev/null
+++ b/packages/romdev-m2c/src/evaluate.js
@@ -0,0 +1,988 @@
+// Port of m2c/evaluate.py
+// Functions for evaluating assembly instructions and building Expression trees.
+import { AsmSymbolicData } from "./asm_file.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Register } from "./asm_instruction.js";
+import { DecompFailure } from "./error.js";
+import { Target } from "./options.js";
+import {
+ AddressMode,
+ AddressOf,
+ ArrayAccess,
+ BinaryOp,
+ CarryBit,
+ Cast,
+ Condition,
+ ErrorExpr,
+ ExprCondition,
+ ExprStmt,
+ Expression,
+ FuncCall,
+ GlobalSymbol,
+ Literal,
+ Load3Bytes,
+ LocalVar,
+ Lwl,
+ StoreStmt,
+ StructAccess,
+ TernaryOp,
+ UnalignedLoad,
+ UnaryOp,
+ as_intish,
+ as_intptr,
+ as_type,
+ early_unwrap,
+ early_unwrap_ints,
+ var_for_expr,
+} from "./translate.js";
+import { FunctionParam, FunctionSignature, StructDeclaration, Type } from "./types.js";
+import { normint, band, bit_length, bnot, bor, bxor, dcreplace, floordiv, format, pyassert, pyeq, pymod, pyround, shl, shr } from "./py.js";
+
+export function error_stmt(msg) {
+ return new ExprStmt(new ErrorExpr(msg));
+}
+
+export function deref(arg, regs, stack_info, { size, store = false }) {
+ let offset;
+ let v;
+ if (arg instanceof Expression) {
+ offset = 0;
+ v = arg;
+ } else if (arg instanceof AddressMode) {
+ offset = arg.offset;
+ if (stack_info.is_stack_reg(arg.base)) return stack_info.get_stack_var(offset, { store });
+ v = regs.get(arg.base);
+ } else {
+ offset = arg.offset;
+ v = stack_info.global_info.address_of_gsym(arg.sym.symbol_name);
+ }
+
+ if (v instanceof Literal && pymod(v.value, 2 ** 16) === 0) {
+ v = new Literal(v.value + offset, { type: v.type });
+ offset = 0;
+ }
+
+ let uw_var = early_unwrap(v);
+ if (uw_var instanceof BinaryOp && uw_var.op === "+") {
+ for (const [base, addend] of [
+ [uw_var.left, uw_var.right],
+ [uw_var.right, uw_var.left],
+ ]) {
+ const arch = stack_info.global_info.arch;
+ if (addend instanceof Literal && (arch.is_likely_partial_offset(addend.value) || (offset === 0 && addend.value >= 0))) {
+ offset += addend.value;
+ v = base;
+ uw_var = early_unwrap(v);
+ break;
+ }
+ }
+ }
+ if (uw_var instanceof AddressOf && uw_var.expr instanceof StructAccess) {
+ const base = uw_var.expr.struct_var;
+ const iaddend = uw_var.expr.offset;
+ const target = stack_info.global_info.target;
+ const arch = stack_info.global_info.arch;
+ if (arch.is_likely_partial_offset(iaddend) || target.compiler !== Target.CompilerEnum.IDO) {
+ offset += iaddend;
+ v = base;
+ uw_var = early_unwrap(v);
+ }
+ }
+
+ v.type.unify(Type.ptr());
+ stack_info.record_struct_access(v, offset);
+ let type = stack_info.unique_type_for("struct", [uw_var, offset], Type.any());
+
+ if (offset >= 0x200000) {
+ v = BinaryOp.int(new Literal(offset), "+", v);
+ offset = 0;
+ }
+
+ const array_expr = array_access_from_add(v, offset, stack_info, { target_size: size, ptr: false });
+ if (array_expr !== null) return array_expr;
+ let [field_path, field_type] = v.type.get_deref_field(offset, { target_size: size });
+ if (field_path !== null) {
+ field_type.unify(type);
+ type = field_type;
+ } else field_path = null;
+
+ return new StructAccess({ struct_var: v, offset, target_size: size, field_path, stack_info, type });
+}
+
+export function condition_from_expr(expr) {
+ const uw_expr = early_unwrap(expr);
+ if (uw_expr instanceof Condition && !(uw_expr instanceof BinaryOp && !uw_expr.is_comparison())) return uw_expr;
+ return new ExprCondition(expr, { type: expr.type });
+}
+
+export function imm_add_32(expr) {
+ if (expr instanceof Literal) return as_intish(new Literal(expr.value + 32));
+ return BinaryOp.int(expr, "+", new Literal(32));
+}
+
+export function fn_op(fn_name, args, type) {
+ const fn_sig = new FunctionSignature({
+ return_type: type,
+ params: args.map((arg) => new FunctionParam({ type: arg.type })),
+ params_known: true,
+ is_variadic: false,
+ });
+ return new FuncCall({ function: new GlobalSymbol({ c_symbol_name: fn_name, type: Type.function(fn_sig) }), args, type });
+}
+
+export function void_fn_op(fn_name, args) {
+ const fn_call = fn_op(fn_name, args, Type.any_reg());
+ fn_call.use();
+ return new ExprStmt(fn_call);
+}
+
+export function load_upper(args) {
+ pyassert(!(args.raw_arg(1) instanceof Literal), "normalize_instruction should convert lui/lis to li");
+ const ref = args.hi_imm(1);
+ const stack_info = args.stack_info;
+ const source = stack_info.global_info.address_of_gsym(ref.sym.symbol_name);
+ const imm = new Literal(ref.offset);
+ return handle_addi_real(args.reg_ref(0), null, source, imm, args);
+}
+
+export function handle_convert(expr, dest_type, source_type) {
+ const silent = dest_type.data().kind !== source_type.data().kind;
+ expr.type.unify(source_type);
+ return new Cast({ expr, type: dest_type, silent, reinterpret: false });
+}
+
+export function handle_la(args) {
+ const output_reg = args.reg_ref(0);
+ const target = args.memory_ref(1);
+ const stack_info = args.stack_info;
+ if (target instanceof AddressMode) return handle_addi(output_reg, target.base, args.regs.get(target.base), new Literal(target.offset), args);
+ const sym = stack_info.global_info.address_of_gsym(target.sym.symbol_name);
+ return add_imm(output_reg, sym, new Literal(target.offset), args);
+}
+
+export function handle_lw(args) {
+ const ref = args.maybe_got_imm(1);
+ if (ref !== null) {
+ const sym = args.stack_info.global_info.address_of_gsym(ref.sym.symbol_name);
+ return add_imm(args.reg_ref(0), sym, new Literal(ref.offset), args);
+ }
+ return handle_load(args, Type.reg32({ likely_float: false }));
+}
+
+export function handle_or(left, right, { is_arm = false } = {}) {
+ if (pyeq(left, right)) return left;
+ if (left instanceof Literal && left.value === 0) return right;
+ if (right instanceof Literal && right.value === 0) return left;
+ if (left instanceof Literal && right instanceof Literal) {
+ if ((band(left.value, 0xffff) === 0 && band(right.value, 0xffff0000) === 0) || (band(right.value, 0xffff) === 0 && band(left.value, 0xffff0000) === 0)) {
+ return new Literal({ value: bor(left.value, right.value) });
+ }
+ }
+ const uw_left = early_unwrap(left);
+ if (
+ is_arm &&
+ uw_left instanceof BinaryOp &&
+ uw_left.op === "|" &&
+ uw_left.right instanceof Literal &&
+ right instanceof Literal &&
+ (pymod(uw_left.right.value, 0x100) === 0 || pymod(right.value, 0x100) === 0)
+ ) {
+ const imm = bor(uw_left.right.value, right.value);
+ return BinaryOp.int(uw_left.left, "|", new Literal(imm));
+ }
+ return BinaryOp.int(left, "|", right);
+}
+
+export function handle_bitinv(expr) {
+ if (expr instanceof Literal) return s32_literal(bnot(expr.value));
+ return UnaryOp.int("~", expr);
+}
+
+export function handle_sltu(args) {
+ const right = args.reg(2);
+ if (args.reg_ref(1) === new Register("zero")) {
+ const uw_right = early_unwrap(right);
+ if (uw_right instanceof BinaryOp && uw_right.op === "^") return BinaryOp.icmp(uw_right.left, "!=", uw_right.right);
+ return BinaryOp.icmp(right, "!=", new Literal(0));
+ }
+ const left = args.reg(1);
+ return BinaryOp.ucmp(left, "<", right);
+}
+
+export function handle_sltiu(args) {
+ const left = args.reg(1);
+ let right = args.s16_imm(2);
+ if (right instanceof Literal) {
+ const value = band(right.value, 0xffffffff);
+ if (value === 1) {
+ const uw_left = early_unwrap(left);
+ if (uw_left instanceof BinaryOp && uw_left.op === "^") return BinaryOp.icmp(uw_left.left, "==", uw_left.right);
+ return BinaryOp.icmp(left, "==", new Literal(0));
+ } else right = new Literal(value);
+ }
+ return BinaryOp.ucmp(left, "<", right);
+}
+
+export function handle_xor(left, right) {
+ if (right instanceof Literal && right.value === 1) {
+ const uw_left = early_unwrap(left);
+ if (uw_left instanceof BinaryOp && uw_left.is_comparison()) return uw_left.negated();
+ }
+ return BinaryOp.int(left, "^", right);
+}
+
+export function handle_addi_mips(args) {
+ const output_reg = args.reg_ref(0);
+ const source_reg = args.reg_ref(1);
+ const ref = args.maybe_gprel_imm(2);
+ if (ref !== null && source_reg === new Register("gp")) {
+ const sym = args.stack_info.global_info.address_of_gsym(ref.sym.symbol_name);
+ return add_imm(output_reg, sym, new Literal(ref.offset), args);
+ }
+ return handle_addi(output_reg, source_reg, args.reg(1), args.s16_imm(2), args);
+}
+
+export function handle_addi(output_reg, source_reg, source, imm, args) {
+ if (pyeq(imm, new Literal(0))) return source;
+ const arm = args.stack_info.global_info.arch.arch === Target.ArchEnum.ARM;
+ const uw_source = early_unwrap(source);
+ if (
+ uw_source instanceof BinaryOp &&
+ uw_source.op === "+" &&
+ uw_source.right instanceof Literal &&
+ imm instanceof Literal &&
+ (pymod(uw_source.right.value, 0x10000) === 0 || (arm && pymod(imm.value, 0x100) === 0))
+ ) {
+ return add_imm(output_reg, uw_source.left, new Literal(imm.value + uw_source.right.value), args);
+ }
+ return handle_addi_real(output_reg, source_reg, source, imm, args);
+}
+
+export function handle_sub_arm(args) {
+ const stack_info = args.stack_info;
+ const output_reg = args.reg_ref(0);
+ const source_reg = args.reg_ref(1);
+ const lhs = args.reg(1);
+ const rhs = args.reg_or_imm(2);
+ if (rhs instanceof Literal && stack_info.is_stack_reg(source_reg) && stack_info.is_stack_reg(output_reg)) return lhs;
+ return handle_sub(lhs, rhs);
+}
+
+export function handle_sub(lhs, rhs) {
+ if (lhs instanceof Literal && rhs instanceof Literal) return s32_literal(lhs.value - rhs.value);
+ if (pyeq(rhs, new Literal(0))) return lhs;
+ return fold_mul_chains(fold_divmod(BinaryOp.intptr(lhs, "-", rhs)));
+}
+
+export function handle_addis(args) {
+ const source_reg = args.reg_ref(1);
+ const source = args.reg(1);
+ const imm = args.shifted_u16_imm(2);
+ return handle_addi_real(args.reg_ref(0), source_reg, source, imm, args);
+}
+
+export function handle_addi_real(output_reg, source_reg, source, imm, args) {
+ const stack_info = args.stack_info;
+ if (source_reg !== null && stack_info.is_stack_reg(source_reg)) {
+ pyassert(imm instanceof Literal);
+ if (stack_info.is_stack_reg(output_reg)) return source;
+ const v = stack_info.get_stack_var(imm.value, { store: false });
+ if (v instanceof LocalVar) stack_info.add_local_var(v);
+ return new AddressOf(v, { type: v.type.reference() });
+ }
+ return add_imm(output_reg, source, imm, args);
+}
+
+export function add_imm(output_reg, source, imm, args) {
+ const stack_info = args.stack_info;
+ if (pyeq(imm, new Literal(0))) return source;
+ else if (source.type.is_pointer_or_array()) {
+ const dest_var = stack_info.get_planned_var(output_reg, args.instruction_ref);
+ const arch = stack_info.global_info.arch;
+ const inplace = dest_var !== null && var_for_expr(source) === dest_var;
+ if (imm instanceof Literal && !arch.is_likely_partial_offset(imm.value) && !inplace) {
+ const array_access = array_access_from_add(source, imm.value, stack_info, { target_size: null, ptr: true });
+ if (array_access !== null) return array_access;
+ const [field_path, field_type] = source.type.get_deref_field(imm.value, { target_size: null });
+ if (field_path !== null) {
+ return new AddressOf(new StructAccess({ struct_var: source, offset: imm.value, target_size: null, field_path, stack_info, type: field_type }), { type: field_type.reference() });
+ }
+ }
+ if (imm instanceof Literal) {
+ const target = source.type.get_pointer_target();
+ if (target) {
+ const target_size = target.get_size_bytes();
+ if (target_size && pymod(imm.value, target_size) === 0) return new BinaryOp({ left: source, op: "+", right: as_intish(imm), type: source.type });
+ }
+ }
+ return new BinaryOp({ left: source, op: "+", right: as_intish(imm), type: Type.ptr() });
+ } else if (source instanceof Literal && imm instanceof Literal) {
+ return new Literal(source.value + imm.value);
+ }
+ return BinaryOp.intptr(source, "+", imm);
+}
+
+export function handle_load(args, type) {
+ const size = type.get_size_bytes();
+ pyassert(size !== null);
+ const output_reg = args.reg_ref(0);
+ const expr = deref(args.memory_ref(1), args.regs, args.stack_info, { size });
+
+ const load_rodata_constant = () => {
+ if (!(expr instanceof StructAccess)) return null;
+ const arch = args.stack_info.global_info.arch.arch;
+ const is_arm = arch === Target.ArchEnum.ARM;
+ const is_sh = arch === Target.ArchEnum.SH;
+ if (is_arm && args.raw_arg(1) instanceof AsmAddressMode) return null;
+ if (!is_arm && !is_sh && (!type.is_likely_float() || expr.offset !== 0)) return null;
+ const target = early_unwrap(expr.struct_var);
+ if (!(target instanceof AddressOf) || !(target.expr instanceof GlobalSymbol)) return null;
+ const ent = target.expr.asm_data_entry;
+ if (ent === null || !ent.is_readonly) return null;
+ const data = ent.data_at_offset(expr.offset, size);
+ if (data === null) return null;
+ if (data instanceof Uint8Array && [2, 4, 8].includes(size)) {
+ ent.used_as_literal = true;
+ const big = args.stack_info.global_info.target.is_big_endian();
+ let v = 0n;
+ const bs = big ? [...data] : [...data].reverse();
+ for (const b of bs) v = (v << 8n) | BigInt(b);
+ // Values beyond 2**53 stay BigInt (see normint) so 64-bit patterns keep every bit.
+ let val = normint(v);
+ if (type.is_signed() && (v >> BigInt(size * 8 - 1)) & 1n) val = normint(v - (1n << BigInt(size * 8)));
+ return new Literal({ value: val, type });
+ }
+ if ((is_arm || is_sh) && ent.is_text && data instanceof AsmSymbolicData) {
+ let sym = data.data;
+ let addend = 0;
+ if (sym instanceof BinOp && (sym.op === "+" || sym.op === "-") && sym.rhs instanceof AsmLiteral) {
+ addend = sym.rhs.value * (sym.op === "-" ? -1 : 1);
+ sym = sym.lhs;
+ }
+ if (sym instanceof AsmGlobalSymbol) {
+ ent.used_as_literal = true;
+ let addr = args.stack_info.global_info.address_of_gsym(sym.symbol_name);
+ addr = add_imm(output_reg, addr, new Literal(addend), args);
+ return as_type(addr, type, true);
+ }
+ }
+ return null;
+ };
+
+ const c = load_rodata_constant();
+ if (c !== null) return c;
+ return as_type(expr, type, true);
+}
+
+export function deref_unaligned(arg, regs, stack_info, { store = false } = {}) {
+ return deref(arg, regs, stack_info, { size: 1, store });
+}
+
+export function handle_lwl(args) {
+ const ref = args.memory_ref(1);
+ const expr = deref_unaligned(ref, args.regs, args.stack_info);
+ let key;
+ if (ref instanceof AddressMode) key = [ref.offset, args.regs.get(ref.base)];
+ else key = [ref.offset, ref.sym];
+ return new Lwl(expr, key);
+}
+
+export function handle_lwr(args) {
+ const uw_old_value = early_unwrap(args.reg(0));
+ const ref = args.memory_ref(1);
+ const big = args.stack_info.global_info.target.is_big_endian();
+ const delta = big ? -3 : 3;
+ let lwl_key;
+ if (ref instanceof AddressMode) lwl_key = [ref.offset + delta, args.regs.get(ref.base)];
+ else lwl_key = [ref.offset + delta, ref.sym];
+ if (uw_old_value instanceof Lwl && uw_old_value.key[0] === lwl_key[0]) {
+ let load_expr;
+ if (big) load_expr = uw_old_value.load_expr;
+ else load_expr = deref_unaligned(ref, args.regs, args.stack_info);
+ return new UnalignedLoad(load_expr);
+ }
+ if (pymod(ref.offset, 4) === 2 && big) {
+ const left_mem_ref = dcreplace(ref, { offset: ref.offset - 2 });
+ const load_expr = deref_unaligned(left_mem_ref, args.regs, args.stack_info);
+ return new Load3Bytes(load_expr);
+ }
+ return new ErrorExpr("Unable to handle lwr; missing a corresponding lwl");
+}
+
+export function make_store(args, type) {
+ const size = type.get_size_bytes();
+ pyassert(size !== null);
+ const stack_info = args.stack_info;
+ const source_reg = args.reg_ref(0);
+ const source_raw = args.regs.get_raw(source_reg);
+ let source_val;
+ if (type.is_likely_float() && size === 8) source_val = args.dreg(0);
+ else source_val = args.reg(0);
+ const target = args.memory_ref(1);
+ return make_store_real(source_val, source_raw, target, args.regs, stack_info, type);
+}
+
+export function make_store_real(source_val, source_raw, target, regs, stack_info, type) {
+ const size = type.get_size_bytes();
+ pyassert(size !== null);
+ const is_stack = target instanceof AddressMode && stack_info.is_stack_reg(target.base);
+ if (is_stack && source_raw !== null && stack_info.should_save(source_raw, target.offset)) return null;
+ const dest = deref(target, regs, stack_info, { size, store: true });
+ dest.type.unify(type);
+ return new StoreStmt({ source: as_type(source_val, type, is_stack), dest });
+}
+
+export function make_storex(args, type) {
+ const size = type.get_size_bytes();
+ pyassert(size !== null);
+ const source = args.reg(0);
+ const ptr = BinaryOp.intptr(args.reg(1), "+", args.reg(2));
+ const dest = deref(ptr, args.regs, args.stack_info, { size, store: true });
+ dest.type.unify(type);
+ return new StoreStmt({ source: as_type(source, type, false), dest });
+}
+
+export function handle_swl(args) {
+ let source = args.reg(0);
+ let target = args.memory_ref(1);
+ if (!(early_unwrap(source) instanceof UnalignedLoad)) source = new UnalignedLoad(source);
+ if (!args.stack_info.global_info.target.is_big_endian()) target = dcreplace(target, { offset: target.offset - 3 });
+ const dest = deref_unaligned(target, args.regs, args.stack_info, { store: true });
+ return new StoreStmt({ source, dest });
+}
+
+export function handle_swr(args) {
+ const expr = early_unwrap(args.reg(0));
+ const target = args.memory_ref(1);
+ if (!(expr instanceof Load3Bytes)) return null;
+ const real_target = dcreplace(target, { offset: target.offset - 2 });
+ const dest = deref_unaligned(real_target, args.regs, args.stack_info, { store: true });
+ return new StoreStmt({ source: expr, dest });
+}
+
+export function handle_shift_right(args, { signed, arm = false }) {
+ const lhs = args.reg(1);
+ const shift = arm ? args.reg_or_imm(2) : args.s16_imm(2);
+ if (shift instanceof Literal && (shift.value === 16 || shift.value === 24)) {
+ const expr = early_unwrap(lhs);
+ const pow2 = shl(1, shift.value);
+ if (expr instanceof BinaryOp && expr.right instanceof Literal) {
+ let tp;
+ if (signed) tp = shift.value === 16 ? Type.s16() : Type.s8();
+ else tp = shift.value === 16 ? Type.u16() : Type.u8();
+ const rhs = expr.right.value;
+ if (expr.op === "<<" && rhs === shift.value) return as_type(expr.left, tp, false);
+ else if (expr.op === "<<" && rhs > shift.value) {
+ const new_shift = fold_mul_chains(BinaryOp.int(expr.left, "<<", new Literal(rhs - shift.value)));
+ return as_type(new_shift, tp, false);
+ } else if (expr.op === "*" && pymod(rhs, pow2) === 0 && rhs !== pow2) {
+ const mul = BinaryOp.int(expr.left, "*", new Literal({ value: floordiv(rhs, pow2) }));
+ return as_type(mul, tp, false);
+ }
+ }
+ }
+ if (signed) return fold_divmod(BinaryOp.sshift(lhs, ">>", shift));
+ return BinaryOp.ushift(lhs, ">>", shift);
+}
+
+export function handle_sll(args, { arm = false } = {}) {
+ const lhs = args.reg(1);
+ const rhs = arm ? args.reg_or_imm(2) : args.s16_imm(2);
+ if (lhs instanceof Literal && rhs instanceof Literal) return new Literal(shl(lhs.value, rhs.value));
+ return fold_mul_chains(BinaryOp.int(lhs, "<<", as_intish(rhs)));
+}
+
+export function handle_conditional_move(args, nonzero) {
+ const op = nonzero ? "!=" : "==";
+ const val = args.reg(2);
+ const type = Type.any_reg();
+ return new TernaryOp(BinaryOp.icmp(val, op, new Literal(0, { type: val.type })), as_type(args.reg(1), type, true), as_type(args.reg(0), type, true), type);
+}
+
+/** Return a new BinaryOp instance if this one can be simplified to a single / or % op. */
+export function fold_divmod(original_expr) {
+ const mult_high_ops = ["MULT_HI", "MULTU_HI"];
+ const possible_match_ops = [...mult_high_ops, "-", "+", ">>"];
+ if (original_expr.is_floating() || !possible_match_ops.includes(original_expr.op)) return original_expr;
+
+ let expr = original_expr;
+ let left_expr = early_unwrap_ints(expr.left);
+ let right_expr = early_unwrap_ints(expr.right);
+ let divisor_shift = 0;
+
+ if (left_expr instanceof Literal && !(right_expr instanceof Literal)) [left_expr, right_expr] = [right_expr, left_expr];
+
+ if (left_expr instanceof BinaryOp && left_expr.op === ">>" && left_expr.right instanceof Literal && expr.op === "+" && right_expr instanceof CarryBit) {
+ const new_denom = shl(1, left_expr.right.value);
+ return BinaryOp.sint(left_expr.left, "/", new Literal(new_denom), { silent: true });
+ }
+
+ if (left_expr instanceof BinaryOp && left_expr.op === "/" && left_expr.right instanceof Literal && expr.op === ">>" && right_expr instanceof Literal) {
+ const new_denom = shl(left_expr.right.value, right_expr.value);
+ if (new_denom < 2 ** 32) return BinaryOp.int(left_expr.left, "/", new Literal(new_denom));
+ }
+
+ if (expr.op === "-" && right_expr instanceof BinaryOp && right_expr.op === "*") {
+ const div_expr = early_unwrap_ints(right_expr.left);
+ const mod_base = early_unwrap_ints(right_expr.right);
+ if (div_expr instanceof BinaryOp && pyeq(early_unwrap_ints(div_expr.left), left_expr)) {
+ const divisor = early_unwrap_ints(div_expr.right);
+ if (
+ (div_expr.op === "/" && pyeq(divisor, mod_base)) ||
+ (div_expr.op === ">>" && divisor instanceof Literal && mod_base instanceof Literal && shl(1, divisor.value) === mod_base.value)
+ ) {
+ return BinaryOp.int(left_expr, "%", right_expr.right);
+ }
+ }
+ }
+
+ if (
+ expr.op === "-" &&
+ left_expr instanceof BinaryOp &&
+ left_expr.op === ">>" &&
+ pyeq(early_unwrap_ints(left_expr.right), new Literal(31)) &&
+ right_expr instanceof BinaryOp &&
+ right_expr.op === "/" &&
+ right_expr.right instanceof Literal
+ ) {
+ [left_expr, right_expr] = [dcreplace(right_expr, { right: new Literal(-right_expr.right.value) }), left_expr];
+ }
+
+ if (
+ expr.op === "+" &&
+ left_expr instanceof BinaryOp &&
+ left_expr.op === "/" &&
+ left_expr.right instanceof Literal &&
+ left_expr.right.value <= 2 ** 29 &&
+ right_expr instanceof BinaryOp &&
+ pyeq(early_unwrap_ints(right_expr.left), left_expr) &&
+ right_expr.op === ">>" &&
+ pyeq(early_unwrap_ints(right_expr.right), new Literal(31))
+ ) {
+ return left_expr;
+ }
+
+ if (
+ expr.op === "-" &&
+ left_expr instanceof BinaryOp &&
+ left_expr.op === "/" &&
+ left_expr.right instanceof Literal &&
+ right_expr instanceof BinaryOp &&
+ right_expr.op === ">>" &&
+ pyeq(early_unwrap_ints(right_expr.right), new Literal(31))
+ ) {
+ const div_expr = left_expr;
+ const shift_var_expr = early_unwrap_ints(right_expr.left);
+ const div_var_expr = early_unwrap_ints(div_expr.left);
+ if (pyeq(div_var_expr, shift_var_expr)) {
+ if (div_expr.right instanceof Literal && div_expr.right.value >= 2 ** 30) return BinaryOp.int(div_expr.left, div_expr.op, div_expr.right);
+ return div_expr;
+ }
+ if (
+ shift_var_expr instanceof BinaryOp &&
+ pyeq(early_unwrap_ints(div_expr.left), early_unwrap_ints(shift_var_expr.left)) &&
+ shift_var_expr.op === "<<" &&
+ shift_var_expr.right instanceof Literal
+ ) {
+ return div_expr;
+ }
+ }
+
+ if (left_expr instanceof BinaryOp && expr.op === ">>" && right_expr instanceof Literal) {
+ divisor_shift += right_expr.value;
+ expr = left_expr;
+ left_expr = early_unwrap_ints(expr.left);
+ right_expr = early_unwrap_ints(expr.right);
+ if (
+ left_expr instanceof BinaryOp &&
+ left_expr.op === "MULT_HI" &&
+ expr.op === "+" &&
+ (pyeq(right_expr, early_unwrap_ints(left_expr.left)) || pyeq(right_expr, early_unwrap_ints(left_expr.right)))
+ ) {
+ expr = left_expr;
+ left_expr = early_unwrap_ints(expr.left);
+ right_expr = early_unwrap_ints(expr.right);
+ }
+ if (left_expr instanceof Literal && !(right_expr instanceof Literal)) [left_expr, right_expr] = [right_expr, left_expr];
+ }
+
+ if (mult_high_ops.includes(expr.op) && left_expr instanceof BinaryOp && left_expr.op === ">>" && left_expr.right instanceof Literal) {
+ divisor_shift += left_expr.right.value;
+ left_expr = early_unwrap_ints(left_expr.left);
+ }
+
+ const round_div = (x, y) => {
+ if (y <= 1) return null;
+ const result = pyround(x / y);
+ if (x / (y + 1) <= result && result <= x / (y - 1)) return result;
+ return null;
+ };
+
+ if (mult_high_ops.includes(expr.op) && right_expr instanceof Literal) {
+ const denom = round_div(2 ** (32 + divisor_shift), right_expr.value);
+ if (denom !== null) return BinaryOp.int(left_expr, "/", new Literal(denom));
+ }
+ return original_expr;
+}
+
+/** Simplify an expression matching `CLZ(x) >> 5` into `x == 0`. */
+export function replace_clz_shift(expr) {
+ if (expr.is_floating() || expr.op !== ">>") return expr;
+ const left_expr = early_unwrap_ints(expr.left);
+ const right_expr = early_unwrap_ints(expr.right);
+ if (!(left_expr instanceof UnaryOp && left_expr.op === "CLZ" && right_expr instanceof Literal && right_expr.value === 5)) return expr;
+ const sub_expr = early_unwrap(left_expr.expr);
+ if (sub_expr instanceof BinaryOp && !sub_expr.is_floating() && sub_expr.op === "-") return BinaryOp.icmp(sub_expr.right, "==", sub_expr.left);
+ return BinaryOp.icmp(left_expr.expr, "==", new Literal(0, { type: left_expr.expr.type }));
+}
+
+/** Simplify expressions using `&`. */
+export function replace_bitand(expr) {
+ if (!expr.is_floating() && expr.op === "&") {
+ if (pyeq(expr.right, new Literal(0))) return new Literal(0);
+ if (pyeq(expr.right, new Literal(0xff))) return as_type(expr.left, Type.u8(), false);
+ if (pyeq(expr.right, new Literal(0xffff))) return as_type(expr.left, Type.u16(), false);
+ }
+ return expr;
+}
+
+/** Simplify an expression involving +, -, * and << to a single multiplication. */
+export function fold_mul_chains(expr, { allow_sll_chains = false } = {}) {
+ const fold = (expr, toplevel, allow_sll) => {
+ if (expr instanceof BinaryOp) {
+ if ((expr.op === "<<" || expr.op === "*") && expr.right instanceof Literal) {
+ const [lbase, lnum] = fold(expr.left, false, expr.op !== "<<");
+ const rhs = expr.right.value;
+ if (expr.op === "<<" && (allow_sll || allow_sll_chains)) {
+ if (toplevel && lnum === 1 && !(1 <= rhs && rhs <= 4)) return [expr, 1];
+ return [lbase, shl(lnum, rhs)];
+ }
+ if (expr.op === "*" && (allow_sll || allow_sll_chains || pymod(rhs, 2) !== 0)) return [lbase, lnum * rhs];
+ }
+ if ((expr.op === "+" || expr.op === "-") && toplevel) {
+ const [lbase, lnum] = fold(expr.left, false, expr.op !== "<<");
+ const [rbase, rnum] = fold(expr.right, false, expr.op !== "<<");
+ if (pyeq(early_unwrap(lbase), early_unwrap(rbase))) {
+ if (expr.op === "+") return [lbase, lnum + rnum];
+ if (expr.op === "-") return [lbase, lnum - rnum];
+ }
+ }
+ }
+ if (expr instanceof UnaryOp && expr.op === "-" && !toplevel) {
+ const [base, num] = fold(expr.expr, false, true);
+ return [base, -num];
+ }
+ const uw_expr = early_unwrap(expr);
+ if (uw_expr !== expr) {
+ const [base, num] = fold(uw_expr, false, allow_sll);
+ if (num !== 1) return [base, num];
+ }
+ return [expr, 1];
+ };
+
+ const [base, num] = fold(expr, true, true);
+ if (num === 1) return expr;
+ if (allow_sll_chains && num > 16 && band(num, num - 1) === 0) return BinaryOp.int(base, "<<", new Literal(bit_length(num) - 1));
+ return BinaryOp.int(base, "*", new Literal(num));
+}
+
+export function fold_shift_right(expr, shift, { signed }) {
+ const inner = early_unwrap_ints(expr);
+ if (inner instanceof BinaryOp && inner.op === ">>" && inner.type.is_signed() === signed && inner.right instanceof Literal && inner.right.value + shift < 32) {
+ expr = inner.left;
+ shift += inner.right.value;
+ }
+ let ret;
+ if (signed) ret = BinaryOp.sshift(expr, ">>", new Literal(shift));
+ else ret = BinaryOp.ushift(expr, ">>", new Literal(shift));
+ return fold_divmod(ret);
+}
+
+/** Given `expr` of the form `a + (imm * b + Y)` and an `offset` X, try to create `a->unk(X + Y)[b]`. */
+export function array_access_from_add(expr, offset, stack_info, { target_size, ptr }) {
+ expr = early_unwrap(expr);
+ if (!(expr instanceof BinaryOp) || expr.op !== "+") return null;
+ let base = expr.left;
+ let addend = expr.right;
+ if (addend.type.is_pointer_or_array() && !base.type.is_pointer_or_array()) [base, addend] = [addend, base];
+
+ if (addend instanceof Literal) return null;
+
+ let uw_addend = early_unwrap(addend);
+ if (uw_addend instanceof BinaryOp && uw_addend.op === "+") {
+ if (uw_addend.right instanceof Literal) {
+ offset += uw_addend.right.value;
+ addend = uw_addend.left;
+ } else if (uw_addend.left instanceof Literal) {
+ offset += uw_addend.left.value;
+ addend = uw_addend.right;
+ }
+ }
+
+ let index = addend;
+ let scale = 1;
+ uw_addend = early_unwrap(addend);
+ if (uw_addend instanceof BinaryOp && (uw_addend.op === "*" || uw_addend.op === "<<") && uw_addend.right instanceof Literal) {
+ index = uw_addend.left;
+ scale = uw_addend.right.value;
+ if (uw_addend.op === "<<") scale = shl(1, scale);
+ }
+
+ if (scale < 0) {
+ scale = -scale;
+ index = UnaryOp.sint("-", index);
+ }
+
+ let target_type = base.type.get_pointer_target();
+ if (target_type === null) return null;
+
+ const uw_base = early_unwrap(base);
+ const typepool = stack_info.global_info.typepool;
+
+ if (scale > 1 && offset === 0 && uw_base instanceof AddressOf && target_type.get_size_bytes() === null) {
+ let inner_type = null;
+ if (uw_base.expr instanceof GlobalSymbol && uw_base.expr.potential_array_dim(scale)[1] !== 0) {
+ // pass
+ } else if (scale === 2) inner_type = Type.int_of_size(16);
+ else if (scale === 4) inner_type = Type.reg32({ likely_float: false });
+ else if (typepool.unk_inference && uw_base.expr instanceof GlobalSymbol) {
+ const struct_name = `_struct_${uw_base.expr.c_symbol_name}_0x${format(scale, "X")}`;
+ let struct = typepool.get_struct_by_tag_name(struct_name, stack_info.global_info.typemap);
+ if (struct === null) struct = StructDeclaration.unknown(typepool, scale, struct_name);
+ else if (struct.size !== scale) throw new DecompFailure(`sizeof(struct ${struct_name}) != ${format(scale, "#x")}`);
+ inner_type = Type.struct(struct);
+ }
+ if (inner_type !== null) {
+ uw_base.expr.type.unify(Type.array(inner_type, null));
+ target_type.unify(inner_type);
+ }
+ }
+
+ if (target_type.get_size_bytes() === scale) {
+ // base[index]
+ } else {
+ const [sub_path, sub_type, remaining_offset] = base.type.get_deref_field(offset, { target_size: scale, exact: false });
+ if (sub_path === null || sub_path.length < 2 || sub_path[sub_path.length - 1] !== 0) return null;
+ sub_path.pop();
+ base = new StructAccess({ struct_var: base, offset: offset - remaining_offset, target_size: null, field_path: sub_path, stack_info, type: sub_type });
+ offset = remaining_offset;
+ target_type = sub_type;
+ }
+
+ let ret = new ArrayAccess(base, index, { type: target_type });
+ const ret_ref = new AddressOf(ret, { type: ret.type.reference() });
+ const [field_path, field_type] = ret_ref.type.get_deref_field(offset, { target_size });
+ if (offset !== 0 || (target_size !== null && target_size !== scale)) {
+ ret = new StructAccess({ struct_var: ret_ref, offset, target_size, field_path, stack_info, type: field_type });
+ }
+ if (ptr) ret = new AddressOf(ret, { type: ret.type.reference() });
+ return ret;
+}
+
+export function handle_add(args) {
+ const output_reg = args.reg_ref(0);
+ const lhs = args.reg(1);
+ const rhs = args.reg(2);
+ if (rhs instanceof Literal) return fold_mul_chains(handle_addi_real(output_reg, args.reg_ref(1), lhs, rhs, args));
+ if (lhs instanceof Literal) return fold_mul_chains(handle_addi_real(output_reg, args.reg_ref(2), rhs, lhs, args));
+ return handle_add_real(lhs, rhs, args);
+}
+
+export function handle_add_arm(args) {
+ if (args.raw_arg(2) instanceof Register) return handle_add(args);
+ return handle_addi(args.reg_ref(0), args.reg_ref(1), args.reg(1), args.full_imm(2), args);
+}
+
+export function handle_add_real(lhs, rhs, args) {
+ const stack_info = args.stack_info;
+ if (pyeq(lhs, new Literal(0))) return rhs;
+ if (pyeq(rhs, new Literal(0))) return lhs;
+ let type = Type.intptr();
+ if (lhs.type.is_pointer_or_array()) type = Type.ptr();
+ else if (rhs.type.is_pointer_or_array()) type = Type.ptr();
+ const expr = new BinaryOp({ left: as_intptr(lhs), op: "+", right: as_intptr(rhs), type });
+ let folded_expr = fold_mul_chains(expr);
+ if (folded_expr instanceof BinaryOp) folded_expr = fold_divmod(folded_expr);
+ if (folded_expr !== expr) return folded_expr;
+ const array_expr = array_access_from_add(expr, 0, stack_info, { target_size: null, ptr: true });
+ if (array_expr !== null) return array_expr;
+ return expr;
+}
+
+export function handle_add_float(args) {
+ if (args.reg_ref(1) === args.reg_ref(2)) {
+ const two = new Literal(1 << 30, { type: Type.f32() });
+ return BinaryOp.f32(two, "*", args.reg(1));
+ }
+ return BinaryOp.f32(args.reg(1), "+", args.reg(2));
+}
+
+export function handle_add_double(args) {
+ if (args.reg_ref(1) === args.reg_ref(2)) {
+ const two = new Literal(2 ** 62, { type: Type.f64() });
+ return BinaryOp.f64(two, "*", args.dreg(1));
+ }
+ return BinaryOp.f64(args.dreg(1), "+", args.dreg(2));
+}
+
+export function fold_shift_bgez(expr) {
+ const uw_expr = early_unwrap(expr);
+ if (!(uw_expr instanceof BinaryOp) || !(uw_expr.right instanceof Literal)) return null;
+ const value = uw_expr.right.value;
+ let shift;
+ if (uw_expr.op === "<<") shift = value;
+ else if (uw_expr.op === "*" && value > 0 && band(value, value - 1) === 0) shift = bit_length(value) - 1;
+ else return null;
+ const bitand = BinaryOp.int(uw_expr.left, "&", new Literal(shl(1, 31 - shift)));
+ return new UnaryOp("!", bitand, { type: Type.boolean() });
+}
+
+export function handle_bgez(args) {
+ const expr = args.reg(0);
+ return fold_shift_bgez(expr) || BinaryOp.scmp(expr, ">=", new Literal(0));
+}
+
+export function rlwi_mask(mask_begin, mask_end) {
+ const bits_upto = (m) => shl(1, 32 - m) - 1;
+ const all_ones = 0xffffffff;
+ let mask;
+ if (mask_begin <= mask_end) mask = bits_upto(mask_begin) - bits_upto(mask_end + 1);
+ else mask = bxor(bits_upto(mask_end + 1) - bits_upto(mask_begin), all_ones);
+ return mask;
+}
+
+export function handle_rlwinm(source, shift, mask_begin, mask_end, simplify = true) {
+ const all_ones = 0xffffffff;
+ const mask = rlwi_mask(mask_begin, mask_end);
+ const left_shift = shift;
+ const right_shift = 32 - shift;
+ const left_mask = band(shl(all_ones, left_shift), mask);
+ const right_mask = band(shr(all_ones, right_shift), mask);
+
+ simplify = simplify && !(left_mask && right_mask);
+
+ if (source instanceof Literal) {
+ const upper_value = band(shl(source.value, left_shift), mask);
+ const lower_value = band(shr(source.value, right_shift), mask);
+ return new Literal(bor(upper_value, lower_value));
+ }
+
+ let upper_bits;
+ if (left_mask === 0) upper_bits = null;
+ else {
+ upper_bits = source;
+ if (left_shift !== 0) upper_bits = BinaryOp.int(upper_bits, "<<", new Literal(left_shift));
+ if (simplify) upper_bits = fold_mul_chains(upper_bits);
+ if (left_mask !== band(shl(all_ones, left_shift), all_ones)) {
+ upper_bits = BinaryOp.int(upper_bits, "&", new Literal(left_mask));
+ if (simplify) upper_bits = replace_bitand(upper_bits);
+ }
+ }
+
+ let lower_bits;
+ if (right_mask === 0) lower_bits = null;
+ else {
+ lower_bits = BinaryOp.uint(source, ">>", new Literal(right_shift));
+ if (simplify) lower_bits = replace_clz_shift(fold_divmod(lower_bits));
+ if (right_mask !== band(shr(all_ones, right_shift), all_ones)) {
+ lower_bits = BinaryOp.int(lower_bits, "&", new Literal(right_mask));
+ if (simplify) lower_bits = replace_bitand(lower_bits);
+ }
+ }
+
+ if (upper_bits === null && lower_bits === null) return new Literal(0);
+ else if (upper_bits === null) {
+ pyassert(lower_bits !== null);
+ return lower_bits;
+ } else if (lower_bits === null) return upper_bits;
+ return BinaryOp.int(upper_bits, "|", lower_bits);
+}
+
+export function handle_rlwimi(base, source, shift, mask_begin, mask_end) {
+ const mask_literal = new Literal(rlwi_mask(mask_begin, mask_end));
+ const mask = new UnaryOp("~", mask_literal, { type: Type.u32() });
+ const masked_base = BinaryOp.int(base, "&", mask);
+ if (pyeq(source, new Literal(0))) return masked_base;
+ const inserted = handle_rlwinm(source, shift, mask_begin, mask_end, false);
+ if (pyeq(inserted, mask_literal)) return BinaryOp.int(base, "|", inserted);
+ return BinaryOp.int(masked_base, "|", inserted);
+}
+
+export function handle_rlwnm(source, shift_source, mask_begin, mask_end) {
+ const mask = rlwi_mask(mask_begin, mask_end);
+ const shift = BinaryOp.int(shift_source, "&", new Literal(0x1f));
+ const upper_bits = BinaryOp.int(BinaryOp.int(source, "<<", shift), "&", new Literal(mask));
+ const lower_bits = BinaryOp.int(BinaryOp.int(source, ">>", BinaryOp.int(new Literal(32), "-", shift)), "&", new Literal(mask));
+ return BinaryOp.int(upper_bits, "|", lower_bits);
+}
+
+export function handle_cmpnez(source) {
+ let uw_source = early_unwrap(source);
+ if (uw_source instanceof UnaryOp && uw_source.op === "-") {
+ source = uw_source.expr;
+ uw_source = early_unwrap(source);
+ }
+ if (uw_source instanceof BinaryOp && (uw_source.op === "-" || uw_source.op === "^")) return BinaryOp.icmp(uw_source.right, "!=", uw_source.left);
+ return BinaryOp.icmp(source, "!=", new Literal(0));
+}
+
+export function handle_loadx(args, type) {
+ const size = type.get_size_bytes();
+ pyassert(size !== null);
+ const ptr = BinaryOp.intptr(args.reg(1), "+", args.reg(2));
+ const expr = deref(ptr, args.regs, args.stack_info, { size });
+ return as_type(expr, type, true);
+}
+
+export function handle_arm_mov(args) {
+ const dest = args.reg_ref(0);
+ const source = args.raw_arg(1);
+ const value = args.reg_or_imm(1);
+ if (source instanceof Register && args.stack_info.is_stack_reg(source) && !args.stack_info.is_stack_reg(dest)) return handle_addi_real(dest, source, value, new Literal(0), args);
+ return value;
+}
+
+export function eval_arm_cmp(s, lhs, rhs) {
+ s.set_reg(new Register("z"), BinaryOp.icmp(lhs, "==", rhs));
+ const sub = BinaryOp.intptr(lhs, "-", rhs);
+ const sval = as_type(sub, Type.s32(), true, { unify: false });
+ s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0)));
+ const v = fn_op("M2C_OVERFLOW", [sval], Type.boolean());
+ s.set_reg(new Register("v"), v);
+ const ulhs = as_type(lhs, Type.u32(), true, { unify: false });
+ const slhs = as_type(lhs, Type.s32(), true, { unify: false });
+ const urhs = as_type(rhs, Type.u32(), true, { unify: false });
+ const srhs = as_type(rhs, Type.s32(), true, { unify: false });
+ s.set_reg(new Register("c"), BinaryOp.ucmp(ulhs, ">=", urhs));
+ s.set_reg(new Register("hi"), BinaryOp.ucmp(ulhs, ">", urhs));
+ s.set_reg(new Register("ge"), BinaryOp.scmp(slhs, ">=", srhs));
+ s.set_reg(new Register("gt"), BinaryOp.scmp(slhs, ">", srhs));
+}
+
+export function set_arm_flags_from_add(s, val) {
+ s.set_reg(new Register("z"), BinaryOp.icmp(val, "==", new Literal(0, { type: val.type })));
+ const sval = as_type(val, Type.s32(), true, { unify: false });
+ s.set_reg(new Register("n"), BinaryOp.scmp(sval, "<", new Literal(0)));
+ s.set_reg(new Register("c"), new CarryBit(val));
+ const v = fn_op("M2C_OVERFLOW", [sval], Type.boolean());
+ s.set_reg(new Register("v"), v);
+ const u64val = as_type(val, Type.u64(), false, { unify: false });
+ const p32 = new Literal(2 ** 32);
+ s.set_reg(new Register("hi"), BinaryOp.ucmp(u64val, ">", p32));
+ const s64val = as_type(val, Type.s64(), false, { unify: false });
+ s.set_reg(new Register("ge"), BinaryOp.scmp(s64val, ">=", new Literal(0)));
+ s.set_reg(new Register("gt"), BinaryOp.scmp(s64val, ">", new Literal(0)));
+}
+
+export function carry_add_to(expr) {
+ return fold_divmod(BinaryOp.intptr(expr, "+", new CarryBit()));
+}
+
+export function carry_sub_from(expr) {
+ return BinaryOp.intptr(expr, "-", new UnaryOp("!", new CarryBit(), { type: Type.intish() }));
+}
+
+export function s32_literal(value) {
+ return new Literal(band(value + 0x80000000, 0xffffffff) - 0x80000000);
+}
+
+export { ArrayAccess };
diff --git a/packages/romdev-m2c/src/flow_graph.js b/packages/romdev-m2c/src/flow_graph.js
new file mode 100644
index 00000000..0b593a31
--- /dev/null
+++ b/packages/romdev-m2c/src/flow_graph.js
@@ -0,0 +1,1267 @@
+// Port of m2c/flow_graph.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { DecompFailure } from "./error.js";
+import { Target } from "./options.js";
+import { AsmSymbolicData, Function, Label } from "./asm_file.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, JumpTarget, Macro, Register } from "./asm_instruction.js";
+import { ArchAsm, Instruction } from "./instruction.js";
+import { simplify_patterns } from "./asm_pattern.js";
+import { DefaultMap, ValueError, intern, pyassert, lstrip, sorted, compare, shallowcopy } from "./py.js";
+import { print } from "./io.js";
+
+export class ArchFlowGraph extends ArchAsm {
+ process_flowgraph(asm_data, flow_graph) {}
+ simplify_ir(asm_data, flow_graph, { debug_patterns }) {}
+}
+
+ArchFlowGraph.prototype.asm_patterns = [];
+
+/** Reference acts as a pointer to either a specific Instruction, or one of the function's bounds */
+export class Reference {}
+
+/** Reference to a Location's value before the start of a function (e.g. constants, args) */
+export class PrologueRef extends Reference {
+ constructor(location) {
+ super();
+ this.location = location;
+ return intern(this, [location]);
+ }
+}
+
+/** Reference to return values of a function */
+export class EpilogueRef extends Reference {
+ constructor(location) {
+ super();
+ this.location = location;
+ return intern(this, [location]);
+ }
+}
+
+/** Pointer to an Instruction as part of a Block. */
+export class InstrRef extends Reference {
+ constructor(instruction, block) {
+ super();
+ this.instruction = instruction;
+ this.block = block;
+ }
+ /** Add `asm` into the parent assembly before this instruction. */
+ add_instruction_before(asm, arch) {
+ const instr = arch.parse(asm.mnemonic, asm.args, this.instruction.meta.derived());
+ const ref = new InstrRef(instr, this.block);
+ const index = this.block.instruction_refs.indexOf(this);
+ if (index < 0) throw new ValueError("x not in list");
+ this.block.instruction_refs.splice(index, 0, ref);
+ return ref;
+ }
+ /** Replace the existing instruction with `new_asm`. */
+ replace_instruction(new_asm, arch) {
+ const old_instr = this.instruction;
+ const new_instr = arch.parse(new_asm.mnemonic, new_asm.args, old_instr.meta.derived());
+ for (const loc of [...old_instr.outputs, ...old_instr.clobbers]) {
+ if (!new_instr.clobbers.includes(loc)) new_instr.clobbers.push(loc);
+ }
+ this.instruction = new_instr;
+ }
+}
+
+export class Block {
+ constructor(index, label, approx_label_name, instruction_refs = [], is_safeguard = false, block_info = null) {
+ this.index = index;
+ this.label = label;
+ this.approx_label_name = approx_label_name;
+ this.instruction_refs = instruction_refs;
+ this.is_safeguard = is_safeguard;
+ // block_info is actually an Optional[BlockInfo], set by translate.js
+ this.block_info = block_info;
+ }
+ get instructions() {
+ return this.instruction_refs.map((r) => r.instruction);
+ }
+ add_block_info(block_info) {
+ pyassert(this.block_info === null);
+ this.block_info = block_info;
+ }
+ clone() {
+ const ret = shallowcopy(this);
+ ret.instruction_refs = this.instruction_refs.map((ref) => new InstrRef(ref.instruction.clone(), ret));
+ return ret;
+ }
+ toString() {
+ const name = `${this.index} (${this.approx_label_name})`;
+ const inst_str = this.instructions.map((instr) => " " + String(instr)).join("\n");
+ return `# ${name}\n${inst_str}\n`;
+ }
+}
+
+export class BlockBuilder {
+ constructor() {
+ this._curr_index = 0;
+ this._curr_label = null;
+ this._last_label_name = "initial";
+ this._label_counter = 0;
+ this._curr_instructions = [];
+ this._blocks = [];
+ }
+ new_block() {
+ if (this._curr_instructions.length === 0) return null;
+ let label_name = this._last_label_name;
+ if (this._label_counter > 0) label_name += `.${this._label_counter}`;
+ const block = new Block(this._curr_index, this._curr_label, label_name);
+ for (const i of this._curr_instructions) block.instruction_refs.push(new InstrRef(i, block));
+ this._blocks.push(block);
+ this._curr_index += 1;
+ this._curr_label = null;
+ this._label_counter += 1;
+ this._curr_instructions = [];
+ return block;
+ }
+ add_instruction(instruction) {
+ this._curr_instructions.push(instruction);
+ }
+ set_label(label) {
+ pyassert(!this._curr_label, "Cannot have two labels in a row ({label} vs {self._curr_label})");
+ this._curr_label = label;
+ this._last_label_name = label.names[0];
+ this._label_counter = 0;
+ }
+ is_empty() {
+ return !this._blocks.length && !this._curr_instructions.length;
+ }
+ get_blocks() {
+ return this._blocks;
+ }
+}
+
+function verify_no_trailing_delay_slot(fn) {
+ let last_ins = null;
+ for (const item of fn.body) if (item instanceof Instruction) last_ins = item;
+ if (last_ins && last_ins.has_delay_slot) throw new DecompFailure(`Last instruction is missing a delay slot:\n${last_ins}`);
+}
+
+export function invert_mips_branch_mnemonic(mnemonic) {
+ const inverses = { beq: "bne", bne: "beq", beqz: "bnez", bnez: "beqz", bgez: "bltz", bgtz: "blez", blez: "bgtz", bltz: "bgez", bc1t: "bc1f", bc1f: "bc1t" };
+ if (!Object.prototype.hasOwnProperty.call(inverses, mnemonic)) throw new Error(`KeyError: '${mnemonic}'`);
+ return inverses[mnemonic];
+}
+
+export function internal_label(base, related = "") {
+ // (upstream computes `rel` but does not use it)
+ void (related ? lstrip(related, ".") + "_" : "");
+ return `._m2c_${related}${base}`;
+}
+
+function normalize_gcc_likely_branches(fn, arch) {
+ const new_function = fn.bodyless_copy();
+ const new_body = new_function.body;
+ fn.body.forEach((item, i) => {
+ if (item instanceof Instruction && item.is_branch_likely && item.jump_target instanceof JumpTarget && i + 2 < fn.body.length) {
+ const ins = fn.body[i + 1];
+ const label = fn.body[i + 2];
+ if (ins instanceof Instruction && label instanceof Label && label.names.includes(item.jump_target.target)) {
+ const mn_inverted = invert_mips_branch_mnemonic(item.mnemonic.slice(0, -1));
+ new_body.push(arch.parse(mn_inverted, item.args, item.meta.derived()));
+ new_body.push(arch.parse("nop", [], item.meta.derived()));
+ return;
+ }
+ }
+ new_body.push(item);
+ });
+ return new_function;
+}
+
+function iterOf(arr) {
+ const it = arr[Symbol.iterator]();
+ return {
+ next_or_throw() {
+ const r = it.next();
+ if (r.done) throw new Error("StopIteration");
+ return r.value;
+ },
+ *[Symbol.iterator]() {
+ for (;;) {
+ const r = it.next();
+ if (r.done) return;
+ yield r.value;
+ }
+ },
+ };
+}
+
+function normalize_ido_likely_branches(fn, asm_data, arch) {
+ const seen_instrs = new Set();
+ const label_names = new Map();
+ const label_prev_instr = new Map();
+ const label_before_instr = new Map();
+ const instr_before_instr = new Map();
+ let prev_instr = null;
+ let prev_label = null;
+ let prev_item = null;
+ for (const item of fn.body) {
+ if (item instanceof Instruction) {
+ pyassert(!seen_instrs.has(item));
+ seen_instrs.add(item);
+ if (prev_label !== null) {
+ label_before_instr.set(item, prev_label.names[0]);
+ prev_label = null;
+ }
+ if (prev_item instanceof Instruction) instr_before_instr.set(item, prev_item);
+ prev_instr = item;
+ } else if (item instanceof Label) {
+ for (const name of item.names) {
+ label_prev_instr.set(name, prev_instr);
+ label_names.set(name, new Set(item.names));
+ }
+ prev_label = item;
+ prev_instr = null;
+ }
+ prev_item = item;
+ }
+
+ const untouched_targets = new Set();
+ const addAll = (set, other) => {
+ for (const x of other ?? []) set.add(x);
+ };
+
+ const may_transform_branch = (item, next_item, before_target, pre = false) => {
+ if (!item.has_delay_slot) return false;
+ if (before_target === next_item) return false;
+ if (String(before_target) !== String(next_item)) return false;
+ const next_mn = next_item.mnemonic;
+ if (!item.is_branch_likely && next_mn === "nop") return false;
+ if (arch.arch === Target.ArchEnum.SH) {
+ pyassert(item.jump_target instanceof JumpTarget);
+ const label = item.jump_target.target;
+ if (!(next_mn.startsWith("cmp/") || next_mn === "tst")) return false;
+ if (untouched_targets.has(label) && !pre) return false;
+ } else {
+ if (!item.is_branch_likely && item.mnemonic !== "b") return false;
+ }
+ if (!item.is_conditional) {
+ const before_before_target = instr_before_instr.get(before_target) ?? null;
+ if (before_before_target !== null && before_before_target.has_delay_slot) return false;
+ }
+ return true;
+ };
+
+ if (arch.arch === Target.ArchEnum.SH) {
+ for (const label of asm_data.mentioned_labels) addAll(untouched_targets, label_names.get(label));
+ for (let i = 0; i + 1 < fn.body.length; i++) {
+ const item = fn.body[i];
+ const next_item = fn.body[i + 1];
+ if (!(item instanceof Instruction)) continue;
+ if (Array.isArray(item.jump_target)) {
+ for (const target of item.jump_target) addAll(untouched_targets, label_names.get(target.target));
+ } else if (item.jump_target instanceof JumpTarget) {
+ const before_target = label_prev_instr.get(item.jump_target.target) ?? null;
+ if (next_item instanceof Instruction && before_target !== null && may_transform_branch(item, next_item, before_target, true)) continue;
+ addAll(untouched_targets, label_names.get(item.jump_target.target));
+ }
+ }
+ }
+
+ const insert_label_before = new Map();
+ const new_body = [];
+ const body_iter = iterOf(fn.body);
+ for (const item of body_iter) {
+ if (!(item instanceof Instruction) || !(item.jump_target instanceof JumpTarget)) {
+ new_body.push([item, item]);
+ continue;
+ }
+ const next_item = body_iter.next_or_throw();
+ const before_target = label_prev_instr.get(item.jump_target.target) ?? null;
+ if (next_item instanceof Instruction && before_target !== null && may_transform_branch(item, next_item, before_target)) {
+ if (!label_before_instr.has(before_target)) {
+ const new_label = internal_label("before", item.jump_target.target);
+ label_before_instr.set(before_target, new_label);
+ insert_label_before.set(before_target, new_label);
+ }
+ const new_target = label_before_instr.get(before_target);
+ const mn = item.mnemonic;
+ const mn_unlikely = item.is_branch_likely ? mn.slice(0, -1) : mn;
+ const new_item = arch.parse(mn_unlikely, [...item.args.slice(0, -1), new AsmGlobalSymbol(new_target)], item.meta.derived());
+ let new_next_item;
+ if (item.is_conditional && !item.is_branch_likely) new_next_item = next_item;
+ else new_next_item = arch.parse("nop", [], new_item.meta.derived());
+ new_body.push([item, new_item]);
+ new_body.push([next_item, new_next_item]);
+ } else {
+ new_body.push([item, item]);
+ new_body.push([next_item, next_item]);
+ }
+ }
+
+ const new_function = fn.bodyless_copy();
+ for (const [orig_item, new_item] of new_body) {
+ if (orig_item instanceof Instruction && insert_label_before.has(orig_item)) new_function.new_label(insert_label_before.get(orig_item));
+ new_function.body.push(new_item);
+ }
+ return new_function;
+}
+
+function minimize_labels(fn, asm_data) {
+ const labels_used = new Set();
+ for (const label of fn.body) if (label instanceof Label) for (const name of label.names) if (asm_data.mentioned_labels.has(name)) labels_used.add(name);
+ for (const item of fn.body) {
+ if (item instanceof Instruction) {
+ if (item.jump_target instanceof JumpTarget) labels_used.add(item.jump_target.target);
+ if (item.function_target instanceof AsmGlobalSymbol) labels_used.add(item.function_target.symbol_name);
+ }
+ }
+ const new_function = fn.bodyless_copy();
+ let cur_label = [];
+ for (const item of fn.body) {
+ if (item instanceof Label) cur_label.push(...item.names.filter((name) => labels_used.has(name)));
+ else {
+ if (cur_label.length) {
+ new_function.body.push(new Label(cur_label));
+ cur_label = [];
+ }
+ new_function.body.push(item);
+ }
+ }
+ if (cur_label.length) new_function.body.push(new Label(cur_label));
+ return new_function;
+}
+
+function simplify_standard_patterns(fn, asm_data, arch, debug_patterns) {
+ const new_body = simplify_patterns(fn.body, arch.asm_patterns, asm_data, arch, { debug_patterns });
+ const new_function = fn.bodyless_copy();
+ new_function.body.push(...new_body);
+ return new_function;
+}
+
+function build_blocks(fn, asm_data, arch, { fragment, debug_patterns }) {
+ if (!fragment) {
+ if (arch.has_delay_slots) {
+ verify_no_trailing_delay_slot(fn);
+ fn = minimize_labels(fn, asm_data);
+ if (arch.arch === Target.ArchEnum.MIPS) fn = normalize_gcc_likely_branches(fn, arch);
+ fn = normalize_ido_likely_branches(fn, asm_data, arch);
+ }
+ fn = minimize_labels(fn, asm_data);
+ fn = simplify_standard_patterns(fn, asm_data, arch, debug_patterns);
+ fn = minimize_labels(fn, asm_data);
+ }
+
+ const block_builder = new BlockBuilder();
+ const body_iter = iterOf(fn.body);
+ const branch_likely_counts = new Map();
+ let cond_return_target = null;
+
+ const process_delay_slots = (item) => {
+ if (item instanceof Label) {
+ block_builder.new_block();
+ block_builder.set_label(item);
+ return;
+ }
+ if (!item.has_delay_slot) {
+ process_no_delay_slots(item);
+ return;
+ }
+ const process_after = [];
+ let next_item = body_iter.next_or_throw();
+
+ if (next_item instanceof Label) {
+ const label = next_item;
+ next_item = body_iter.next_or_throw();
+ pyassert(next_item instanceof Instruction, "Cannot have two labels in a row");
+ if (item.is_branch_likely || item.function_target !== null) {
+ let msg = [
+ `Label ${label} refers to a delay slot; this is currently not supported.`,
+ "Please modify the assembly to work around it (e.g. copy the instruction",
+ "to all jump sources and move the label, or add a nop to the delay slot).",
+ ];
+ if (label.names[0].includes("_before")) {
+ msg = msg.concat([
+ "",
+ "This label was auto-generated as the target for a branch-likely",
+ "instruction (e.g. beql); you can also try to turn that into a non-likely",
+ "branch if that's equivalent in this context, i.e., if it's okay to",
+ "execute its delay slot unconditionally.",
+ ]);
+ }
+ throw new DecompFailure(msg.join("\n"));
+ } else if (next_item.outputs.every((x) => !next_item.inputs.includes(x)) && !next_item.is_store) {
+ process_after.push(label);
+ process_after.push(next_item.clone());
+ } else {
+ pyassert(item.jump_target instanceof JumpTarget, "has delay slot and isn't a call");
+ const target = item.jump_target.target;
+ const temp_label = internal_label("skip", label.names[0]);
+ const meta = item.meta.derived();
+ const nop = arch.parse("nop", [], meta);
+ block_builder.add_instruction(arch.parse(item.mnemonic, [...item.args.slice(0, -1), new AsmGlobalSymbol(temp_label)], item.meta));
+ block_builder.add_instruction(nop);
+ block_builder.new_block();
+ block_builder.add_instruction(arch.parse("b", [new AsmGlobalSymbol(label.names[0])], item.meta.derived()));
+ block_builder.add_instruction(nop.clone());
+ block_builder.new_block();
+ block_builder.set_label(Label.new(temp_label));
+ block_builder.add_instruction(arch.parse("b", [new AsmGlobalSymbol(target)], item.meta.derived()));
+ block_builder.add_instruction(next_item.clone());
+ block_builder.new_block();
+ block_builder.set_label(label);
+ block_builder.add_instruction(next_item);
+ return;
+ }
+ }
+
+ if (next_item.has_delay_slot) throw new DecompFailure(`Two delay slot instructions in a row is not supported:\n${item}\n${next_item}`);
+
+ if (item.is_branch_likely) {
+ pyassert(item.jump_target instanceof JumpTarget);
+ const target = item.jump_target.target;
+ branch_likely_counts.set(target, (branch_likely_counts.get(target) ?? 0) + 1);
+ const index = branch_likely_counts.get(target);
+ const mn_inverted = invert_mips_branch_mnemonic(item.mnemonic.slice(0, -1));
+ const temp_label = internal_label(`branchlikelyskip_${index}`, target);
+ const branch_not = arch.parse(mn_inverted, [...item.args.slice(0, -1), new AsmGlobalSymbol(temp_label)], item.meta.derived());
+ const nop = arch.parse("nop", [], item.meta.derived());
+ block_builder.add_instruction(branch_not);
+ block_builder.add_instruction(nop);
+ block_builder.new_block();
+ block_builder.add_instruction(next_item);
+ block_builder.add_instruction(arch.parse("b", [new AsmGlobalSymbol(target)], item.meta.derived()));
+ block_builder.add_instruction(nop.clone());
+ block_builder.new_block();
+ block_builder.set_label(Label.new(temp_label));
+ block_builder.add_instruction(nop.clone());
+ } else if (item.function_target !== null) {
+ if (item.args.length >= 2 && (next_item.outputs.includes(item.args[1]) || next_item.clobbers.includes(item.args[1]))) {
+ throw new DecompFailure(`Instruction after ${item.mnemonic} clobbers its source\n` + "register, which is currently not supported.\n\n" + "Try rewriting the assembly to avoid that.");
+ }
+ block_builder.add_instruction(next_item);
+ block_builder.add_instruction(item);
+ } else {
+ block_builder.add_instruction(item);
+ block_builder.add_instruction(next_item);
+ }
+
+ if (item.is_jump()) block_builder.new_block();
+
+ for (const it of process_after) process_delay_slots(it);
+ };
+
+ const process_no_delay_slots = (item) => {
+ if (item instanceof Label) {
+ block_builder.new_block();
+ block_builder.set_label(item);
+ return;
+ }
+ if (item.is_conditional && Array.isArray(item.jump_target)) {
+ for (let i = 0; i < item.jump_target.length; i++) {
+ if (item.jump_target[i] === new JumpTarget("_m2c_ret")) {
+ if (cond_return_target === null) cond_return_target = internal_label("conditionalreturn");
+ item.jump_target[i] = new JumpTarget(cond_return_target);
+ }
+ }
+ }
+ if (item.is_conditional && item.is_return) {
+ if (cond_return_target === null) cond_return_target = internal_label("conditionalreturn");
+ pyassert(item.mnemonic.slice(-2) === "lr");
+ const branch_instr = arch.parse(item.mnemonic.slice(0, -2), [new AsmGlobalSymbol(cond_return_target)], item.meta.derived());
+ block_builder.add_instruction(branch_instr);
+ block_builder.new_block();
+ return;
+ }
+ block_builder.add_instruction(item);
+ if (item.is_jump()) block_builder.new_block();
+ };
+
+ if (arch.has_delay_slots && !fragment) {
+ for (const item of body_iter) process_delay_slots(item);
+ } else {
+ for (const item of body_iter) process_no_delay_slots(item);
+ }
+
+ if (block_builder.is_empty()) throw new DecompFailure(`Function ${fn.name} contains no instructions. Maybe it is rodata?`);
+
+ if (fragment) {
+ block_builder.new_block();
+ return block_builder.get_blocks();
+ }
+
+ for (const instr of arch.missing_return()) block_builder.add_instruction(instr);
+ const emitted_block = block_builder.new_block();
+ pyassert(emitted_block !== null);
+ emitted_block.is_safeguard = true;
+
+ if (cond_return_target !== null) {
+ block_builder.set_label(Label.new(cond_return_target));
+ for (const instr of arch.missing_return()) block_builder.add_instruction(instr);
+ block_builder.new_block();
+ }
+ return block_builder.get_blocks();
+}
+
+function verify_no_duplicate_instructions(blocks) {
+ const seen = new Set();
+ for (const block of blocks) {
+ for (const instr of block.instructions) {
+ pyassert(!seen.has(instr), "Instructions must be clone()ed if emitted twice");
+ seen.add(instr);
+ }
+ }
+}
+
+export class BaseNode {
+ constructor(block, emit_goto) {
+ this.block = block;
+ this.emit_goto = emit_goto;
+ this.parents = [];
+ this.dominators = new Set();
+ this.immediate_dominator = null;
+ this.immediately_dominates = [];
+ this.postdominators = new Set();
+ this.immediate_postdominator = null;
+ this.immediately_postdominates = [];
+ // This is only populated on the head node of the loop
+ this.loop = null;
+ }
+ name() {
+ return String(this.block.index);
+ }
+ children() {
+ throw new Error("abstract");
+ }
+ __repr__() {
+ return `<${this.constructor.name}: ${this.name()}>`;
+ }
+}
+
+export class BasicNode extends BaseNode {
+ constructor(block, emit_goto, successor, fake_successor = null) {
+ super(block, emit_goto);
+ this.successor = successor;
+ // Optional link to the TerminalNode, used to make infinite loops reducible.
+ this.fake_successor = fake_successor;
+ }
+ children() {
+ if (this.fake_successor !== null) return [this.successor, this.fake_successor];
+ return [this.successor];
+ }
+ toString() {
+ return [`${this.block}\n`, `# ${this.name()} -> ${this.successor.name()}`, this.loop ? " (loop)" : "", this.emit_goto ? " (goto)" : ""].join("");
+ }
+}
+
+export class ConditionalNode extends BaseNode {
+ constructor(block, emit_goto, conditional_edge, fallthrough_edge) {
+ super(block, emit_goto);
+ this.conditional_edge = conditional_edge;
+ this.fallthrough_edge = fallthrough_edge;
+ }
+ children() {
+ if (this.conditional_edge === this.fallthrough_edge) return [this.conditional_edge];
+ return [this.conditional_edge, this.fallthrough_edge];
+ }
+ toString() {
+ return [
+ `${this.block}\n`,
+ `# ${this.name()} -> `,
+ `cond: ${this.conditional_edge.name()}`,
+ this.loop ? " (loop)" : "",
+ ", ",
+ `def: ${this.fallthrough_edge.name()}`,
+ this.emit_goto ? " (goto)" : "",
+ ].join("");
+ }
+}
+
+export class ReturnNode extends BaseNode {
+ constructor(block, emit_goto, index, terminal) {
+ super(block, emit_goto);
+ this.index = index;
+ this.terminal = terminal;
+ }
+ children() {
+ return [this.terminal];
+ }
+ name() {
+ const name = super.name();
+ return this.is_real() ? name : `${name}.${this.index}`;
+ }
+ is_real() {
+ return this.index === 0;
+ }
+ toString() {
+ return [`${this.block}\n`, `# ${this.name()} -> ret`, this.emit_goto ? " (goto)" : ""].join("");
+ }
+}
+
+export class SwitchNode extends BaseNode {
+ constructor(block, emit_goto, cases) {
+ super(block, emit_goto);
+ this.cases = cases;
+ }
+ children() {
+ const seen = new Set();
+ const children = [];
+ for (const node of this.cases) {
+ if (!seen.has(node)) {
+ seen.add(node);
+ children.push(node);
+ }
+ }
+ return children;
+ }
+ toString() {
+ const targets = this.cases.map((c) => c.name()).join(", ");
+ return `${this.block}\n# ${this.name()} -> ${targets}`;
+ }
+}
+
+/** A fictive node that acts as a common postdominator for every node in the flowgraph. */
+export class TerminalNode extends BaseNode {
+ static terminal() {
+ return new TerminalNode(new Block(-1, null, "", []), false);
+ }
+ children() {
+ return [];
+ }
+ toString() {
+ return "return";
+ }
+}
+
+export class NaturalLoop {
+ constructor(head, nodes = new Set(), backedges = new Set()) {
+ this.head = head;
+ this.nodes = nodes;
+ this.backedges = backedges;
+ }
+}
+
+export function get_literal_pool_symbolic_data(arg, asm_data) {
+ let offset = 0;
+ if (arg instanceof BinOp && arg.op === "+" && arg.rhs instanceof AsmLiteral) {
+ offset = arg.rhs.value;
+ arg = arg.lhs;
+ }
+ if (!(arg instanceof AsmGlobalSymbol)) return null;
+ const ent = asm_data.values.get(arg.symbol_name) ?? null;
+ if (ent === null || !ent.is_text) return null;
+ const data = ent.data_at_offset(offset, 4);
+ if (!(data instanceof AsmSymbolicData)) return null;
+ return data;
+}
+
+export function get_literal_pool_symbol(arg, asm_data) {
+ const data = get_literal_pool_symbolic_data(arg, asm_data);
+ if (data === null) return null;
+ return data.as_symbol_without_addend();
+}
+
+export function arm_jtbl_for_ldr(arg, asm_data) {
+ const jtbl_name = get_literal_pool_symbol(arg, asm_data);
+ if (jtbl_name === null) return null;
+ const ent = asm_data.values.get(jtbl_name) ?? null;
+ if (ent === null || !ent.is_text || !ent.data.length || !(ent.data[0] instanceof AsmSymbolicData) || ent.data[0].as_symbol_without_addend() === null) return null;
+ return jtbl_name;
+}
+
+function build_graph_from_block(block, blocks, parent_blocks, nodes, asm_data, arch) {
+ for (const node of nodes) if (node.block === block) return node;
+
+ let new_node;
+ const dummy_node = null;
+ const terminal_node = nodes[0];
+ pyassert(terminal_node instanceof TerminalNode, "expected first node to be TerminalNode");
+
+ const find_block_by_label = (label) => {
+ for (const b of blocks) if (b.label && b.label.names.includes(label)) return b;
+ return null;
+ };
+ const blockAt = (i) => {
+ if (i >= blocks.length) throw new Error("IndexError: list index out of range");
+ return blocks[i];
+ };
+
+ const jumps = block.instructions.filter((inst) => inst.is_jump());
+ pyassert(jumps.length === 0 || jumps.length === 1, "too many jump instructions in one block");
+
+ if (jumps.length === 0) {
+ new_node = new BasicNode(block, false, dummy_node);
+ nodes.push(new_node);
+ const next_block = blockAt(block.index + 1);
+ new_node.successor = build_graph_from_block(next_block, blocks, [...parent_blocks, block], nodes, asm_data, arch);
+ } else if (jumps.length === 1) {
+ const jump = jumps[0];
+
+ if (jump.is_return) {
+ new_node = new ReturnNode(block, false, 0, terminal_node);
+ nodes.push(new_node);
+ return new_node;
+ }
+
+ if (jump.jump_target instanceof Register) {
+ new_node = new SwitchNode(block, false, []);
+ nodes.push(new_node);
+
+ const jtbl_names = new Set();
+ for (const jtbl_block of [block, ...[...parent_blocks].reverse()]) {
+ for (const ins of jtbl_block.instructions) {
+ for (let arg of ins.args) {
+ if (arg instanceof AsmAddressMode) arg = arg.addend;
+ if (
+ arg instanceof Macro &&
+ (arg.macro_name === "lo" || arg.macro_name === "l") &&
+ arg.argument instanceof AsmGlobalSymbol &&
+ ["jtbl", "jpt_", "lbl_", "jumptable_"].some((prefix) => arg.argument.symbol_name.startsWith(prefix))
+ ) {
+ jtbl_names.add(arg.argument.symbol_name);
+ }
+ if (ins.arch_mnemonic(arch) === "arm:ldr") {
+ const jtbl_name = arm_jtbl_for_ldr(arg, asm_data);
+ if (jtbl_name !== null) jtbl_names.add(jtbl_name);
+ }
+ }
+ }
+ if (jtbl_names.size) break;
+ }
+ if (jtbl_names.size > 1) {
+ throw new DecompFailure(
+ `Unable to determine jump table for ${jump.mnemonic} instruction ${jump.meta.loc_str()}.\n\n` +
+ `Found multiple candidates: ${sorted(jtbl_names).join(", ")}\n` +
+ "You can help m2c's analysis by putting a copy of the jump table\n" +
+ "setup instructions within the same block as the jump instruction.",
+ );
+ }
+ if (!jtbl_names.size) {
+ let help_text = "";
+ if (arch.arch !== Target.ArchEnum.ARM) {
+ help_text = "\n\nThere must be a read of a variable before the instruction\n" + 'which has a name starting with with "jtbl"/"jpt_"/"lbl_"/"jumptable_".';
+ }
+ throw new DecompFailure(`Unable to determine jump table for ${jump.mnemonic} instruction ${jump.meta.loc_str()}.${help_text}`);
+ }
+
+ const jtbl_name = [...jtbl_names][0];
+ if (!asm_data.values.has(jtbl_name)) {
+ throw new DecompFailure(
+ `Found ${jump.mnemonic} instruction ${jump.meta.loc_str()}, but the ` +
+ "corresponding jump table is not provided.\n" +
+ "\n" +
+ "Please include it in the input .s file(s), or in an additional file.\n",
+ );
+ }
+ const jtbl_value = asm_data.values.get(jtbl_name);
+ jtbl_value.is_jtbl = true;
+ for (const entry of jtbl_value.data) {
+ if (entry instanceof Uint8Array) break;
+ const sym = entry.as_symbol_without_addend();
+ if (sym === null) break;
+ const case_block = find_block_by_label(sym);
+ if (case_block === null) throw new DecompFailure(`Cannot find jtbl target ${sym}`);
+ const case_node = build_graph_from_block(case_block, blocks, [...parent_blocks, block], nodes, asm_data, arch);
+ new_node.cases.push(case_node);
+ }
+ return new_node;
+ }
+
+ if (Array.isArray(jump.jump_target)) {
+ new_node = new SwitchNode(block, false, []);
+ nodes.push(new_node);
+ for (const jump_target of jump.jump_target) {
+ const case_block = find_block_by_label(jump_target.target);
+ if (case_block === null) throw new DecompFailure(`Cannot find jtbl target ${jump_target}`);
+ const case_node = build_graph_from_block(case_block, blocks, [...parent_blocks, block], nodes, asm_data, arch);
+ new_node.cases.push(case_node);
+ }
+ return new_node;
+ }
+
+ const branch_label = jump.jump_target;
+ pyassert(branch_label instanceof JumpTarget);
+ const branch_block = find_block_by_label(branch_label.target);
+ if (branch_block === null) throw new DecompFailure(`Cannot find branch target ${branch_label.target}`);
+
+ const emit_goto = jump.meta.emit_goto;
+ if (!jump.is_conditional) {
+ new_node = new BasicNode(block, emit_goto, dummy_node);
+ nodes.push(new_node);
+ new_node.successor = build_graph_from_block(branch_block, blocks, [...parent_blocks, block], nodes, asm_data, arch);
+ } else {
+ new_node = new ConditionalNode(block, emit_goto, dummy_node, dummy_node);
+ nodes.push(new_node);
+ const next_block = blockAt(block.index + 1);
+ new_node.conditional_edge = build_graph_from_block(branch_block, blocks, [...parent_blocks, block], nodes, asm_data, arch);
+ new_node.fallthrough_edge = build_graph_from_block(next_block, blocks, [...parent_blocks, block], nodes, asm_data, arch);
+ }
+ }
+ return new_node;
+}
+
+function is_trivial_return_block(block, arch) {
+ for (const instr of block.instructions) {
+ if (instr.is_store || instr.function_target !== null) return false;
+ if ([...instr.inputs, ...instr.outputs].some((reg) => arch.all_return_regs.includes(reg))) return false;
+ }
+ return true;
+}
+
+/** Return the set of nodes that can reach `end` with `without` removed. */
+function inv_reachable_without(end, without) {
+ const reachable = new Set();
+ const stack = [end];
+ while (stack.length) {
+ const node = stack.pop();
+ if (node === without || reachable.has(node)) continue;
+ reachable.add(node);
+ stack.push(...node.parents);
+ }
+ return reachable;
+}
+
+function build_nodes(fn, blocks, asm_data, arch, { fragment }) {
+ const terminal_node = TerminalNode.terminal();
+ const graph = [terminal_node];
+ if (fragment) blocks.push(terminal_node.block);
+ const entry_block = blocks[0];
+ build_graph_from_block(entry_block, blocks, [], graph, asm_data, arch);
+ const terms = graph.filter((n) => n instanceof TerminalNode);
+ pyassert(terms.length === 1 && terms[0] === terminal_node);
+ terminal_node.block.index = Math.max(...graph.map((n) => n.block.index)) + 1;
+ graph.sort((a, b) => a.block.index - b.block.index);
+ return graph;
+}
+
+function warn_on_safeguard_use(fn, nodes, arch) {
+ const node = nodes.find((n) => n.block.is_safeguard) ?? null;
+ if (node) {
+ const label = node.block.approx_label_name;
+ const return_instrs = arch.missing_return();
+ print(`Warning: missing "${return_instrs[0]}" in last block of ${fn.name} (${label}).\n`);
+ }
+}
+
+/** Check whether a given edge in the flow graph is an early return. */
+function is_premature_return(node, edge, nodes, arch) {
+ if (nodes.length < 3) return false;
+ const [antepenultimate_node, final_return_node, terminal_node] = nodes.slice(-3);
+ pyassert(terminal_node instanceof TerminalNode);
+ if (!(edge instanceof ReturnNode) || edge !== final_return_node) return false;
+ if (!is_trivial_return_block(edge.block, arch)) return false;
+ if (!(node instanceof BasicNode)) return false;
+ return node !== antepenultimate_node;
+}
+
+/** For each jump to an early return node, create a duplicate return node for it to jump to. */
+function duplicate_premature_returns(nodes, arch) {
+ const extra_nodes = [];
+ let index = 0;
+ for (const node of nodes) {
+ if (node instanceof BasicNode && !node.emit_goto && is_premature_return(node, node.successor, nodes, arch)) {
+ pyassert(node.successor instanceof ReturnNode);
+ index += 1;
+ const n = new ReturnNode(node.successor.block.clone(), false, index, node.successor.terminal);
+ node.successor = n;
+ extra_nodes.push(n);
+ }
+ }
+ nodes.push(...extra_nodes);
+ nodes.sort((a, b) => a.block.index - b.block.index);
+
+ const queue = [nodes[0]];
+ const reachable_nodes = new Set(nodes.filter((n) => n instanceof TerminalNode));
+ while (queue.length) {
+ const node = queue.pop();
+ reachable_nodes.add(node);
+ for (const c of node.children()) if (!reachable_nodes.has(c) && !queue.includes(c)) queue.push(c);
+ }
+ return nodes.filter((n) => reachable_nodes.has(n));
+}
+
+/** Compute dominators, postdominators, and backedges for the set of nodes. */
+export function compute_relations(nodes) {
+ for (const node of nodes) node.parents = [];
+ for (const node of nodes) for (const child of node.children()) child.parents.push(node);
+
+ const nnodes = nodes.length;
+ const index_of = new Map(nodes.map((n, i) => [n, i]));
+ const words = Math.ceil(nnodes / 32) || 1;
+
+ const compute_dominators = (entry, parents, dominators, immediately_dominates, set_immediate_dominator) => {
+ // Bitsets as Uint32Array words (Python uses big ints).
+ const doms = new Map();
+ nodes.forEach((n, i) => {
+ const bs = new Uint32Array(words);
+ if (n === entry) bs[i >>> 5] |= 1 << (i & 31);
+ else {
+ for (let w = 0; w < words; w++) bs[w] = 0xffffffff;
+ const extra = words * 32 - nnodes;
+ if (extra > 0) bs[words - 1] = 0xffffffff >>> extra;
+ }
+ doms.set(n, bs);
+ });
+ let changes = true;
+ while (changes) {
+ changes = false;
+ nodes.forEach((node, i) => {
+ if (node === entry) return;
+ const nset = Uint32Array.from(doms.get(node));
+ for (const parent of parents(node)) {
+ const p = doms.get(parent);
+ for (let w = 0; w < words; w++) nset[w] &= p[w];
+ }
+ nset[i >>> 5] |= 1 << (i & 31);
+ const cur = doms.get(node);
+ let differ = false;
+ for (let w = 0; w < words; w++) if (nset[w] !== cur[w]) differ = true;
+ if (differ) {
+ for (let w = 0; w < words; w++) pyassert((nset[w] & cur[w]) >>> 0 === nset[w] >>> 0);
+ doms.set(node, nset);
+ changes = true;
+ }
+ });
+ }
+ for (const n of nodes) {
+ const bitset = doms.get(n);
+ const nodeset = dominators(n);
+ nodeset.clear();
+ for (let i = 0; i < nnodes; i++) if (bitset[i >>> 5] & (1 << (i & 31))) nodeset.add(nodes[i]);
+ }
+ for (const node of nodes) immediately_dominates(node).length = 0;
+ for (const node of nodes) {
+ const ds = [...dominators(node)].filter((d) => d !== node);
+ if (ds.length) {
+ let imdom = null;
+ let best = null;
+ for (const d of ds) {
+ const key = [dominators(d).size, d.block.index];
+ if (best === null || compare(key, best) > 0) {
+ best = key;
+ imdom = d;
+ }
+ }
+ immediately_dominates(imdom).push(node);
+ set_immediate_dominator(node, imdom);
+ } else set_immediate_dominator(node, null);
+ }
+ for (const node of nodes) immediately_dominates(node).sort((x, y) => x.block.index - y.block.index);
+ };
+ void index_of;
+
+ const entry = nodes[0];
+ const terminal = nodes[nodes.length - 1];
+ pyassert(terminal instanceof TerminalNode);
+
+ compute_dominators(
+ entry,
+ (n) => n.parents,
+ (n) => n.dominators,
+ (n) => n.immediately_dominates,
+ (node, imdom) => {
+ node.immediate_dominator = imdom;
+ },
+ );
+ compute_dominators(
+ terminal,
+ (n) => n.children(),
+ (n) => n.postdominators,
+ (n) => n.immediately_postdominates,
+ (node, impdom) => {
+ node.immediate_postdominator = impdom;
+ },
+ );
+
+ for (const node of nodes) {
+ for (const child of node.children()) {
+ if (!node.dominators.has(child)) continue;
+ if (child.loop === null) child.loop = new NaturalLoop(child);
+ child.loop.nodes.add(child);
+ child.loop.nodes.add(node);
+ child.loop.backedges.add(node);
+ for (const parent of inv_reachable_without(node, child)) child.loop.nodes.add(parent);
+ }
+ }
+}
+
+function reachable_backwards(start) {
+ const seen = new Set();
+ const queue = [start];
+ while (queue.length) {
+ const n = queue.pop();
+ seen.add(n);
+ for (const p of n.parents) if (!seen.has(p) && !queue.includes(p)) queue.push(p);
+ }
+ return seen;
+}
+
+function terminate_infinite_loops(nodes) {
+ const terminal_node = nodes[nodes.length - 1];
+ pyassert(terminal_node instanceof TerminalNode);
+ for (;;) {
+ const seen = reachable_backwards(terminal_node);
+ const unterminated_nodes = nodes.filter((node) => !seen.has(node) && node instanceof BasicNode);
+ if (!unterminated_nodes.length) return;
+ unterminated_nodes[unterminated_nodes.length - 1].fake_successor = terminal_node;
+ compute_relations(nodes);
+ }
+}
+
+/** A set of References, backed by a list to avoid non-determinism */
+export class RefSet {
+ constructor(refs = []) {
+ this.refs = refs;
+ }
+ static empty() {
+ return new RefSet([]);
+ }
+ is_empty() {
+ return this.refs.length === 0;
+ }
+ get length() {
+ return this.refs.length;
+ }
+ get_unique() {
+ if (this.refs.length === 1) return this.refs[0];
+ return null;
+ }
+ add(ref) {
+ if (!this.refs.includes(ref)) this.refs.push(ref);
+ }
+ update(other) {
+ for (const ref of other.refs) this.add(ref);
+ }
+ remove(ref) {
+ const i = this.refs.indexOf(ref);
+ if (i < 0) throw new ValueError("list.remove(x): x not in list");
+ this.refs.splice(i, 1);
+ }
+ copy() {
+ return new RefSet([...this.refs]);
+ }
+ has(ref) {
+ return this.refs.includes(ref);
+ }
+ [Symbol.iterator]() {
+ return this.refs[Symbol.iterator]();
+ }
+ equals(other) {
+ return this.refs.length === other.refs.length && this.refs.every((x) => other.has(x));
+ }
+}
+
+/** A map from Locations to RefSets. A missing key is equivalent to an empty RefSet. */
+export class LocationRefSetDict {
+ constructor(refs = new Map()) {
+ this.refs = refs;
+ }
+ get(loc) {
+ return this.refs.get(loc) ?? RefSet.empty();
+ }
+ add(loc, ref) {
+ if (!this.has(loc)) this.refs.set(loc, new RefSet([ref]));
+ else this.refs.get(loc).add(ref);
+ }
+ remove(loc) {
+ this.refs.delete(loc);
+ }
+ copy() {
+ return new LocationRefSetDict(new Map(this.refs));
+ }
+ items() {
+ return [...this.refs.entries()];
+ }
+ is_empty() {
+ for (const v of this.refs.values()) if (v.refs.length) return false;
+ return true;
+ }
+ /** Python __contains__: the location maps to a non-empty RefSet */
+ has(key) {
+ return this.get(key).refs.length > 0;
+ }
+ set(key, value) {
+ this.refs.set(key, value);
+ }
+}
+
+export class FlowGraph {
+ constructor(nodes) {
+ this.nodes = nodes;
+ this.instr_inputs = new DefaultMap(() => new LocationRefSetDict());
+ this.instr_uses = new DefaultMap(() => new LocationRefSetDict());
+ }
+ entry_node() {
+ return this.nodes[0];
+ }
+ terminal_node() {
+ const node = this.nodes[this.nodes.length - 1];
+ pyassert(node instanceof TerminalNode);
+ return node;
+ }
+ /** A control flow graph is considered reducible or "well-structured" (see upstream docs). */
+ is_reducible() {
+ const seen = new Set();
+ const queue = [this.entry_node()];
+ const incoming_edges = new Map();
+ for (const n of this.nodes) {
+ const s = new Set(n.parents);
+ if (n.loop) for (const b of n.loop.backedges) s.delete(b);
+ incoming_edges.set(n, s);
+ }
+ while (queue.length) {
+ const n = queue.pop();
+ seen.add(n);
+ for (const s of n.children()) {
+ if (s.loop !== null && s.loop.backedges.has(n)) continue;
+ const inc = incoming_edges.get(s);
+ if (!inc.has(n)) throw new Error(`KeyError: ${n.name()}`);
+ inc.delete(n);
+ if (!inc.size && !queue.includes(s)) queue.push(s);
+ }
+ }
+ for (const v of incoming_edges.values()) if (v.size) return false;
+ if (seen.size !== this.nodes.length) return false;
+ const seen2 = reachable_backwards(this.terminal_node());
+ if (seen2.size !== this.nodes.length) return false;
+ return true;
+ }
+ reset_block_info() {
+ for (const node of this.nodes) node.block.block_info = null;
+ }
+ /** Update instr_inputs/instr_uses that `use` depends on `loc` from `src` */
+ add_instruction_use({ use, loc, src }) {
+ this.instr_inputs.get(use).add(loc, src);
+ this.instr_uses.get(src).add(loc, use);
+ }
+ /** Remove all inputs for `ref` from instr_inputs/instr_uses */
+ clear_instruction_inputs(ref) {
+ for (const [loc, uses] of this.instr_inputs.get(ref).items()) {
+ for (const use of uses) this.instr_uses.get(use).get(loc).remove(ref);
+ }
+ this.instr_inputs.delete(ref);
+ }
+ /** Verify that the instr_inputs & instr_uses dicts are consistent */
+ validate_instruction_graph() {
+ const new_uses = new DefaultMap(() => new LocationRefSetDict());
+ for (const [ref, inputs] of this.instr_inputs) {
+ for (const [reg, deps] of inputs.items()) for (const dep of deps) new_uses.get(dep).add(reg, ref);
+ }
+ for (const [ref, uses] of new_uses) {
+ for (const [reg, deps] of uses.items()) pyassert(deps.equals(this.instr_uses.get(ref).get(reg)));
+ }
+ }
+}
+
+/** Return the RefSet of all of the places `loc` is assigned to, if it is a valid phi. */
+function phi_loc_sources(node, loc, imdom_srcs) {
+ pyassert(node.immediate_dominator !== null);
+ const seen = new Set();
+ const stack = [...node.parents];
+ const sources = new RefSet();
+ while (stack.length) {
+ const n = stack.pop();
+ if (seen.has(n)) continue;
+ seen.add(n);
+ if (n === node.immediate_dominator) {
+ if (imdom_srcs.is_empty()) return RefSet.empty();
+ sources.update(imdom_srcs);
+ continue;
+ }
+ let broke = false;
+ const refs = n.block.instruction_refs;
+ for (let i = refs.length - 1; i >= 0; i--) {
+ const ref = refs[i];
+ if (ref.instruction.outputs.includes(loc)) {
+ sources.add(ref);
+ broke = true;
+ break;
+ }
+ if (ref.instruction.clobbers.includes(loc)) return RefSet.empty();
+ }
+ if (!broke) stack.push(...n.parents);
+ }
+ return sources;
+}
+
+export function locs_clobbered_until_dominator(node) {
+ pyassert(node.immediate_dominator !== null);
+ const seen = new Set([node.immediate_dominator]);
+ const stack = [...node.parents];
+ const clobbered = new Set();
+ while (stack.length) {
+ const n = stack.pop();
+ if (seen.has(n)) continue;
+ seen.add(n);
+ for (const instr of n.block.instructions) {
+ for (const o of instr.outputs) clobbered.add(o);
+ for (const c of instr.clobbers) clobbered.add(c);
+ }
+ stack.push(...n.parents);
+ }
+ return clobbered;
+}
+
+function compute_flowgraph_inputs_uses(flow_graph, fn, arch, { print_warnings = false } = {}) {
+ const missing_regs = [];
+
+ const process_node = (node, loc_srcs) => {
+ const add_use_sources = ({ use, input_loc }) => {
+ const sources = loc_srcs.get(input_loc);
+ for (const src of sources) flow_graph.add_instruction_use({ use, loc: input_loc, src });
+ return sources;
+ };
+
+ for (const ref of node.block.instruction_refs) {
+ const ir = ref.instruction;
+ for (const inp of ir.inputs) {
+ const sources = add_use_sources({ use: ref, input_loc: inp });
+ if (inp instanceof Register && sources.is_empty() && (ir.function_target === null || !arch.argument_regs.includes(inp))) {
+ missing_regs.push([inp, ref]);
+ }
+ }
+ for (const clob of [...ir.clobbers, ...ir.outputs]) if (loc_srcs.has(clob)) loc_srcs.remove(clob);
+ for (const out of ir.outputs) loc_srcs.add(out, ref);
+ }
+
+ if (node instanceof TerminalNode) {
+ pyassert(!node.block.instruction_refs.length);
+ for (const reg of arch.all_return_regs) add_use_sources({ use: new EpilogueRef(reg), input_loc: reg });
+ }
+
+ for (const child of node.immediately_dominates) {
+ const child_loc_srcs = loc_srcs.copy();
+ for (const loc of locs_clobbered_until_dominator(child)) {
+ const phi_reg_srcs = phi_loc_sources(child, loc, loc_srcs.get(loc));
+ if (!phi_reg_srcs.is_empty()) child_loc_srcs.set(loc, phi_reg_srcs);
+ else if (child_loc_srcs.has(loc)) child_loc_srcs.remove(loc);
+ }
+ process_node(child, child_loc_srcs);
+ }
+ };
+
+ const entry_reg_srcs = new LocationRefSetDict();
+ for (const r of arch.all_regs) entry_reg_srcs.refs.set(r, new RefSet([new PrologueRef(r)]));
+
+ const entry_node = flow_graph.entry_node();
+ process_node(entry_node, entry_reg_srcs);
+
+ if (print_warnings && missing_regs.length) {
+ print("/*");
+ print(`Warning: in ${fn.name}, regs were read before being written to:`);
+ for (const [reg, ref] of missing_regs) print(` ${reg} ${ref.instruction.meta.loc_str()}: ${ref.instruction}`);
+ print("*/");
+ }
+}
+
+/**
+ * Build the FlowGraph for the given Function.
+ * If `fragment` is true, do not treat the asm as a full function.
+ */
+export function build_flowgraph(fn, asm_data, arch, { fragment, print_warnings = false, debug_patterns = false }) {
+ const blocks = build_blocks(fn, asm_data, arch, { fragment, debug_patterns });
+ verify_no_duplicate_instructions(blocks);
+ let nodes = build_nodes(fn, blocks, asm_data, arch, { fragment });
+ warn_on_safeguard_use(fn, nodes, arch);
+ if (!fragment) nodes = duplicate_premature_returns(nodes, arch);
+ compute_relations(nodes);
+ if (!fragment) terminate_infinite_loops(nodes);
+ const flow_graph = new FlowGraph(nodes);
+ if (!fragment) arch.process_flowgraph(asm_data, flow_graph);
+ compute_flowgraph_inputs_uses(flow_graph, fn, arch, { print_warnings: print_warnings || fragment });
+ if (!fragment) arch.simplify_ir(asm_data, flow_graph, { debug_patterns });
+ return flow_graph;
+}
+
+export { Function };
diff --git a/packages/romdev-m2c/src/if_statements.js b/packages/romdev-m2c/src/if_statements.js
new file mode 100644
index 00000000..c9345a51
--- /dev/null
+++ b/packages/romdev-m2c/src/if_statements.js
@@ -0,0 +1,960 @@
+// Port of m2c/if_statements.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { BasicNode, ConditionalNode, ReturnNode, SwitchNode, TerminalNode } from "./flow_graph.js";
+import { Target } from "./options.js";
+import { BinaryOp, CommaConditionExpr, Condition, Literal, SwitchControl, early_unwrap_ints, format_expr, get_block_info, simplify_condition } from "./translate.js";
+import { Type } from "./types.js";
+import { DefaultMap, dcinit, dcreplace, factory, format, lstrip, pyassert, pyeq, sorted } from "./py.js";
+
+export class Context {
+ constructor({ flow_graph, fmt, options, is_void = true }) {
+ this.flow_graph = flow_graph;
+ this.fmt = fmt;
+ this.options = options;
+ this.is_void = is_void;
+ this.switch_nodes = new Map();
+ this.case_nodes = new DefaultMap(() => []);
+ this.goto_nodes = new Set();
+ this.emitted_nodes = new Set();
+ this.has_warned = false;
+ }
+ add_switch(node) {
+ this.switch_nodes.set(node, 0);
+ return new SwitchIndex(this, node);
+ }
+}
+
+export class IfElseStatement {
+ constructor(condition, if_body, else_body = null) {
+ this.condition = condition;
+ this.if_body = if_body;
+ this.else_body = else_body;
+ }
+ should_write() {
+ return true;
+ }
+ format(fmt) {
+ const space = fmt.indent("");
+ const condition = simplify_condition(this.condition);
+ const cond_str = format_expr(condition, fmt);
+ const after_ifelse = fmt.coding_style.newline_after_if ? `\n${space}` : " ";
+ const before_else = fmt.coding_style.newline_before_else ? `\n${space}` : " ";
+ let if_str = fmt.indented(() => [`${space}if (${cond_str})${after_ifelse}{`, this.if_body.format(fmt), `${space}}`].join("\n"));
+ if (this.else_body !== null && !this.else_body.is_empty()) {
+ const sub_if = this.else_body.get_lone_if_statement();
+ let else_str;
+ if (sub_if) {
+ const sub_if_str = lstrip(sub_if.format(fmt));
+ else_str = `${before_else}else ${sub_if_str}`;
+ } else {
+ else_str = fmt.indented(() => [`${before_else}else${after_ifelse}{`, this.else_body.format(fmt), `${space}}`].join("\n"));
+ }
+ if_str = if_str + else_str;
+ }
+ return if_str;
+ }
+}
+
+export class SwitchIndex {
+ constructor(context, node) {
+ this.context = context;
+ this.node = node;
+ }
+ equals(other) {
+ return other instanceof SwitchIndex && this.context === other.context && this.node === other.node;
+ }
+ to_comment(fmt) {
+ const index = this.context.switch_nodes.get(this.node);
+ if (this.context.switch_nodes.size === 1) return null;
+ return `switch ${index + 1}`;
+ }
+}
+
+export class SwitchStatement {
+ constructor(jump, body, index) {
+ this.jump = jump;
+ this.body = body;
+ this.index = index;
+ }
+ should_write() {
+ return true;
+ }
+ format(fmt) {
+ const lines = [];
+ const comments = [];
+ const body_is_empty = this.body.is_empty();
+ const comment = this.index.to_comment(fmt);
+ if (comment) comments.push(comment);
+ if (this.jump.is_irregular) comments.push("irregular");
+ else if (this.jump.num_cases === null) comments.push("unable to parse jump table");
+ else if (this.jump.jump_table !== null && body_is_empty) comments.push(`jump table: ${this.jump.jump_table.c_symbol_name}`);
+ const head = `switch (${format_expr(this.jump.control_expr, fmt)})`;
+ if (body_is_empty) lines.push(fmt.with_comments(`${head};`, comments));
+ else {
+ if (fmt.coding_style.newline_after_if) {
+ lines.push(fmt.with_comments(`${head}`, comments));
+ lines.push(fmt.indent("{"));
+ } else lines.push(fmt.with_comments(`${head} {`, comments));
+ fmt.indented(fmt.coding_style.switch_indent_level, () => lines.push(this.body.format(fmt)));
+ lines.push(fmt.indent("}"));
+ }
+ return lines.join("\n");
+ }
+}
+
+export class SimpleStatement {
+ static __fields = [["contents"], ["comments", factory(() => [])], ["is_jump", false], ["indent", 0]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ should_write() {
+ return this.contents !== null || this.comments.length > 0;
+ }
+ format(fmt) {
+ let content;
+ if (this.contents === null) content = "";
+ else if (typeof this.contents === "string") content = this.contents;
+ else content = this.contents.format(fmt);
+ const comments = [];
+ for (const c of this.comments) {
+ if (typeof c === "string") comments.push(c);
+ else {
+ const co = c(fmt);
+ if (co !== null) comments.push(co);
+ }
+ }
+ return fmt.with_comments(content, comments, { indent: this.indent });
+ }
+ clear() {
+ this.contents = null;
+ this.comments = [];
+ }
+}
+
+export class LabelStatement {
+ constructor(context, node) {
+ this.context = context;
+ this.node = node;
+ }
+ should_write() {
+ const cn = this.context.case_nodes.peek(this.node);
+ return this.context.goto_nodes.has(this.node) || Boolean(cn && cn.length);
+ }
+ format(fmt) {
+ const lines = [];
+ if (this.context.case_nodes.has(this.node)) {
+ for (const [index, case_label] of this.context.case_nodes.get(this.node)) {
+ const comment = index.to_comment(fmt);
+ const comments = comment ? [comment] : [];
+ lines.push(fmt.with_comments(`${case_label}:`, comments, { indent: -1 }));
+ }
+ }
+ if (this.context.goto_nodes.has(this.node)) lines.push(`${label_for_node(this.context, this.node)}:`);
+ return lines.join("\n");
+ }
+}
+
+export class DoWhileLoop {
+ constructor(body, condition) {
+ this.body = body;
+ this.condition = condition;
+ }
+ should_write() {
+ return true;
+ }
+ format(fmt) {
+ const space = fmt.indent("");
+ const after_do = fmt.coding_style.newline_after_if ? `\n${space}` : " ";
+ const cond = format_expr(simplify_condition(this.condition), fmt);
+ return fmt.indented(() => [`${space}do${after_do}{`, this.body.format(fmt), `${space}} while (${cond});`].join("\n"));
+ }
+}
+
+export class Body {
+ constructor(print_node_comment, statements = []) {
+ this.print_node_comment = print_node_comment;
+ this.statements = statements;
+ }
+ extend(other) {
+ this.print_node_comment = this.print_node_comment || other.print_node_comment;
+ this.statements.push(...other.statements);
+ }
+ add_node(node, comment_empty) {
+ const block_info = get_block_info(node);
+ const statements = block_info.statements_to_write();
+ if (this.print_node_comment && (statements.length || comment_empty)) this.add_comment(`Node ${node.name()}`);
+ for (const item of statements) this.statements.push(new SimpleStatement(item));
+ }
+ add_statement(statement) {
+ this.statements.push(statement);
+ }
+ add_comment(contents) {
+ this.add_statement(new SimpleStatement(null, { comments: [contents] }));
+ }
+ add_if_else(if_else) {
+ if (if_else.else_body === null || if_else.if_body.ends_in_jump()) {
+ this.statements.push(rewrite_if_ands(if_else.condition, if_else.if_body));
+ if (if_else.else_body !== null) this.extend(if_else.else_body);
+ } else this.statements.push(if_else);
+ }
+ add_do_while_loop(do_while_loop) {
+ this.statements.push(do_while_loop);
+ }
+ add_switch(sw) {
+ this.add_statement(sw);
+ }
+ is_empty() {
+ return !this.statements.some((s) => s.should_write());
+ }
+ ends_in_jump() {
+ for (let i = this.statements.length - 1; i >= 0; i--) {
+ const statement = this.statements[i];
+ if (!statement.should_write()) continue;
+ return statement instanceof SimpleStatement && statement.is_jump;
+ }
+ return false;
+ }
+ get_lone_if_statement() {
+ let ret = null;
+ for (const statement of this.statements) {
+ if (statement.should_write()) {
+ if (!(statement instanceof IfElseStatement) || ret) return null;
+ ret = statement;
+ }
+ }
+ return ret;
+ }
+ elide_empty_returns() {
+ for (let i = this.statements.length - 1; i >= 0; i--) {
+ const statement = this.statements[i];
+ if (statement instanceof SimpleStatement && statement.contents === "return;") statement.clear();
+ if (!statement.should_write()) continue;
+ if (statement instanceof IfElseStatement) {
+ statement.if_body.elide_empty_returns();
+ if (statement.else_body !== null) statement.else_body.elide_empty_returns();
+ }
+ break;
+ }
+ }
+ format(fmt) {
+ return this.statements
+ .filter((s) => s.should_write())
+ .map((s) => s.format(fmt))
+ .join("\n");
+ }
+}
+
+/** Iterate through the left-heavy `&&`-joined subconditions, rewriting CommaConditionExprs into nested ifs. */
+export function rewrite_if_ands(condition, if_body) {
+ let outer_cond = condition;
+ const inner_conds = [];
+ while (outer_cond instanceof BinaryOp && outer_cond.left instanceof Condition && outer_cond.op === "&&" && outer_cond.right instanceof Condition) {
+ const cond = outer_cond.right;
+ outer_cond = outer_cond.left;
+ if (!(cond instanceof CommaConditionExpr)) inner_conds.push(cond);
+ else {
+ let inner_cond = cond.condition;
+ while (inner_conds.length) inner_cond = join_conditions(inner_cond, "&&", inner_conds.pop());
+ const new_body = new Body(if_body.print_node_comment);
+ for (const stmt of cond.statements) new_body.add_statement(new SimpleStatement(stmt));
+ new_body.add_if_else(new IfElseStatement(inner_cond, if_body, null));
+ if_body = new_body;
+ condition = outer_cond;
+ }
+ }
+ return new IfElseStatement(condition, if_body, null);
+}
+
+export function label_for_node(context, node) {
+ if (node.loop) return `loop_${node.block.index}`;
+ return `block_${node.block.index}`;
+}
+
+/** Try to emit a node for the first time, together with a label for it. */
+export function emit_node(context, node, body) {
+ if (context.emitted_nodes.has(node)) {
+ if (!(node instanceof ReturnNode)) {
+ emit_goto(context, node, body);
+ return false;
+ } else body.add_comment(`Duplicate return node #${node.name()}. Try simplifying control flow for better match`);
+ } else {
+ body.add_statement(new LabelStatement(context, node));
+ context.emitted_nodes.add(node);
+ }
+ body.add_node(node, true);
+ if (node instanceof ReturnNode) emit_return(context, node, body);
+ return true;
+}
+
+export function emit_goto(context, target, body) {
+ pyassert(!(target instanceof TerminalNode), "cannot goto a TerminalNode");
+ const label = label_for_node(context, target);
+ context.goto_nodes.add(target);
+ body.add_statement(new SimpleStatement(`goto ${label};`, { is_jump: true }));
+}
+
+export function add_labels_for_switch(context, node, case_type, cases, default_node) {
+ pyassert(cases.length, "jtbl list must not be empty");
+ const switch_index = context.add_switch(node);
+ const indexes = sorted(cases.map(([i]) => i));
+ const use_hex = context.fmt.coding_style.hex_case || (Math.min(...indexes) >= 0 && Math.max(...indexes) > 50);
+
+ const skipped_labels = [];
+ let emitted_label_count = 0;
+
+ for (const [index, target] of cases) {
+ const enum_name = case_type.get_enum_name(index);
+ let case_label;
+ if (enum_name) case_label = `case ${enum_name}`;
+ else if (use_hex) {
+ if (index < 0) case_label = `case -0x${format(-index, "X")}`;
+ else case_label = `case 0x${format(index, "X")}`;
+ } else case_label = `case ${index}`;
+
+ if (is_empty_goto(target, default_node) || is_empty_goto(target, node.immediate_postdominator)) skipped_labels.push([target, [switch_index, case_label]]);
+ else {
+ context.case_nodes.get(target).push([switch_index, case_label]);
+ emitted_label_count += 1;
+ }
+ }
+
+ if (default_node !== null) {
+ context.case_nodes.get(default_node).push([switch_index, "default"]);
+ emitted_label_count += 1;
+ }
+
+ if (emitted_label_count < 5) for (const [target, label] of skipped_labels) context.case_nodes.get(target).push(label);
+ return switch_index;
+}
+
+/** If `node` is a switch bounds-check ConditionalNode, return the switch's control expression. */
+export function switch_guard_expr(node) {
+ if (!(node instanceof ConditionalNode)) return null;
+ const cond = get_block_info(node).branch_condition;
+ pyassert(cond !== null);
+ const switch_node = node.fallthrough_edge;
+ if (!(switch_node instanceof SwitchNode)) return null;
+ const switch_block_info = get_block_info(switch_node);
+ pyassert(switch_block_info.switch_control !== null);
+ if (
+ switch_node.parents.length === 1 &&
+ switch_node.parents[0] === node &&
+ !switch_block_info.statements_to_write().length &&
+ switch_block_info.switch_control.matches_guard_condition(cond)
+ ) {
+ return switch_block_info.switch_control.control_expr;
+ }
+ return null;
+}
+
+/** Return true if `node` represents a jump to `end` without any other statements */
+export function is_empty_goto(node, end) {
+ if (end === null) return false;
+ const seen_nodes = new Set([node]);
+ for (;;) {
+ if (node === end) return true;
+ const block_info = get_block_info(node);
+ if (block_info.statements_to_write().length) return false;
+ if (node instanceof ReturnNode && end instanceof TerminalNode && block_info.return_value === null) return true;
+ else if (node instanceof BasicNode) {
+ node = node.successor;
+ if (seen_nodes.has(node)) return false;
+ seen_nodes.add(node);
+ } else return false;
+ }
+}
+
+export function gather_any_comma_conditions(block_info) {
+ const branch_condition = block_info.branch_condition;
+ pyassert(branch_condition !== null);
+ const comma_statements = block_info.statements_to_write();
+ if (comma_statements.length) {
+ pyassert(!(branch_condition instanceof CommaConditionExpr));
+ return new CommaConditionExpr(comma_statements, branch_condition);
+ }
+ return branch_condition;
+}
+
+/** Utility class for tracking possible switch control values across multiple conditional branches. */
+export class Bounds {
+ static __fields = [["lower", -(2 ** 31)], ["upper", 2 ** 32 - 1], ["holes", factory(() => new Set())]];
+ constructor(...args) {
+ dcinit(this, args);
+ pyassert(this.lower <= this.upper);
+ }
+ without(hole) {
+ return dcreplace(this, { holes: new Set([...this.holes, hole]) });
+ }
+ at_most(val) {
+ if (this.lower <= val && val <= this.upper) return dcreplace(this, { upper: val });
+ else if (val > this.upper) return this;
+ return Bounds.empty();
+ }
+ at_least(val) {
+ if (this.lower <= val && val <= this.upper) return dcreplace(this, { lower: val });
+ else if (val < this.lower) return this;
+ return Bounds.empty();
+ }
+ values({ max_count }) {
+ const values = [];
+ for (let i = this.lower; i < this.upper + 1; i++) {
+ if (!this.holes.has(i)) {
+ values.push(i);
+ if (values.length > max_count) return null;
+ }
+ }
+ return values;
+ }
+ static empty() {
+ return new Bounds({ lower: 0, upper: 0, holes: new Set([0]) });
+ }
+}
+
+/** Try to express the nodes in `chained_cond_nodes` as a single Condition. Returns [cond, if_node, else_node] or null. */
+export function try_make_if_condition(chained_cond_nodes, end) {
+ const start_node = chained_cond_nodes[0];
+ let if_node = chained_cond_nodes[chained_cond_nodes.length - 1].fallthrough_edge;
+ let else_node = chained_cond_nodes[chained_cond_nodes.length - 1].conditional_edge;
+ pyassert(else_node !== null);
+
+ const allowed_nodes = new Set([...chained_cond_nodes, if_node, else_node]);
+ const node_cond_edges = new Map();
+ for (const node of chained_cond_nodes) {
+ if (!allowed_nodes.has(node.conditional_edge) || !allowed_nodes.has(node.fallthrough_edge)) return null;
+ allowed_nodes.delete(node);
+ const block_info = get_block_info(node);
+ let cond;
+ if (node === start_node) {
+ cond = block_info.branch_condition;
+ pyassert(cond instanceof Condition);
+ } else cond = gather_any_comma_conditions(block_info);
+ node_cond_edges.set(node, [cond, node.conditional_edge, node.fallthrough_edge]);
+ }
+
+ for (;;) {
+ const node_parents = new Map();
+ for (const node of node_cond_edges.keys()) node_parents.set(node, []);
+ for (const [node, edges] of node_cond_edges) {
+ for (const child of edges.slice(1)) {
+ if (child !== if_node && child !== else_node) {
+ pyassert(child instanceof ConditionalNode);
+ if (!node_parents.has(child)) throw new Error("KeyError: node");
+ node_parents.get(child).push(node);
+ }
+ }
+ }
+
+ let found = false;
+ for (const [child, parents] of node_parents) {
+ if (parents.length !== 1) continue;
+ const parent = parents[0];
+ const [child_cond, child_if, child_else] = node_cond_edges.get(child);
+ let [parent_cond, parent_if, parent_else] = node_cond_edges.get(parent);
+ let cond;
+ if (parent_if === child_if && parent_else === child) {
+ parent_else = child_else;
+ cond = join_conditions(parent_cond, "||", child_cond);
+ } else if (parent_if === child_else && parent_else === child) {
+ parent_else = child_if;
+ cond = join_conditions(parent_cond, "||", child_cond.negated());
+ } else if (parent_if === child && parent_else === child_if) {
+ parent_if = child_else;
+ cond = join_conditions(parent_cond, "&&", child_cond.negated());
+ } else if (parent_if === child && parent_else === child_else) {
+ parent_if = child_if;
+ cond = join_conditions(parent_cond, "&&", child_cond);
+ } else continue;
+ node_cond_edges.set(parent, [cond, parent_if, parent_else]);
+ node_cond_edges.delete(child);
+ found = true;
+ break;
+ }
+ if (!found) break;
+ }
+
+ if (node_cond_edges.size !== 1 || !node_cond_edges.has(start_node)) return null;
+ let [cond, left_node, right_node] = node_cond_edges.get(start_node);
+
+ if (left_node === else_node && right_node === if_node) cond = cond.negated();
+ else pyassert(left_node === if_node && right_node === else_node);
+
+ if (else_node === end) else_node = null;
+ else if (if_node === end) {
+ cond = cond.negated();
+ if_node = else_node;
+ else_node = null;
+ }
+ return [cond, if_node, else_node];
+}
+
+/** Look for irregular switch-like structures from nested ConditionalNodes & SwitchNodes. */
+export function try_build_irregular_switch(context, start, end) {
+ if (!(start instanceof ConditionalNode)) return null;
+ pyassert(start.postdominators.has(end));
+ const start_block_info = get_block_info(start);
+ const control_expr0 = switch_guard_expr(start);
+ let var_expr = null;
+
+ if (control_expr0 !== null) var_expr = control_expr0;
+ else if (start_block_info.branch_condition !== null) {
+ const start_cond = simplify_condition(start_block_info.branch_condition);
+ if (start_cond !== null && start_cond instanceof BinaryOp && start_cond.right instanceof Literal) var_expr = start_cond.left;
+ }
+ if (var_expr === null) return null;
+
+ const uw_var_expr = early_unwrap_ints(var_expr);
+ const node_queue = [[start, new Bounds()]];
+ const visited_nodes = new Set();
+ const nodes_to_mark_emitted = new Set();
+ const cases = new Map();
+ let default_node = null;
+ let irregular_comparison_count = 0;
+
+ while (node_queue.length) {
+ const [node, bounds] = node_queue.pop();
+ if (visited_nodes.has(node) || node === end || node === default_node) continue;
+ visited_nodes.add(node);
+ const block_info = get_block_info(node);
+
+ if (node !== start && block_info.statements_to_write().length) {
+ // pass
+ } else if (is_empty_goto(node, end)) {
+ nodes_to_mark_emitted.add(node);
+ if (node instanceof BasicNode) node_queue.push([node.successor, bounds]);
+ continue;
+ } else if (!node.dominators.has(start) || !node.postdominators.has(end)) {
+ // pass
+ } else if (node instanceof BasicNode) {
+ nodes_to_mark_emitted.add(node);
+ node_queue.push([node.successor, bounds]);
+ continue;
+ } else if (node instanceof ConditionalNode) {
+ const control_expr = switch_guard_expr(node);
+ if (control_expr !== null && pyeq(early_unwrap_ints(control_expr), uw_var_expr)) {
+ node_queue.push([node.fallthrough_edge, bounds]);
+ node_queue.push([node.conditional_edge, bounds]);
+ nodes_to_mark_emitted.add(node);
+ continue;
+ }
+ pyassert(block_info.branch_condition !== null);
+ const cond = simplify_condition(block_info.branch_condition);
+ if (cond instanceof BinaryOp && cond.right instanceof Literal && pyeq(early_unwrap_ints(cond.left), uw_var_expr)) {
+ const val = cond.right.value;
+ if (cond.op === "==") {
+ if (cases.has(val)) return null;
+ cases.set(val, node.conditional_edge);
+ node_queue.push([node.fallthrough_edge, bounds.without(val)]);
+ } else if (cond.op === "!=" && (node.block.index > node.conditional_edge.block.index || context.options.target.compiler !== Target.CompilerEnum.IDO)) {
+ if (cases.has(val)) return null;
+ cases.set(val, node.fallthrough_edge);
+ node_queue.push([node.conditional_edge, bounds.without(val)]);
+ } else if (cond.op === "<") {
+ node_queue.push([node.fallthrough_edge, bounds.at_least(val)]);
+ node_queue.push([node.conditional_edge, bounds.at_most(val - 1)]);
+ } else if (cond.op === ">=") {
+ node_queue.push([node.fallthrough_edge, bounds.at_most(val - 1)]);
+ node_queue.push([node.conditional_edge, bounds.at_least(val)]);
+ } else if (cond.op === "<=") {
+ node_queue.push([node.fallthrough_edge, bounds.at_least(val + 1)]);
+ node_queue.push([node.conditional_edge, bounds.at_most(val)]);
+ } else if (cond.op === ">") {
+ node_queue.push([node.fallthrough_edge, bounds.at_most(val)]);
+ node_queue.push([node.conditional_edge, bounds.at_least(val + 1)]);
+ } else return null;
+ irregular_comparison_count += 1;
+ nodes_to_mark_emitted.add(node);
+ continue;
+ }
+ } else if (node instanceof SwitchNode) {
+ if (block_info.switch_control === null) return null;
+ if (!pyeq(early_unwrap_ints(block_info.switch_control.control_expr), uw_var_expr)) return null;
+ let i = block_info.switch_control.offset;
+ for (const c of node.cases) {
+ if (cases.has(i)) return null;
+ cases.set(i, c);
+ i++;
+ }
+ nodes_to_mark_emitted.add(node);
+ irregular_comparison_count += 1;
+ continue;
+ }
+
+ const values = bounds.values({ max_count: 1 });
+ if (values && values.length && context.options.target.compiler !== Target.CompilerEnum.IDO) {
+ for (const value of values) {
+ if (cases.has(value)) return null;
+ cases.set(value, node);
+ }
+ nodes_to_mark_emitted.add(node);
+ continue;
+ }
+
+ if (default_node !== null) return null;
+ if (node instanceof ReturnNode || (node.dominators.has(start) && node.postdominators.has(end))) default_node = node;
+ }
+
+ if (irregular_comparison_count < 2 || nodes_to_mark_emitted.size < 3 || new Set(cases.values()).size < 2) return null;
+
+ const switch_index = add_labels_for_switch(context, start, var_expr.type, [...cases.entries()], default_node);
+ const case_nodes = [...cases.values()];
+ if (default_node !== null) case_nodes.push(default_node);
+ const sw = build_switch_statement(context, SwitchControl.irregular_from_expr(var_expr), case_nodes, switch_index, end);
+ for (const n of nodes_to_mark_emitted) context.emitted_nodes.add(n);
+ return sw;
+}
+
+/** Output the subgraph between `start` and `end`, including the branch condition in `start`. */
+export function build_conditional_subgraph(context, start, end) {
+ let curr_node = start;
+ const chained_cond_nodes = [];
+ for (;;) {
+ pyassert(curr_node instanceof ConditionalNode);
+ chained_cond_nodes.push(curr_node);
+ curr_node = curr_node.fallthrough_edge;
+ if (
+ !(
+ context.options.andor_detection &&
+ curr_node instanceof ConditionalNode &&
+ curr_node.postdominators.has(end) &&
+ end !== curr_node &&
+ !curr_node.loop &&
+ curr_node.parents.every((p) => chained_cond_nodes.includes(p)) &&
+ !switch_guard_expr(curr_node)
+ )
+ ) {
+ break;
+ }
+ }
+
+ let cond_result;
+ for (;;) {
+ pyassert(chained_cond_nodes.length);
+ cond_result = try_make_if_condition(chained_cond_nodes, end);
+ if (cond_result) break;
+ chained_cond_nodes.pop();
+ }
+ const [cond, if_node, else_node] = cond_result;
+
+ for (const n of chained_cond_nodes.slice(1)) context.emitted_nodes.add(n);
+
+ let else_body = null;
+ if (else_node) else_body = build_flowgraph_between(context, else_node, end);
+ const if_body = build_flowgraph_between(context, if_node, end);
+ return new IfElseStatement(cond, if_body, else_body);
+}
+
+export function join_conditions(left, op, right) {
+ pyassert(op === "&&" || op === "||");
+ return new BinaryOp(left, op, right, { type: Type.boolean() });
+}
+
+export function emit_return(context, node, body) {
+ const ret_info = get_block_info(node);
+ const ret = ret_info.return_value;
+ if (ret !== null) {
+ const ret_str = format_expr(ret, context.fmt);
+ body.add_statement(new SimpleStatement(`return ${ret_str};`, { is_jump: true }));
+ context.is_void = false;
+ } else body.add_statement(new SimpleStatement("return;", { is_jump: true }));
+}
+
+/** Helper for building both regular & irregular switch bodies. */
+export function build_switch_statement(context, jump, case_nodes, switch_index, end) {
+ const switch_body = new Body(context.options.debug);
+
+ const remaining_labels = [];
+ // (Python closure semantics: the lambda reads `index` late, i.e. its final value.)
+ let index;
+ const end_labels = context.case_nodes.get(end);
+ for (const entry of end_labels) {
+ index = entry[0];
+ const case_label = entry[1];
+ if (index.equals(switch_index)) {
+ const comments = [(fmt) => index.to_comment(fmt)];
+ switch_body.add_statement(new SimpleStatement(`${case_label}:`, { comments, indent: -1 }));
+ } else remaining_labels.push([index, case_label]);
+ }
+ if (remaining_labels.length !== context.case_nodes.get(end).length) {
+ switch_body.add_statement(new SimpleStatement("break;", { is_jump: true }));
+ context.case_nodes.set(end, remaining_labels);
+ }
+
+ const uniq = [...new Set(case_nodes)];
+ const sorted_cases = sorted(uniq, (node) => [node.block.index, case_nodes.indexOf(node)]);
+ const next_sorted_cases = [...sorted_cases.slice(1), null];
+ for (let k = 0; k < sorted_cases.length; k++) {
+ const c = sorted_cases[k];
+ const next_case = next_sorted_cases[k];
+ if (context.emitted_nodes.has(c) || c === end) {
+ // pass
+ } else if (next_case !== null && !context.emitted_nodes.has(next_case) && next_case !== end && c.postdominators.has(next_case)) {
+ switch_body.extend(build_flowgraph_between(context, c, next_case));
+ if (!switch_body.ends_in_jump()) switch_body.add_comment("fallthrough");
+ } else {
+ switch_body.extend(build_flowgraph_between(context, c, end));
+ if (!switch_body.ends_in_jump()) switch_body.add_statement(new SimpleStatement("break;", { is_jump: true }));
+ }
+ }
+ return new SwitchStatement(jump, switch_body, switch_index);
+}
+
+function enumerate_from(arr, start) {
+ return arr.map((v, i) => [i + start, v]);
+}
+
+/** Output the subgraph between `switch` and `end` (single jump table switches). */
+export function build_switch_between(context, sw, def, end) {
+ const switch_cases = [...sw.cases];
+ if (def === end) def = null;
+ else if (def !== null) switch_cases.push(def);
+ const jump = get_block_info(sw).switch_control;
+ pyassert(jump !== null);
+ const switch_index = add_labels_for_switch(context, sw, jump.control_expr.type, enumerate_from(sw.cases, jump.offset), def);
+ return build_switch_statement(context, jump, switch_cases, switch_index, end);
+}
+
+export function detect_loop(context, start, end) {
+ pyassert(start.loop);
+ let condition = null;
+ let new_end = null;
+ for (const node of start.loop.backedges) {
+ if (start.postdominators.has(node) && node instanceof ConditionalNode && node.fallthrough_edge === end) {
+ const block_info = get_block_info(node);
+ pyassert(block_info.branch_condition !== null);
+ condition = block_info.branch_condition;
+ new_end = node;
+ break;
+ }
+ }
+ if (!condition) return null;
+ const loop_body = build_flowgraph_between(context, start, new_end, true);
+ emit_node(context, new_end, loop_body);
+ return new DoWhileLoop(loop_body, condition);
+}
+
+/** Output a section of a flow graph (start inclusive, end exclusive). */
+export function build_flowgraph_between(context, start, end, skip_loop_detection = false) {
+ let curr_start = start;
+ const body = new Body(context.options.debug);
+
+ while (curr_start !== end) {
+ pyassert(!(curr_start instanceof TerminalNode));
+
+ if (!skip_loop_detection && curr_start.loop && !context.emitted_nodes.has(curr_start)) {
+ let imm_pdom = curr_start;
+ while (curr_start.loop.nodes.has(imm_pdom)) {
+ pyassert(imm_pdom.immediate_postdominator !== null);
+ imm_pdom = imm_pdom.immediate_postdominator;
+ }
+ const do_while_loop = detect_loop(context, curr_start, imm_pdom);
+ if (do_while_loop) {
+ body.add_do_while_loop(do_while_loop);
+ curr_start = imm_pdom;
+ continue;
+ }
+ }
+
+ if (context.emitted_nodes.has(curr_start) && is_empty_goto(curr_start, end)) break;
+
+ if (!emit_node(context, curr_start, body)) break;
+
+ if (curr_start.emit_goto) {
+ emit_goto(context, curr_start, body);
+ const index = context.flow_graph.nodes.indexOf(curr_start);
+ const fallthrough = context.flow_graph.nodes[index + 1];
+ if (curr_start instanceof ConditionalNode) pyassert(fallthrough === curr_start.fallthrough_edge);
+ curr_start = fallthrough;
+ continue;
+ }
+
+ let curr_end = curr_start.immediate_postdominator;
+ pyassert(curr_end !== null);
+
+ let irregular_switch = null;
+ if (context.options.switch_detection) irregular_switch = try_build_irregular_switch(context, curr_start, curr_end);
+
+ if (irregular_switch !== null) body.add_switch(irregular_switch);
+ else if (switch_guard_expr(curr_start) !== null) {
+ pyassert(curr_start instanceof ConditionalNode, "checked by switch_guard_expr");
+ const switch_node = curr_start.fallthrough_edge;
+ pyassert(switch_node instanceof SwitchNode, "checked by switch_guard_expr");
+ const default_node = curr_start.conditional_edge;
+ context.emitted_nodes.add(switch_node);
+ if (curr_end === switch_node) {
+ curr_end = switch_node.immediate_postdominator;
+ pyassert(curr_start.postdominators.has(curr_end));
+ }
+ body.add_switch(build_switch_between(context, switch_node, default_node, curr_end));
+ } else if (curr_start instanceof SwitchNode) {
+ body.add_switch(build_switch_between(context, curr_start, null, curr_end));
+ } else if (curr_start instanceof ConditionalNode) {
+ body.add_if_else(build_conditional_subgraph(context, curr_start, curr_end));
+ } else if (curr_start instanceof BasicNode && curr_start.fake_successor === curr_end) {
+ curr_end = curr_start.successor;
+ } else {
+ const ch = curr_start.children();
+ pyassert(
+ ch.length === 1 && ch[0] === curr_end,
+ `While emitting flowgraph between ${start.name()}:${end.name()}, ` + `skipped nodes while stepping from ${curr_start.name()} to ${curr_end.name()}.`,
+ );
+ }
+ curr_start = curr_end;
+ }
+ return body;
+}
+
+/** Naive procedure for generating output with only gotos for control flow. */
+export function build_naive(context, nodes) {
+ const body = new Body(context.options.debug);
+
+ const emit_goto_or_early_return = (node, b) => {
+ if (node instanceof ReturnNode && !node.is_real()) emit_node(context, node, b);
+ else emit_goto(context, node, b);
+ };
+ const emit_successor = (node, cur_index) => {
+ if (cur_index + 1 < nodes.length && nodes[cur_index + 1] === node && !(node instanceof ReturnNode && !node.is_real())) return;
+ emit_goto_or_early_return(node, body);
+ };
+
+ nodes.forEach((node, i) => {
+ if (node instanceof ReturnNode) {
+ if (node.is_real()) emit_node(context, node, body);
+ } else if (node instanceof BasicNode) {
+ emit_node(context, node, body);
+ emit_successor(node.successor, i);
+ } else if (node instanceof SwitchNode) {
+ const jump = get_block_info(node).switch_control;
+ pyassert(jump !== null);
+ const index = add_labels_for_switch(context, node, jump.control_expr.type, enumerate_from(node.cases, jump.offset), null);
+ emit_node(context, node, body);
+ body.add_switch(new SwitchStatement(jump, new Body(false), index));
+ } else if (node instanceof ConditionalNode) {
+ emit_node(context, node, body);
+ const if_body = new Body(true);
+ emit_goto_or_early_return(node.conditional_edge, if_body);
+ const block_info = get_block_info(node);
+ pyassert(block_info.branch_condition !== null);
+ body.add_if_else(new IfElseStatement(block_info.branch_condition, if_body, null));
+ emit_successor(node.fallthrough_edge, i);
+ } else {
+ pyassert(node instanceof TerminalNode);
+ }
+ });
+ return body;
+}
+
+export function build_body(context, options) {
+ const start_node = context.flow_graph.entry_node();
+ const terminal_node = context.flow_graph.terminal_node();
+ const is_reducible = context.flow_graph.is_reducible();
+
+ let body;
+ if (options.ifs && is_reducible) {
+ body = build_flowgraph_between(context, start_node, terminal_node);
+ body.elide_empty_returns();
+ } else {
+ body = new Body(context.options.debug);
+ if (options.ifs && !is_reducible) body.add_comment("Flowgraph is not reducible, falling back to gotos-only mode.");
+ body.extend(build_naive(context, context.flow_graph.nodes));
+ }
+
+ for (const node of context.flow_graph.nodes) {
+ if (context.emitted_nodes.has(node) || node instanceof TerminalNode) continue;
+ if (node instanceof ReturnNode && !node.is_real()) continue;
+ body.add_comment(`bug: did not emit code for node #${node.name()}; contents below:`);
+ emit_node(context, node, body);
+ }
+
+ let index = 0;
+ for (const node of context.flow_graph.nodes) {
+ if (context.switch_nodes.has(node)) {
+ context.switch_nodes.set(node, index);
+ index += 1;
+ }
+ }
+ return body;
+}
+
+export function get_function_text(function_info, options) {
+ const fmt = options.formatter();
+ const context = new Context({ flow_graph: function_info.flow_graph, options, fmt });
+ const body = build_body(context, options);
+
+ const function_lines = [];
+ if (options.debug) function_lines.push("Here's the whole function!\n");
+
+ for (const warning of function_info.stack_info.warnings) {
+ const line = fmt.with_comments("", [`Warning: ${warning}`]);
+ if (line) function_lines.push(line);
+ }
+ if (function_info.symbol.demangled_str !== null) {
+ const line = fmt.with_comments("", [function_info.symbol.demangled_str]);
+ if (line) function_lines.push(line);
+ }
+
+ const fn_name = function_info.symbol.c_symbol_name;
+ const arg_strs = [];
+ function_info.stack_info.arguments.forEach((arg, i) => {
+ if (i === 0 && function_info.stack_info.replace_first_arg !== null) {
+ const [original_name, original_type] = function_info.stack_info.replace_first_arg;
+ arg_strs.push(original_type.to_decl(original_name, fmt));
+ } else arg_strs.push(arg.type.to_decl(arg.format(fmt), fmt));
+ });
+ if (function_info.stack_info.is_variadic) arg_strs.push("...");
+ const arg_str = arg_strs.join(", ") || "void";
+
+ let fn_header = `${fn_name}(${arg_str})`;
+ if (context.is_void) fn_header = `void ${fn_header}`;
+ else fn_header = function_info.return_type.to_decl(fn_header, fmt);
+ const whitespace = fmt.coding_style.newline_after_function ? "\n" : " ";
+ function_lines.push(`${fn_header}${whitespace}{`);
+
+ let any_decl = false;
+ fmt.indented(() => {
+ const formatted_body = body.format(fmt);
+
+ let local_vars = function_info.stack_info.local_vars;
+ if (options.target.compiler !== Target.CompilerEnum.GCC) local_vars = [...local_vars].reverse();
+ for (const local_var of local_vars) {
+ const type_decl = local_var.toplevel_decl(fmt);
+ if (type_decl !== null) {
+ let comments = [];
+ if (function_info.stack_info.weak_stack_var_locations.has(local_var.value)) comments = ["compiler-managed"];
+ function_lines.push(new SimpleStatement(`${type_decl};`, { comments }).format(fmt));
+ any_decl = true;
+ }
+ }
+
+ const temp_decls = [];
+ for (const v of function_info.stack_info.temp_vars) {
+ if (v.is_emitted) {
+ const type_decl = v.type.to_decl(v.format(fmt), fmt);
+ temp_decls.push(`${type_decl};`);
+ any_decl = true;
+ }
+ }
+
+ const var_sort = fmt.descending_regs ? (d) => d.split("_")[1] : (d) => d;
+ for (const decl of sorted(temp_decls, var_sort, fmt.descending_regs)) function_lines.push(new SimpleStatement(decl).format(fmt));
+
+ for (const phi_var of function_info.stack_info.naive_phi_vars) {
+ const type_decl = phi_var.type.to_decl(phi_var.get_var_name(), fmt);
+ function_lines.push(new SimpleStatement(`${type_decl};`).format(fmt));
+ any_decl = true;
+ }
+
+ if (function_info.stack_info.replace_first_arg !== null) {
+ pyassert(function_info.stack_info.arguments.length >= 1);
+ const replaced_arg = function_info.stack_info.arguments[0];
+ const [original_name] = function_info.stack_info.replace_first_arg;
+ const lhs = replaced_arg.type.to_decl(replaced_arg.format(fmt), fmt);
+ const rhs = `(${replaced_arg.type.format(fmt)}) ${original_name}`;
+ function_lines.push(new SimpleStatement(`${lhs} = ${rhs};`).format(fmt));
+ }
+
+ if (any_decl) function_lines.push("");
+ function_lines.push(formatted_body);
+ function_lines.push("}");
+ });
+ return function_lines.join("\n");
+}
diff --git a/packages/romdev-m2c/src/index.js b/packages/romdev-m2c/src/index.js
new file mode 100644
index 00000000..d752b1b5
--- /dev/null
+++ b/packages/romdev-m2c/src/index.js
@@ -0,0 +1,42 @@
+// romdev-m2c - m2c ported to JS ESM (GPL-3.0; see NOTICE).
+//
+// import { decompile } from "romdev-m2c";
+// const { code, stdout, stderr } = await decompile(["--target", "mips-ido-c", "--context", ctx, "func.s"]);
+//
+// `decompile` takes the same flags as upstream m2c's CLI and returns what it would have
+// printed. Asm inputs may also be passed inline as { name, text } objects.
+export { decompile, parse_flags, run, ArgumentError } from "./main.js";
+export const UPSTREAM = { repo: "https://github.com/matt-kempster/m2c", commit: "1d1c4454a445326541305f83f2b0cb680a9ecb2d" };
+
+import { Worker } from "node:worker_threads";
+
+/**
+ * decompile() in a worker thread. Resolves to { code, stdout, stderr, timedOut }.
+ * On timeout the worker is terminated and code is null.
+ */
+export function decompileInWorker(flags, { timeoutMs = 120_000 } = {}) {
+ return new Promise((resolve, reject) => {
+ const worker = new Worker(new URL("./worker.js", import.meta.url), { workerData: { flags } });
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ worker.terminate();
+ resolve({ code: null, stdout: "", stderr: `m2c timed out after ${timeoutMs} ms\n`, timedOut: true });
+ }, timeoutMs);
+ worker.once("message", (m) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ worker.terminate();
+ if (m.ok) resolve({ code: m.code, stdout: m.stdout, stderr: m.stderr, timedOut: false });
+ else reject(new Error(m.error));
+ });
+ worker.once("error", (e) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(e);
+ });
+ });
+}
diff --git a/packages/romdev-m2c/src/instruction.js b/packages/romdev-m2c/src/instruction.js
new file mode 100644
index 00000000..5c49681e
--- /dev/null
+++ b/packages/romdev-m2c/src/instruction.js
@@ -0,0 +1,153 @@
+// Port of m2c/instruction.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { DecompFailure } from "./error.js";
+import { AsmGlobalSymbol, AsmLiteral, BinOp, ArchAsmParsing, parse_asm_instruction } from "./asm_instruction.js";
+import { band, intern, shallowcopy } from "./py.js";
+
+/**
+ * Represents a word on the stack. Currently only used for pattern matching.
+ * `symbolic_offset` represents a label offset that is only used in patterns.
+ */
+export class StackLocation {
+ constructor(offset, symbolic_offset) {
+ this.offset = offset;
+ this.symbolic_offset = symbolic_offset;
+ return intern(this, [offset, symbolic_offset]);
+ }
+ toString() {
+ const prefix = this.symbolic_offset === null ? "" : `${this.symbolic_offset}+`;
+ return `${prefix}${this.offset}($sp)`;
+ }
+ offset_as_arg() {
+ if (this.symbolic_offset === null) return new AsmLiteral(this.offset);
+ if (this.offset === 0) return new AsmGlobalSymbol(this.symbolic_offset);
+ return new BinOp("+", new AsmGlobalSymbol(this.symbolic_offset), new AsmLiteral(this.offset));
+ }
+ static from_offset(offset) {
+ const align = (x) => band(x, ~3);
+ if (offset instanceof AsmLiteral) return new StackLocation(align(offset.value), null);
+ if (offset instanceof AsmGlobalSymbol) return new StackLocation(0, offset.symbol_name);
+ if (offset instanceof BinOp && (offset.op === "+" || offset.op === "-") && offset.lhs instanceof AsmGlobalSymbol && offset.rhs instanceof AsmLiteral) {
+ let base = offset.rhs.value;
+ if (offset.op === "-") base = -base;
+ return new StackLocation(align(base), offset.lhs.symbol_name);
+ }
+ return null;
+ }
+}
+
+export class InstructionMeta {
+ constructor({ emit_goto, filename, lineno, synthetic }) {
+ // True if the original asm line was marked with a goto pattern
+ this.emit_goto = emit_goto;
+ // Asm source filename & line number
+ this.filename = filename;
+ this.lineno = lineno;
+ // True if the Instruction is not directly from the source asm
+ this.synthetic = synthetic;
+ return intern(this, [emit_goto, filename, lineno, synthetic]);
+ }
+ static missing() {
+ return new InstructionMeta({ emit_goto: false, filename: "", lineno: 0, synthetic: true });
+ }
+ derived() {
+ return new InstructionMeta({ emit_goto: this.emit_goto, filename: this.filename, lineno: this.lineno, synthetic: true });
+ }
+ loc_str() {
+ const adj = this.synthetic ? "near" : "at";
+ return `${adj} ${this.filename} line ${this.lineno}`;
+ }
+}
+
+const INSTRUCTION_DEFAULTS = {
+ jump_target: null,
+ function_target: null,
+ is_conditional: false,
+ is_return: false,
+ is_load: false,
+ is_store: false,
+ is_effectful: true,
+ has_delay_slot: false,
+ is_branch_likely: false,
+ in_pattern: false,
+};
+
+export class Instruction {
+ /**
+ * @param {object} f fields: mnemonic, args, meta, inputs, clobbers, outputs, eval_fn,
+ * and optional jump_target, function_target, is_conditional, is_return, is_load,
+ * is_store, is_effectful, has_delay_slot, is_branch_likely, in_pattern
+ */
+ constructor(f) {
+ this.mnemonic = f.mnemonic;
+ this.args = f.args;
+ this.meta = f.meta;
+ this.inputs = f.inputs;
+ this.clobbers = f.clobbers;
+ this.outputs = f.outputs;
+ this.eval_fn = f.eval_fn;
+ for (const [k, v] of Object.entries(INSTRUCTION_DEFAULTS)) this[k] = f[k] === undefined ? v : f[k];
+ }
+ is_jump() {
+ return this.jump_target !== null || this.is_return;
+ }
+ toString() {
+ if (!this.args.length) return this.mnemonic;
+ return `${this.mnemonic} ${this.args.map((a) => String(a)).join(", ")}`;
+ }
+ arch_mnemonic(arch) {
+ return `${arch.arch}:${this.mnemonic}`;
+ }
+ clone() {
+ return this.replace({ meta: this.meta.derived() });
+ }
+ /** dataclasses.replace */
+ replace(changes) {
+ const out = shallowcopy(this);
+ Object.assign(out, changes);
+ return out;
+ }
+}
+
+/** Arch-specific information that relates to the asm level. Extends ArchAsmParsing. */
+export class ArchAsm extends ArchAsmParsing {
+ missing_return() {
+ throw new Error("abstract");
+ }
+ parse(mnemonic, args, meta) {
+ throw new Error("abstract");
+ }
+}
+
+ArchAsm.prototype.asm_word_size = 4;
+
+export function parse_instruction(line, meta, arch, asm_state) {
+ try {
+ const base = parse_asm_instruction(line, arch, asm_state);
+ return arch.parse(base.mnemonic, base.args, meta);
+ } catch (e) {
+ let msg = `Failed to parse instruction ${meta.loc_str()}: ${line}`;
+ if (e instanceof DecompFailure) msg += "\n\n" + e.message;
+ throw new DecompFailure(msg);
+ }
+}
+
+export class InstrProcessingFailure extends Error {
+ constructor(instr, cause) {
+ super(`Error while processing instruction:\n${instr}`, cause ? { cause } : undefined);
+ this.name = "InstrProcessingFailure";
+ this.instr = instr;
+ }
+ __str__() {
+ return `Error while processing instruction:\n${this.instr}`;
+ }
+}
+
+/** Mark an instruction as being the one currently processed, for error messages. */
+export function set_current_instr(instr, fn) {
+ try {
+ return fn();
+ } catch (e) {
+ throw new InstrProcessingFailure(instr, e);
+ }
+}
diff --git a/packages/romdev-m2c/src/io.js b/packages/romdev-m2c/src/io.js
new file mode 100644
index 00000000..3988ab0c
--- /dev/null
+++ b/packages/romdev-m2c/src/io.js
@@ -0,0 +1,42 @@
+// io.js - stdout/stderr capture standing in for Python's print() / sys.stdout.
+// m2c writes its output with print(); run() captures it into a string.
+
+const stack = [];
+
+/** Run fn with print() output captured; returns { value, stdout, stderr }. */
+export function capture(fn) {
+ const sink = { out: [], err: [] };
+ stack.push(sink);
+ let value;
+ try {
+ value = fn();
+ } finally {
+ stack.pop();
+ }
+ return { value, stdout: sink.out.join(""), stderr: sink.err.join("") };
+}
+
+function current() {
+ return stack[stack.length - 1] ?? null;
+}
+
+/** Python print(*args, sep=" ", end="\n", file=stdout|stderr). */
+export function print(...args) {
+ let opts = {};
+ if (args.length && args[args.length - 1] && typeof args[args.length - 1] === "object" && args[args.length - 1].__print_opts) opts = args.pop();
+ const { sep = " ", end = "\n", stderr = false } = opts;
+ const text = args.map((a) => (typeof a === "string" ? a : String(a))).join(sep) + end;
+ write(text, stderr);
+}
+
+/** Options marker for print(): print("x", popts({ end: "" })). */
+export function popts(o) {
+ return { ...o, __print_opts: true };
+}
+
+/** sys.stdout.write / sys.stderr.write */
+export function write(text, stderr = false) {
+ const s = current();
+ if (s) (stderr ? s.err : s.out).push(text);
+ else (stderr ? process.stderr : process.stdout).write(text);
+}
diff --git a/packages/romdev-m2c/src/ir_pattern.js b/packages/romdev-m2c/src/ir_pattern.js
new file mode 100644
index 00000000..c1a66407
--- /dev/null
+++ b/packages/romdev-m2c/src/ir_pattern.js
@@ -0,0 +1,284 @@
+// Port of m2c/ir_pattern.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { assert_never } from "./error.js";
+import { BaseNode, InstrRef, RefSet, TerminalNode, build_flowgraph } from "./flow_graph.js";
+import { AsmData, Function } from "./asm_file.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmInstruction, AsmLiteral, AsmState, BinOp, Register, RegisterList } from "./asm_instruction.js";
+import { Instruction, InstructionMeta, StackLocation, parse_instruction } from "./instruction.js";
+import { DefaultMap, pyassert, shl } from "./py.js";
+import { isupper } from "./asm_pattern.js";
+import { print } from "./io.js";
+
+/**
+ * Template for defining "IR" patterns that can match against input asm.
+ * Subclasses define static-ish instance fields `parts` (string[]) and `replacement` (string),
+ * and can optionally implement `check()`.
+ */
+export class IrPattern {
+ check(m, arch, flow_graph) {
+ return true;
+ }
+ compile(arch) {
+ const missing_meta = InstructionMeta.missing();
+ const asm_state = new AsmState({ is_pattern: true });
+ const replacement_instr = parse_instruction(this.replacement, missing_meta, arch, asm_state);
+
+ const name = `__pattern_${this.constructor.name}`;
+ const func = new Function({ name });
+ pyassert(replacement_instr.inputs.length === new Set(replacement_instr.inputs).size, "pattern inputs must be unique");
+ for (const inp of replacement_instr.inputs) {
+ func.new_instruction(new Instruction({ mnemonic: "in.fictive", args: [], meta: missing_meta, inputs: [], clobbers: [], outputs: [inp], eval_fn: null }));
+ }
+ for (const part of this.parts) func.new_instruction(parse_instruction(part, missing_meta, arch, asm_state));
+
+ const asm_data = new AsmData();
+ const flow_graph = build_flowgraph(func, asm_data, arch, { fragment: true });
+ return new CompiledIrPattern(this, flow_graph, replacement_instr);
+ }
+}
+
+export class CompiledIrPattern {
+ constructor(source, flow_graph, replacement_instr) {
+ this.source = source;
+ this.flow_graph = flow_graph;
+ this.replacement_instr = replacement_instr;
+ }
+}
+
+/** IrMatch represents the matched state of an IrPattern. */
+export class IrMatch {
+ constructor({ asm_data, symbolic_registers = new Map(), symbolic_args = new Map(), ref_map = new Map(), body = [] }) {
+ this.asm_data = asm_data;
+ this.symbolic_registers = symbolic_registers;
+ this.symbolic_args = symbolic_args;
+ this.ref_map = ref_map;
+ this.body = body;
+ }
+ static _is_symbolic_reg(arg) {
+ return arg.register_name.length <= 1;
+ }
+ static _is_symbolic_sym(arg) {
+ return isupper(arg.symbol_name);
+ }
+ static _is_label_sym(arg) {
+ return arg.symbol_name.startsWith(".");
+ }
+ eval_math(pat) {
+ if (pat instanceof AsmLiteral) return pat;
+ if (pat instanceof BinOp) {
+ const lhs = this.eval_math(pat.lhs);
+ const rhs = this.eval_math(pat.rhs);
+ if (lhs instanceof AsmLiteral && rhs instanceof AsmLiteral) {
+ if (pat.op === "+") return new AsmLiteral(lhs.value + rhs.value);
+ if (pat.op === "-") return new AsmLiteral(lhs.value - rhs.value);
+ if (pat.op === "<<") return new AsmLiteral(shl(lhs.value, rhs.value));
+ }
+ return new BinOp(pat.op, lhs, rhs);
+ } else if (pat instanceof AsmGlobalSymbol) {
+ pyassert(this.symbolic_args.has(pat.symbol_name), `undefined variable in math pattern: ${pat.symbol_name}`);
+ return this.symbolic_args.get(pat.symbol_name);
+ } else {
+ pyassert(false, `bad pattern expr: ${pat}`);
+ }
+ }
+ map_reg(key) {
+ const ret = this.symbolic_registers.get(key.register_name);
+ if (ret !== undefined && ret !== null) return ret;
+ pyassert(!IrMatch._is_symbolic_reg(key));
+ return key;
+ }
+ map_arg(key) {
+ if (key instanceof AsmLiteral) return key;
+ if (key instanceof Register) return this.map_reg(key);
+ if (key instanceof AsmGlobalSymbol) {
+ pyassert(!IrMatch._is_label_sym(key), "not supported yet");
+ if (IrMatch._is_symbolic_sym(key)) {
+ if (!this.symbolic_args.has(key.symbol_name)) throw new Error(`KeyError: '${key.symbol_name}'`);
+ return this.symbolic_args.get(key.symbol_name);
+ }
+ return key;
+ }
+ if (key instanceof AsmAddressMode) return new AsmAddressMode(this.map_reg(key.base), this.map_arg(key.addend), key.writeback);
+ if (key instanceof BinOp) return this.eval_math(key);
+ pyassert(false, `bad pattern part: ${key}`);
+ }
+ map_ref(key) {
+ const refset = this.ref_map.get(key);
+ if (refset === undefined) throw new Error("KeyError: ref");
+ const value = refset.get_unique();
+ pyassert(value instanceof InstrRef);
+ return value;
+ }
+ try_map_ref(key) {
+ const refset = this.ref_map.get(key);
+ if (refset === undefined) return null;
+ return refset.get_unique();
+ }
+ map_location(key) {
+ if (key instanceof Register) return this.map_reg(key);
+ if (key instanceof StackLocation) {
+ const loc = StackLocation.from_offset(this.map_arg(key.offset_as_arg()));
+ pyassert(loc !== null);
+ return loc;
+ }
+ assert_never(key);
+ }
+ map_asm(key) {
+ return new AsmInstruction(
+ key.mnemonic,
+ key.args.map((a) => this.map_arg(a)),
+ );
+ }
+}
+
+/** Partial (in-progress) match state of an IrPattern. */
+export class TryIrMatch extends IrMatch {
+ _match_var(var_map, key, value, eq = (a, b) => a === b) {
+ if (var_map.has(key)) {
+ if (!eq(var_map.get(key), value)) return false;
+ } else var_map.set(key, value);
+ return true;
+ }
+ match_arg(pat, cand) {
+ if (pat instanceof AsmLiteral) return pat === cand;
+ if (pat instanceof Register) {
+ if (!IrMatch._is_symbolic_reg(pat)) return pat === cand;
+ if (!(cand instanceof Register)) return false;
+ return this._match_var(this.symbolic_registers, pat.register_name, cand);
+ }
+ if (pat instanceof AsmGlobalSymbol) {
+ pyassert(!IrMatch._is_label_sym(pat), "not supported yet");
+ if (IrMatch._is_symbolic_sym(pat)) return this._match_var(this.symbolic_args, pat.symbol_name, cand);
+ return pat === cand;
+ }
+ if (pat instanceof AsmAddressMode) {
+ return cand instanceof AsmAddressMode && this.match_arg(pat.base, cand.base) && this.match_arg(pat.addend, cand.addend) && pat.writeback === cand.writeback;
+ }
+ if (pat instanceof BinOp) return this.eval_math(pat) === cand;
+ if (pat instanceof RegisterList) {
+ return cand instanceof RegisterList && cand.regs.length === pat.regs.length && cand.regs.every((cr, i) => this.match_arg(cr, pat.regs[i]));
+ }
+ pyassert(false, `bad pattern arg: ${pat}`);
+ }
+ match_instr(pat, cand) {
+ if (pat.mnemonic !== cand.mnemonic || pat.args.length !== cand.args.length) return false;
+ return pat.args.every((a, i) => this.match_arg(a, cand.args[i]));
+ }
+ match_refset(pat, cand_set) {
+ return this._match_var(this.ref_map, pat, cand_set.copy(), (a, b) => a.equals(b));
+ }
+ match_inputrefs(pat, cand) {
+ for (const [pat_loc, pat_refs] of pat.items()) {
+ const cand_loc = this.map_location(pat_loc);
+ const cand_refs = cand.get(cand_loc);
+ const pat_ref = pat_refs.get_unique();
+ pyassert(pat_ref !== null, "patterns can not have phis");
+ if (!this.match_refset(pat_ref, cand_refs)) return false;
+ }
+ return true;
+ }
+ rename_reg(pat, new_reg) {
+ this.symbolic_registers.set(pat.register_name, new_reg);
+ }
+}
+
+export function simplify_ir_patterns(arch, asm_data, flow_graph, patterns, { debug_patterns }) {
+ const refs_by_mnemonic = new DefaultMap(() => []);
+ for (const node of flow_graph.nodes) for (const ref of node.block.instruction_refs) refs_by_mnemonic.get(ref.instruction.mnemonic).push(ref);
+
+ let fictive_reg_index = 0;
+
+ for (const pattern_base of patterns) {
+ const pattern = pattern_base.compile(arch);
+ pyassert(pattern.flow_graph.nodes.length === 2, "branching patterns not yet supported");
+ pyassert(pattern.flow_graph.nodes[0] instanceof BaseNode);
+ pyassert(pattern.flow_graph.nodes[1] instanceof TerminalNode);
+ const pattern_node = pattern.flow_graph.nodes[0];
+ const pattern_refs = pattern_node.block.instruction_refs;
+
+ const n_inputs = pattern.replacement_instr.inputs.length;
+ const input_refs = pattern_refs.slice(0, n_inputs);
+ const body_refs = pattern_refs.slice(n_inputs, -1);
+ const tail_ref = pattern_refs[pattern_refs.length - 1];
+ pyassert(input_refs.every((r) => r.instruction.mnemonic === "in.fictive"));
+ pyassert(body_refs.every((r) => r.instruction.mnemonic !== "in.fictive"));
+ pyassert(pattern.replacement_instr.inputs.every((inp) => inp instanceof Register));
+ const ro = pattern.replacement_instr.outputs;
+ const to = tail_ref.instruction.outputs;
+ pyassert(ro.length === to.length && ro.every((x, i) => x === to[i]), `${ro} ${to}`);
+
+ const cands = refs_by_mnemonic.has(tail_ref.instruction.mnemonic) ? refs_by_mnemonic.get(tail_ref.instruction.mnemonic) : [];
+ for (const cand_tail_ref of cands) {
+ const state = new TryIrMatch({ asm_data });
+ if (!state.match_refset(tail_ref, new RefSet([cand_tail_ref]))) continue;
+
+ let is_match = true;
+ for (const pat_ref of [tail_ref, ...[...body_refs].reverse()]) {
+ const cand = state.try_map_ref(pat_ref);
+ const pat_inputs = pattern.flow_graph.instr_inputs.get(pat_ref);
+ if (!(cand instanceof InstrRef && state.match_instr(pat_ref.instruction, cand.instruction) && state.match_inputrefs(pat_inputs, flow_graph.instr_inputs.get(cand)))) {
+ is_match = false;
+ break;
+ }
+ }
+ if (!is_match) continue;
+
+ for (const pat_ref of [...body_refs, tail_ref]) state.body.push(state.map_ref(pat_ref));
+
+ if (!pattern.source.check(state, arch, flow_graph)) continue;
+
+ const temp_reg_refs = new Map();
+ for (const pat_ref of input_refs) {
+ pyassert(pat_ref.instruction.outputs.length === 1);
+ const input_reg = pat_ref.instruction.outputs[0];
+ pyassert(input_reg instanceof Register);
+ const input_uses = pattern.flow_graph.instr_uses.get(pat_ref).get(input_reg);
+ const input_use_ref = state.map_ref(input_uses.refs[0]);
+ const original_reg = state.map_reg(input_reg);
+ const temp_reg = Register.fictive(original_reg.register_name, String(fictive_reg_index));
+ fictive_reg_index += 1;
+ state.rename_reg(input_reg, temp_reg);
+
+ const move_asm = new AsmInstruction("move.fictive", [temp_reg, original_reg]);
+ const move_ref = input_use_ref.add_instruction_before(move_asm, arch);
+ temp_reg_refs.set(temp_reg, move_ref);
+
+ for (const src_ref of flow_graph.instr_inputs.get(input_use_ref).get(original_reg)) {
+ flow_graph.add_instruction_use({ use: move_ref, loc: original_reg, src: src_ref });
+ }
+ }
+
+ const repl_ref = state.map_ref(tail_ref);
+ const repl_asm = state.map_asm(pattern.replacement_instr);
+ repl_ref.replace_instruction(repl_asm, arch);
+
+ flow_graph.clear_instruction_inputs(repl_ref);
+ for (const [temp_reg, temp_ref] of temp_reg_refs) flow_graph.add_instruction_use({ use: repl_ref, loc: temp_reg, src: temp_ref });
+
+ for (const pat_ref of [...body_refs].reverse()) {
+ const cand_ref = state.map_ref(pat_ref);
+ if (flow_graph.instr_uses.get(cand_ref).is_empty()) {
+ const nop_asm = new AsmInstruction("nop", []);
+ cand_ref.replace_instruction(nop_asm, arch);
+ flow_graph.clear_instruction_inputs(cand_ref);
+ } else if (!cand_ref.instruction.in_pattern) {
+ cand_ref.instruction = cand_ref.instruction.replace({ in_pattern: true });
+ }
+ }
+
+ if (debug_patterns) {
+ print(`Rewrote asm using ${pattern.constructor.name}:`);
+ print();
+ for (const node of flow_graph.nodes) {
+ const instrs = node.block.instructions;
+ if (instrs.length) {
+ print(`${node.block.approx_label_name}:`);
+ for (const ins of node.block.instructions) print(String(ins));
+ }
+ }
+ print();
+ }
+ }
+ }
+ flow_graph.validate_instruction_graph();
+}
diff --git a/packages/romdev-m2c/src/main.js b/packages/romdev-m2c/src/main.js
new file mode 100644
index 00000000..70b83499
--- /dev/null
+++ b/packages/romdev-m2c/src/main.js
@@ -0,0 +1,528 @@
+// Port of m2c/main.py
+import fs from "node:fs";
+import { build_typemap, dump_typemap } from "./c_types.js";
+import { DecompFailure } from "./error.js";
+import { build_flowgraph } from "./flow_graph.js";
+import { get_function_text } from "./if_statements.js";
+import { CodingStyle, Options, Target } from "./options.js";
+import { AsmData, parse_file } from "./asm_file.js";
+import { InstrProcessingFailure } from "./instruction.js";
+import { GlobalInfo, narrow_func_call_outputs, translate_to_ast, visualize_flowgraph } from "./translate.js";
+import { TypePool } from "./types.js";
+import { MipsArch, MipseeArch } from "./arch_mips.js";
+import { ValueError, int_ } from "./py.js";
+import { capture, print, write } from "./io.js";
+
+let graphviz = null;
+/** Graphviz compiled to WASM, loaded only when --visualize is used. */
+async function loadGraphviz() {
+ if (!graphviz) graphviz = (await import("@viz-js/viz")).instance();
+ return graphviz;
+}
+
+let archModules = null;
+async function loadArchModules() {
+ if (archModules) return archModules;
+ const [ppc, arm, sh] = await Promise.all([import("./arch_ppc.js"), import("./arch_arm.js"), import("./arch_sh.js")]);
+ archModules = { ppc, arm, sh };
+ return archModules;
+}
+
+class DecompilationState {
+ constructor(fn, state) {
+ this.function = fn;
+ this.state = state; // {flow_graph, info} or an Error
+ }
+}
+
+function isError(x) {
+ return x instanceof Error;
+}
+
+/** Python traceback.format_exception_only-ish rendering for internal errors. */
+function print_exception(exc) {
+ let e = exc;
+ if (e instanceof InstrProcessingFailure && e.cause) e = e.cause;
+ const name = e && e.name ? e.name : "Error";
+ const msg = e && e.message !== undefined ? e.message : String(e);
+ print("Traceback (most recent call last):");
+ if (e && e.stack) {
+ for (const line of String(e.stack).split("\n").slice(1)) print(` ${line.trim()}`);
+ }
+ print(msg ? `${name}: ${msg}` : name);
+}
+
+function print_exception_as_comment(exc, options, context) {
+ const context_phrase = context !== null ? ` in ${context}` : "";
+ if (exc && (exc.code === "ENOENT" || exc.code === "EACCES" || exc.code === "EISDIR")) {
+ print(`/* OSError${context_phrase}: ${exc.message} */`);
+ return;
+ } else if (exc instanceof DecompFailure) {
+ print("/*");
+ print(`Decompilation failure${context_phrase}:\n`);
+ print(exc.message);
+ if (options.stacktrace && exc.cause) {
+ print();
+ print_exception(exc.cause);
+ }
+ print("*/");
+ } else {
+ print("/*");
+ print(`Internal error${context_phrase}:\n`);
+ print_exception(exc);
+ print("*/");
+ }
+}
+
+function make_arch(options, mods) {
+ const t = options.target;
+ if (t.arch === Target.ArchEnum.MIPS) return t.platform === Target.PlatformEnum.MIPSEE ? new MipseeArch() : new MipsArch();
+ if (t.arch === Target.ArchEnum.PPC) return new mods.ppc.PpcArch();
+ if (t.arch === Target.ArchEnum.ARM) return t.platform === Target.PlatformEnum.GBA ? new mods.arm.ArmGbaArch() : new mods.arm.ArmArch();
+ if (t.arch === Target.ArchEnum.SH) return t.platform === Target.PlatformEnum.SH4 ? new mods.sh.Sh4Arch() : new mods.sh.Sh2Arch();
+ throw new ValueError(`Invalid target arch: ${t.arch}`);
+}
+
+/**
+ * Run m2c with parsed options, printing to the current io sink. Returns the exit code.
+ * Arch modules for non-MIPS targets are loaded by run_async / decompile.
+ */
+export function run(options, mods = archModules ?? {}) {
+ const arch = make_arch(options, mods);
+
+ const all_functions = new Map();
+ const asm_data = new AsmData();
+ let typemap;
+ try {
+ for (const filename of options.filenames) {
+ let text;
+ if (typeof filename === "object" && filename !== null) text = filename.text;
+ else if (filename === "-") text = fs.readFileSync(0, "utf8");
+ else text = fs.readFileSync(filename, "utf8");
+ const name = typeof filename === "object" && filename !== null ? filename.name : filename;
+ const asm_file = parse_file({ name, text }, arch, options);
+ for (const fn of asm_file.functions) all_functions.set(fn.name, fn);
+ asm_file.asm_data.merge_into(asm_data);
+ }
+ if (options.heuristic_strings) asm_data.detect_heuristic_strings();
+ typemap = build_typemap(options.c_contexts, arch, options.use_cache);
+ } catch (e) {
+ print_exception_as_comment(e, options, null);
+ return 1;
+ }
+
+ if (options.dump_typemap) {
+ dump_typemap(typemap);
+ return 0;
+ }
+
+ let functions;
+ if (!options.function_indexes_or_names.length) functions = [...all_functions.values()];
+ else {
+ const functions_by_c_name = new Map();
+ for (const [name, fn] of all_functions) functions_by_c_name.set(arch.c_symbol_name(name), fn);
+ functions = [];
+ for (const index_or_name of options.function_indexes_or_names) {
+ if (typeof index_or_name === "number") {
+ if (!(0 <= index_or_name && index_or_name < all_functions.size)) {
+ print(`Function index ${index_or_name} is out of bounds (must be between ` + `0 and ${all_functions.size - 1}).`, { __print_opts: true, stderr: true });
+ return 1;
+ }
+ functions.push([...all_functions.values()][index_or_name]);
+ } else {
+ let fn = all_functions.get(index_or_name) ?? null;
+ if (fn === null) fn = functions_by_c_name.get(index_or_name) ?? null;
+ if (fn === null) {
+ print(`Function ${index_or_name} not found.`, { __print_opts: true, stderr: true });
+ return 1;
+ }
+ functions.push(fn);
+ }
+ }
+ }
+
+ const fmt = options.formatter();
+ const function_names = new Set(all_functions.keys());
+ const typepool = new TypePool({
+ unknown_field_prefix: fmt.coding_style.unknown_underscore ? "unk_" : "unk",
+ unk_inference: options.unk_inference,
+ union_field_overrides: options.union_field_overrides,
+ });
+ const global_info = new GlobalInfo(asm_data, arch, options.target, function_names, typemap, typepool, {
+ deterministic_vars: options.deterministic_vars,
+ stack_spill_detection: options.stack_spill_detection,
+ });
+
+ const decompilations = [];
+ for (const fn of functions) {
+ let state;
+ try {
+ narrow_func_call_outputs(fn, global_info);
+ const flow_graph = build_flowgraph(fn, global_info.asm_data, arch, { fragment: false, print_warnings: options.debug, debug_patterns: options.debug_patterns });
+ state = { flow_graph, info: null };
+ } catch (e) {
+ state = e;
+ }
+ decompilations.push(new DecompilationState(fn, state));
+ }
+
+ let global_decls_exc = null;
+ for (let i = 0; i < options.passes - 1; i++) {
+ for (const decomp of decompilations) {
+ if (isError(decomp.state)) continue;
+ const flow_graph = decomp.state.flow_graph;
+ try {
+ flow_graph.reset_block_info();
+ decomp.state.info = translate_to_ast(decomp.function, flow_graph, options, global_info);
+ } catch (e) {
+ decomp.state = e;
+ }
+ }
+ if (global_decls_exc === null) {
+ try {
+ global_info.global_decls(fmt, options.global_decls, []);
+ } catch (e) {
+ global_decls_exc = e;
+ }
+ }
+ for (const decomp of decompilations) {
+ if (isError(decomp.state)) continue;
+ const info = decomp.state.info;
+ try {
+ get_function_text(info, options);
+ } catch (e) {
+ decomp.state = e;
+ }
+ }
+ typepool.prune_structs();
+ }
+
+ for (const decomp of decompilations) {
+ if (isError(decomp.state)) continue;
+ const flow_graph = decomp.state.flow_graph;
+ try {
+ flow_graph.reset_block_info();
+ decomp.state.info = translate_to_ast(decomp.function, flow_graph, options, global_info);
+ } catch (e) {
+ decomp.state = e;
+ }
+ }
+
+ if (options.visualize_flowgraph !== null) {
+ const decomp = decompilations[0];
+ try {
+ if (isError(decomp.state)) throw decomp.state;
+ const dot_source = visualize_flowgraph(decomp.state.flow_graph, options.visualize_flowgraph);
+ if (options.visualize_format === Options.VisualizeFormatEnum.SVG) {
+ // Upstream pipes the dot source through graphviz; here graphviz runs as WASM (@viz-js/viz).
+ if (!mods.viz) throw new DecompFailure("SVG visualization: graphviz WASM not loaded (call decompile(), which loads it)");
+ write(mods.viz.renderString(dot_source, { format: "svg" }));
+ } else write(dot_source);
+ return 0;
+ } catch (e) {
+ print_exception_as_comment(e, options, null);
+ return 1;
+ }
+ }
+
+ let return_code = 0;
+ try {
+ const type_decls = typepool.format_type_declarations(fmt, options.print_stack_structs);
+ if (type_decls) print(type_decls);
+ if (global_decls_exc !== null) throw global_decls_exc;
+ const infos = decompilations.filter((d) => !isError(d.state) && d.state.info !== null).map((d) => d.state.info);
+ const global_decls = global_info.global_decls(fmt, options.global_decls, infos);
+ if (global_decls) print(global_decls);
+ } catch (e) {
+ print_exception_as_comment(e, options, null);
+ return_code = 1;
+ }
+
+ decompilations.forEach((decomp, index) => {
+ if (index !== 0) print();
+ const fn = decomp.function;
+ try {
+ if (options.print_assembly) {
+ print(String(fn));
+ print();
+ }
+ if (isError(decomp.state)) throw decomp.state;
+ const function_text = get_function_text(decomp.state.info, options);
+ print(function_text);
+ } catch (e) {
+ print_exception_as_comment(e, options, `function ${fn.name}`);
+ return_code = 1;
+ }
+ });
+
+ for (const warning of typepool.warnings) {
+ const line = fmt.with_comments("", [warning]);
+ if (line) print(line);
+ }
+ return return_code;
+}
+
+// ---------------------------------------------------------------- flags
+
+const BOOL_FLAGS = {
+ "--no-cache": ["use_cache", false],
+ "--stack-structs": ["print_stack_structs", true],
+ "--debug": ["debug", true],
+ "--debug-patterns": ["debug_patterns", true],
+ "--stacktrace": ["stacktrace", true],
+ "--print-assembly": ["print_assembly", true],
+ "--dump-typemap": ["dump_typemap", true],
+ "--sanitize-tracebacks": ["sanitize_tracebacks", true],
+ "--valid-syntax": ["valid_syntax", true],
+ "--allman": ["allman", true],
+ "--knr": ["knr", true],
+ "--indent-switch-contents": ["indent_switch_contents", true],
+ "--unk-underscore": ["unknown_underscore", true],
+ "--hex-case": ["hex_case", true],
+ "--no-casts": ["skip_casts", true],
+ "--zfill-constants": ["zfill_constants", true],
+ "--force-decimal": ["force_decimal", true],
+ "--deterministic-vars": ["deterministic_vars", true],
+ "--descending-regs": ["descending_regs", true],
+ "--backwards-bss": ["backwards_bss", true],
+ "--stop-on-error": ["stop_on_error", true],
+ "--void": ["void", true],
+ "--gotos-only": ["ifs", false],
+ "--no-ifs": ["ifs", false],
+ "--no-switches": ["switch_detection", false],
+ "--no-andor": ["andor_detection", false],
+ "--no-unk-inference": ["unk_inference", false],
+ "--no-stack-spill": ["stack_spill_detection", false],
+ "--heuristic-strings": ["heuristic_strings", true],
+ "--pdb-translate": ["pdb_translate", true],
+ "--disable-gc": ["disable_gc", true],
+};
+const VALUE_FLAGS = {
+ "--context": "c_contexts",
+ "-D": "defined",
+ "-U": "undefined",
+ "--incbin-dir": "incbin_dirs",
+ "-f": "functions",
+ "--function": "functions",
+ "--globals": "global_decls",
+ "--visualize-format": "visualize_format",
+ "--pointer-style": "pointer_style",
+ "--comment-style": "comment_style",
+ "--comment-column": "comment_column",
+ "-t": "target",
+ "--target": "target",
+ "--passes": "passes",
+ "-P": "passes",
+ "--reg-vars": "reg_vars",
+ "--goto": "goto_patterns",
+ "--union-field": "union_fields",
+};
+const APPEND = new Set(["c_contexts", "defined", "undefined", "incbin_dirs", "functions", "goto_patterns", "union_fields"]);
+
+export class ArgumentError extends Error {}
+
+const ALL_LONG = [...Object.keys(BOOL_FLAGS), ...Object.keys(VALUE_FLAGS), "--visualize"].filter((o) => o.startsWith("--"));
+function has_opt(flag) {
+ return ALL_LONG.includes(flag);
+}
+
+/** Parse m2c command-line flags (subset-compatible with upstream argparse). Returns Options. */
+export function parse_flags(flags) {
+ const args = {
+ filenames: [],
+ c_contexts: [],
+ use_cache: true,
+ defined: [],
+ undefined: [],
+ incbin_dirs: [],
+ functions: [],
+ global_decls: "used",
+ print_stack_structs: false,
+ debug: false,
+ debug_patterns: false,
+ stacktrace: false,
+ print_assembly: false,
+ dump_typemap: false,
+ visualize_flowgraph: null,
+ visualize_format: "svg",
+ sanitize_tracebacks: false,
+ valid_syntax: false,
+ allman: false,
+ knr: false,
+ indent_switch_contents: false,
+ pointer_style: "right",
+ unknown_underscore: false,
+ hex_case: false,
+ comment_style: "multiline",
+ comment_column: "52",
+ skip_casts: false,
+ zfill_constants: false,
+ force_decimal: false,
+ deterministic_vars: false,
+ descending_regs: false,
+ backwards_bss: false,
+ target: "mips-ido-c",
+ passes: "2",
+ stop_on_error: false,
+ void: false,
+ ifs: true,
+ switch_detection: true,
+ andor_detection: true,
+ unk_inference: true,
+ stack_spill_detection: true,
+ heuristic_strings: false,
+ reg_vars: null,
+ goto_patterns: ["GOTO"],
+ pdb_translate: false,
+ disable_gc: false,
+ union_fields: [],
+ };
+ for (let i = 0; i < flags.length; i++) {
+ let flag = flags[i];
+ if (typeof flag !== "string") {
+ args.filenames.push(flag);
+ continue;
+ }
+ let value = null;
+ if (flag.startsWith("--") && flag.includes("=")) {
+ value = flag.slice(flag.indexOf("=") + 1);
+ flag = flag.slice(0, flag.indexOf("="));
+ } else if (/^-[DUftP]./.test(flag) && !flag.startsWith("--")) {
+ value = flag.slice(2);
+ flag = flag.slice(0, 2);
+ }
+ if (flag.startsWith("--") && !has_opt(flag)) {
+ // argparse accepts unambiguous prefixes of long options
+ const matches = ALL_LONG.filter((o) => o.startsWith(flag));
+ if (matches.length === 1) flag = matches[0];
+ else if (matches.length > 1) throw new ArgumentError(`ambiguous option: ${flag} could match ${matches.join(", ")}`);
+ }
+ if (flag === "--visualize") {
+ if (value === null && i + 1 < flags.length && (flags[i + 1] === "asm" || flags[i + 1] === "c")) value = flags[++i];
+ args.visualize_flowgraph = value ?? "c";
+ continue;
+ }
+ if (Object.prototype.hasOwnProperty.call(BOOL_FLAGS, flag)) {
+ const [k, v] = BOOL_FLAGS[flag];
+ args[k] = v;
+ continue;
+ }
+ if (Object.prototype.hasOwnProperty.call(VALUE_FLAGS, flag)) {
+ if (value === null) {
+ if (i + 1 >= flags.length) throw new ArgumentError(`argument ${flag}: expected one argument`);
+ value = flags[++i];
+ }
+ const k = VALUE_FLAGS[flag];
+ if (APPEND.has(k)) args[k] = k === "goto_patterns" ? [...args[k], value] : [...args[k], value];
+ else args[k] = value;
+ continue;
+ }
+ if (flag.startsWith("-") && flag !== "-") throw new ArgumentError(`unrecognized arguments: ${flag}`);
+ args.filenames.push(flag);
+ }
+ if (!args.filenames.length) throw new ArgumentError("the following arguments are required: filename");
+
+ const reg_vars = args.reg_vars ? args.reg_vars.split(",") : [];
+ const preproc_defines = new Map();
+ for (const d of args.undefined) preproc_defines.set(d, null);
+ for (const d of args.defined) {
+ const i = d.indexOf("=");
+ if (i >= 0) preproc_defines.set(d.slice(0, i), int_(d.slice(i + 1), 0));
+ else preproc_defines.set(d, 1);
+ }
+
+ const coding_style = new CodingStyle({
+ newline_after_function: args.allman || args.knr,
+ newline_after_if: args.allman,
+ newline_before_else: args.allman,
+ switch_indent_level: args.indent_switch_contents ? 2 : 1,
+ pointer_style_left: args.pointer_style === "left",
+ unknown_underscore: args.unknown_underscore,
+ hex_case: args.hex_case,
+ comment_style: CodingStyle.CommentStyle.of(args.comment_style),
+ comment_column: int_(args.comment_column),
+ });
+
+ const functions = [];
+ for (const fn of args.functions) {
+ try {
+ functions.push(int_(fn));
+ } catch (e) {
+ if (!(e instanceof ValueError)) throw e;
+ functions.push(fn);
+ }
+ }
+
+ const union_field_overrides = new Map();
+ for (const override of args.union_fields) {
+ const i = override.indexOf(":");
+ if (i < 0) throw new ArgumentError(`Error: Invalid union field override '${override}'. Expected format: STRUCT_NAME:FIELD_NAME`);
+ union_field_overrides.set(override.slice(0, i), override.slice(i + 1));
+ }
+
+ let visualize_flowgraph = args.visualize_flowgraph === null ? null : Options.VisualizeTypeEnum.of(args.visualize_flowgraph);
+ if (visualize_flowgraph !== null) {
+ args.debug = false;
+ args.debug_patterns = false;
+ }
+
+ return new Options({
+ filenames: args.filenames,
+ function_indexes_or_names: functions,
+ debug: args.debug,
+ debug_patterns: args.debug_patterns,
+ stacktrace: args.stacktrace,
+ void: args.void,
+ ifs: args.ifs,
+ switch_detection: args.switch_detection,
+ andor_detection: args.andor_detection,
+ skip_casts: args.skip_casts,
+ zfill_constants: args.zfill_constants,
+ force_decimal: args.force_decimal,
+ heuristic_strings: args.heuristic_strings,
+ reg_vars,
+ goto_patterns: args.goto_patterns,
+ stop_on_error: args.stop_on_error,
+ print_assembly: args.print_assembly,
+ visualize_flowgraph,
+ visualize_format: Options.VisualizeFormatEnum.of(args.visualize_format),
+ c_contexts: args.c_contexts,
+ use_cache: args.use_cache,
+ dump_typemap: args.dump_typemap,
+ pdb_translate: args.pdb_translate,
+ preproc_defines,
+ coding_style,
+ sanitize_tracebacks: args.sanitize_tracebacks,
+ valid_syntax: args.valid_syntax,
+ global_decls: Options.GlobalDeclsEnum.of(args.global_decls),
+ target: Target.parse(args.target),
+ print_stack_structs: args.print_stack_structs,
+ unk_inference: args.unk_inference,
+ stack_spill_detection: args.stack_spill_detection,
+ passes: int_(args.passes),
+ incbin_dirs: args.incbin_dirs,
+ deterministic_vars: args.deterministic_vars,
+ descending_regs: args.descending_regs,
+ backwards_bss: args.backwards_bss,
+ disable_gc: args.disable_gc,
+ union_field_overrides,
+ });
+}
+
+/**
+ * In-process equivalent of running upstream m2c with : returns { code, stdout, stderr }.
+ * Asm inputs may be file paths, or {name, text} objects mixed into `flags`.
+ */
+export async function decompile(flags) {
+ const mods = { ...(await loadArchModules()) };
+ if (flags.some((f) => typeof f === "string" && f.startsWith("--visualize"))) mods.viz = await loadGraphviz();
+ let options;
+ try {
+ options = parse_flags(flags);
+ } catch (e) {
+ if (e instanceof ArgumentError || e instanceof ValueError) return { code: 2, stdout: "", stderr: `m2c: error: ${e.message}\n` };
+ throw e;
+ }
+ const r = capture(() => run(options, mods));
+ return { code: r.value, stdout: r.stdout, stderr: r.stderr };
+}
diff --git a/packages/romdev-m2c/src/options.js b/packages/romdev-m2c/src/options.js
new file mode 100644
index 00000000..7f4b00c8
--- /dev/null
+++ b/packages/romdev-m2c/src/options.js
@@ -0,0 +1,287 @@
+// Port of m2c/options.py
+import { assert_never } from "./error.js";
+import { ValueError, format } from "./py.js";
+
+let enumSeq = 0;
+/** Minimal Python enum.Enum replacement: members are singletons with .name/.value. */
+export class PyEnum {
+ constructor(name, value) {
+ this.name = name;
+ this.value = value;
+ Object.defineProperty(this, "__enum_key", { value: `${new.target.name}.${name}.${++enumSeq}`, enumerable: false });
+ }
+ __str__() {
+ return String(this.value);
+ }
+ toString() {
+ return String(this.value);
+ }
+ static define(cls, members) {
+ cls.members = [];
+ for (const [name, value] of Object.entries(members)) {
+ const m = new cls(name, value);
+ cls[name] = m;
+ cls.members.push(m);
+ }
+ return cls;
+ }
+ /** `EnumCls(value)` lookup; raises ValueError like Python. */
+ static of(value) {
+ for (const m of this.members) if (m.value === value) return m;
+ throw new ValueError(`'${value}' is not a valid ${this.name}`);
+ }
+}
+
+export class CommentStyle extends PyEnum {}
+PyEnum.define(CommentStyle, { MULTILINE: "multiline", ONELINE: "oneline", NONE: "none" });
+
+export class CodingStyle {
+ static CommentStyle = CommentStyle;
+ constructor({
+ newline_after_function,
+ newline_after_if,
+ newline_before_else,
+ switch_indent_level,
+ pointer_style_left,
+ unknown_underscore,
+ hex_case,
+ comment_style,
+ comment_column,
+ }) {
+ this.newline_after_function = newline_after_function;
+ this.newline_after_if = newline_after_if;
+ this.newline_before_else = newline_before_else;
+ this.switch_indent_level = switch_indent_level;
+ this.pointer_style_left = pointer_style_left;
+ this.unknown_underscore = unknown_underscore;
+ this.hex_case = hex_case;
+ this.comment_style = comment_style;
+ this.comment_column = comment_column;
+ Object.freeze(this);
+ }
+}
+
+class PlatformEnum extends PyEnum {
+ get arch() {
+ if (this === PlatformEnum.MIPS) return ArchEnum.MIPS;
+ else if (this === PlatformEnum.MIPSEL) return ArchEnum.MIPS;
+ else if (this === PlatformEnum.MIPSEE) return ArchEnum.MIPS;
+ else if (this === PlatformEnum.PPC) return ArchEnum.PPC;
+ else if (this === PlatformEnum.ARM) return ArchEnum.ARM;
+ else if (this === PlatformEnum.GBA) return ArchEnum.ARM;
+ else if (this === PlatformEnum.SH2 || this === PlatformEnum.SH4) return ArchEnum.SH;
+ else return assert_never(this);
+ }
+}
+PyEnum.define(PlatformEnum, { MIPS: "mips", MIPSEL: "mipsel", MIPSEE: "mipsee", PPC: "ppc", ARM: "arm", GBA: "gba", SH2: "sh2", SH4: "sh4" });
+class ArchEnum extends PyEnum {}
+PyEnum.define(ArchEnum, { MIPS: "mips", PPC: "ppc", ARM: "arm", SH: "sh" });
+class EndianEnum extends PyEnum {}
+PyEnum.define(EndianEnum, { LITTLE: "little", BIG: "big" });
+class CompilerEnum extends PyEnum {}
+PyEnum.define(CompilerEnum, { IDO: "ido", GCC: "gcc", MWCC: "mwcc", SHC: "shc" });
+class LanguageEnum extends PyEnum {}
+PyEnum.define(LanguageEnum, { C: "c", CXX: "c++" });
+
+export class Target {
+ static PlatformEnum = PlatformEnum;
+ static ArchEnum = ArchEnum;
+ static EndianEnum = EndianEnum;
+ static CompilerEnum = CompilerEnum;
+ static LanguageEnum = LanguageEnum;
+
+ constructor({ platform, arch, endian, compiler, language }) {
+ this.platform = platform;
+ this.arch = arch;
+ this.endian = endian;
+ this.compiler = compiler;
+ this.language = language;
+ }
+
+ is_big_endian() {
+ return this.endian === EndianEnum.BIG;
+ }
+
+ /**
+ * Parse an `platform-compiler-language` triple.
+ * If `-language` is missing, use the default for the compiler.
+ * If `-compiler` is missing, use the default for the platform.
+ */
+ static parse(name) {
+ let endian = EndianEnum.BIG;
+ const terms = name.split("-");
+ let platform, arch, compiler, language;
+ try {
+ platform = PlatformEnum.of(terms[0]);
+ if ([PlatformEnum.MIPSEL, PlatformEnum.MIPSEE, PlatformEnum.ARM, PlatformEnum.GBA, PlatformEnum.SH4].includes(platform)) {
+ endian = EndianEnum.LITTLE;
+ }
+ arch = platform.arch;
+
+ if (terms.length >= 2) compiler = CompilerEnum.of(terms[1]);
+ else if (platform === PlatformEnum.SH4) compiler = CompilerEnum.SHC;
+ else if (arch === ArchEnum.PPC) compiler = CompilerEnum.MWCC;
+ else if (arch === ArchEnum.MIPS && endian === EndianEnum.BIG) compiler = CompilerEnum.IDO;
+ else compiler = CompilerEnum.GCC;
+
+ if (terms.length >= 3) language = LanguageEnum.of(terms[2]);
+ else if (compiler === CompilerEnum.MWCC) language = LanguageEnum.CXX;
+ else language = LanguageEnum.C;
+ } catch (e) {
+ if (e instanceof ValueError) throw new ValueError(`Unable to parse Target '${name}' (${e.message})`);
+ throw e;
+ }
+ return new Target({ platform, arch, endian, compiler, language });
+ }
+}
+
+class GlobalDeclsEnum extends PyEnum {}
+PyEnum.define(GlobalDeclsEnum, { ALL: "all", USED: "used", NONE: "none" });
+class VisualizeTypeEnum extends PyEnum {}
+PyEnum.define(VisualizeTypeEnum, { ASM: "asm", C: "c" });
+class VisualizeFormatEnum extends PyEnum {}
+PyEnum.define(VisualizeFormatEnum, { DOT: "dot", SVG: "svg" });
+
+export class Options {
+ static GlobalDeclsEnum = GlobalDeclsEnum;
+ static VisualizeTypeEnum = VisualizeTypeEnum;
+ static VisualizeFormatEnum = VisualizeFormatEnum;
+
+ constructor(fields) {
+ Object.assign(this, fields);
+ }
+
+ formatter() {
+ return new Formatter({
+ coding_style: this.coding_style,
+ skip_casts: this.skip_casts,
+ zfill_constants: this.zfill_constants,
+ force_decimal: this.force_decimal,
+ valid_syntax: this.valid_syntax,
+ descending_regs: this.descending_regs,
+ backwards_bss: this.backwards_bss,
+ });
+ }
+}
+
+export const DEFAULT_CODING_STYLE = new CodingStyle({
+ newline_after_function: false,
+ newline_after_if: false,
+ newline_before_else: false,
+ switch_indent_level: 1,
+ pointer_style_left: false,
+ unknown_underscore: false,
+ hex_case: false,
+ comment_style: CommentStyle.MULTILINE,
+ comment_column: 52,
+});
+
+/** Python len() of a str (code points). */
+function pylen(s) {
+ let n = 0;
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i);
+ if (c < 0xd800 || c > 0xdbff) n++;
+ }
+ return n;
+}
+
+export class Formatter {
+ constructor({
+ coding_style = DEFAULT_CODING_STYLE,
+ indent_step = " ".repeat(4),
+ skip_casts = false,
+ extra_indent = 0,
+ debug = false,
+ valid_syntax = false,
+ line_length = 80,
+ zfill_constants = false,
+ force_decimal = false,
+ descending_regs = false,
+ backwards_bss = false,
+ } = {}) {
+ this.coding_style = coding_style;
+ this.indent_step = indent_step;
+ this.skip_casts = skip_casts;
+ this.extra_indent = extra_indent;
+ this.debug = debug;
+ this.valid_syntax = valid_syntax;
+ this.line_length = line_length;
+ this.zfill_constants = zfill_constants;
+ this.force_decimal = force_decimal;
+ this.descending_regs = descending_regs;
+ this.backwards_bss = backwards_bss;
+ }
+
+ indent(line, indent = 0) {
+ return this.indent_step.repeat(Math.max(indent + this.extra_indent, 0)) + line;
+ }
+
+ /** Python `with fmt.indented(amt):` - runs fn with extra indentation. */
+ indented(amt, fn) {
+ if (typeof amt === "function") {
+ fn = amt;
+ amt = 1;
+ }
+ try {
+ this.extra_indent += amt;
+ return fn();
+ } finally {
+ this.extra_indent -= amt;
+ }
+ }
+
+ format_array(elements) {
+ if (!elements.some((el) => el.includes("\n") || pylen(el) > this.line_length)) {
+ const output = `{ ${elements.join(", ")} }`;
+ if (pylen(output) < this.line_length) return output;
+ }
+ let output = "{\n";
+ for (let el of elements) {
+ el = el.replaceAll("\n", "\n" + this.indent_step);
+ output += this.indent(`${el},\n`, 1);
+ }
+ output += "}";
+ return output;
+ }
+
+ /** Indent `line` and append a list of `comments` joined with ';' */
+ with_comments(line, comments, { indent = 0 } = {}) {
+ const base = this.indent(line, indent);
+ if (!comments.length || this.coding_style.comment_style === CommentStyle.NONE) return base;
+ let padding = "";
+ if (line) padding = " ".repeat(Math.max(1, this.coding_style.comment_column - pylen(base)));
+ const comment_str = comments.join("; ");
+ let start, mid, end;
+ if (this.coding_style.comment_style === CommentStyle.ONELINE) {
+ start = "// ";
+ mid = "// ";
+ end = "";
+ } else {
+ start = "/* ";
+ mid = " * ";
+ end = " */";
+ }
+ const lines = comment_str.split("\n");
+ let ret = `${base}${padding}${start}${lines[0]}`;
+ for (const cline of lines.slice(1)) {
+ const new_base = this.indent("", indent) + " ".repeat(pylen(line));
+ ret += `\n${new_base}${padding}${mid}${cline}`;
+ }
+ return ret + end;
+ }
+
+ format_hex(val) {
+ return format(val, "x").toUpperCase();
+ }
+
+ format_int(val, size_bits = null) {
+ if (Math.abs(val) < 10 || this.force_decimal) return String(val);
+ let hex_digits;
+ if (this.zfill_constants && size_bits !== null && size_bits !== undefined) hex_digits = format(Math.abs(val), `0${Math.floor(size_bits / 4)}X`);
+ else hex_digits = format(Math.abs(val), "X");
+ if (hex_digits.length === 7) hex_digits = `0${hex_digits}`;
+ if (val < 0) return `-0x${hex_digits}`;
+ else return `0x${hex_digits}`;
+ }
+}
diff --git a/packages/romdev-m2c/src/py.js b/packages/romdev-m2c/src/py.js
new file mode 100644
index 00000000..7346540d
--- /dev/null
+++ b/packages/romdev-m2c/src/py.js
@@ -0,0 +1,952 @@
+// py.js - small helpers that reproduce the Python semantics m2c relies on
+// (integer arithmetic, number formatting, string methods, containers), so the
+// module-by-module port can stay a line-for-line translation.
+//
+// Porting conventions used across src/:
+// - Identifiers keep m2c's Python names (snake_case functions, methods and
+// attributes; CamelCase classes) so the port can be diffed against upstream.
+// - Python ints are JS Numbers. Every bitwise operation that can see a value
+// outside int32 goes through band/bor/bxor/shl/shr below (JS operators
+// truncate to 32 bits). `//` is floordiv, `%` is pymod.
+// - Frozen value dataclasses are interned (see intern()), so `===` and Map
+// keys give Python's value equality and hashing.
+// - `assert` becomes pyassert(), raising AssertionError.
+
+export class AssertionError extends Error {
+ constructor(message) {
+ super(message ?? "");
+ this.name = "AssertionError";
+ }
+}
+export class ValueError extends Error {
+ constructor(message) {
+ super(message ?? "");
+ this.name = "ValueError";
+ }
+}
+export class IndexError extends Error {
+ constructor(message) {
+ super(message ?? "");
+ this.name = "IndexError";
+ }
+}
+export class KeyError extends Error {
+ constructor(message) {
+ super(message ?? "");
+ this.name = "KeyError";
+ }
+}
+
+/** Python `assert cond, msg`. */
+export function pyassert(cond, msg) {
+ if (!cond) throw new AssertionError(msg === undefined ? "" : String(msg));
+}
+
+// ---------------------------------------------------------------- integers
+
+const I32_MIN = -0x80000000;
+const I32_MAX = 0x7fffffff;
+const isI32 = (x) => x >= I32_MIN && x <= I32_MAX;
+
+function toBig(x) {
+ if (typeof x === "bigint") return x;
+ if (!Number.isInteger(x)) throw new TypeError(`integer expected, got ${x}`);
+ return BigInt(x);
+}
+/**
+ * Python ints beyond 2**53 (64-bit register/double bit patterns) are kept as
+ * BigInt so no bits are lost; everything in the safe range is a Number.
+ */
+function fromBig(b) {
+ const n = Number(b);
+ return Number.isSafeInteger(n) ? n : b;
+}
+export function normint(b) {
+ return typeof b === "bigint" ? fromBig(b) : b;
+}
+
+/** Python `a & b` for arbitrary-size ints. */
+export function band(a, b) {
+ if (isI32(a) && isI32(b)) return a & b;
+ if (a >= 0 && b >= 0 && a <= 0xffffffff && b <= 0xffffffff) return (a & b) >>> 0;
+ return fromBig(toBig(a) & toBig(b));
+}
+/** Python `a | b`. */
+export function bor(a, b) {
+ if (isI32(a) && isI32(b)) return a | b;
+ if (a >= 0 && b >= 0 && a <= 0xffffffff && b <= 0xffffffff) return (a | b) >>> 0;
+ return fromBig(toBig(a) | toBig(b));
+}
+/** Python `a ^ b`. */
+export function bxor(a, b) {
+ if (isI32(a) && isI32(b)) return a ^ b;
+ if (a >= 0 && b >= 0 && a <= 0xffffffff && b <= 0xffffffff) return (a ^ b) >>> 0;
+ return fromBig(toBig(a) ^ toBig(b));
+}
+/** Python `~a`. */
+export function bnot(a) {
+ if (typeof a === "bigint") return normint(-a - 1n);
+ return -a - 1;
+}
+/** Python `a << n`. */
+export function shl(a, n) {
+ if (n < 0) throw new ValueError("negative shift count");
+ if (n < 31 && isI32(a)) {
+ const r = a * 2 ** n;
+ if (Number.isSafeInteger(r)) return r;
+ }
+ return fromBig(toBig(a) << toBig(n));
+}
+/** Python `a >> n` (arithmetic, floors). */
+export function shr(a, n) {
+ if (n < 0) throw new ValueError("negative shift count");
+ if (isI32(a)) return n >= 32 ? (a < 0 ? -1 : 0) : a >> n;
+ return fromBig(toBig(a) >> toBig(n));
+}
+/** Python `a // b`. */
+export function floordiv(a, b) {
+ if (b === 0) throw new Error("ZeroDivisionError: integer division or modulo by zero");
+ if (Number.isSafeInteger(a) && Number.isSafeInteger(b)) {
+ const q = Math.floor(a / b);
+ // Guard against rounding in the float division for large operands.
+ if (Math.abs(a) < 2 ** 52 && Math.abs(b) < 2 ** 52) return q;
+ const A = BigInt(a), B = BigInt(b);
+ let r = A / B;
+ if ((A % B !== 0n) && ((A < 0n) !== (B < 0n))) r -= 1n;
+ return Number(r);
+ }
+ return Math.floor(a / b);
+}
+/** Python `a % b` for ints (result has the sign of b). */
+export function pymod(a, b) {
+ if (b === 0) throw new Error("ZeroDivisionError: integer division or modulo by zero");
+ if (Number.isSafeInteger(a) && Number.isSafeInteger(b)) {
+ const r = a % b;
+ return r !== 0 && (r < 0) !== (b < 0) ? r + b : r === 0 ? 0 : r;
+ }
+ const r = a % b;
+ return r !== 0 && (r < 0) !== (b < 0) ? r + b : r;
+}
+/** Python float `%` (math.fmod with divisor sign). */
+export function pyfmod(a, b) {
+ const r = a % b;
+ return r !== 0 && (r < 0) !== (b < 0) ? r + b : r;
+}
+
+/** Python `hex(n)`. */
+export function hex(n) {
+ if (typeof n === "bigint") return n < 0n ? "-0x" + (-n).toString(16) : "0x" + n.toString(16);
+ return n < 0 ? "-0x" + (-n).toString(16) : "0x" + n.toString(16);
+}
+
+/**
+ * Python `int(s, base)`. base 0 honours 0x/0o/0b prefixes (and rejects
+ * leading zeros on decimals, like Python). Underscores between digits allowed.
+ */
+export function int_(s, base = 10) {
+ if (typeof s === "number") {
+ if (!Number.isFinite(s)) throw new ValueError(`cannot convert float ${s} to integer`);
+ return Math.trunc(s);
+ }
+ if (typeof s === "boolean") return s ? 1 : 0;
+ const orig = s;
+ let t = String(s).trim();
+ let neg = false;
+ if (t.startsWith("-")) { neg = true; t = t.slice(1); } else if (t.startsWith("+")) t = t.slice(1);
+ let b = base;
+ const low = t.toLowerCase();
+ if (b === 0) {
+ if (low.startsWith("0x")) { b = 16; t = t.slice(2); }
+ else if (low.startsWith("0o")) { b = 8; t = t.slice(2); }
+ else if (low.startsWith("0b")) { b = 2; t = t.slice(2); }
+ else {
+ b = 10;
+ if (/^0+[1-9_]/.test(t) && !/^0+(_0+)*$/.test(t)) throw new ValueError(`invalid literal for int() with base 0: '${orig}'`);
+ }
+ if (t.startsWith("_")) t = t.slice(1);
+ } else if (b === 16 && low.startsWith("0x")) t = t.slice(2);
+ else if (b === 8 && low.startsWith("0o")) t = t.slice(2);
+ else if (b === 2 && low.startsWith("0b")) t = t.slice(2);
+ if (!t || t.startsWith("_") || t.endsWith("_") || t.includes("__")) throw new ValueError(`invalid literal for int() with base ${base}: '${orig}'`);
+ t = t.replace(/_/g, "");
+ const digits = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, b);
+ for (const c of t.toLowerCase()) if (!digits.includes(c)) throw new ValueError(`invalid literal for int() with base ${base}: '${orig}'`);
+ let v;
+ if (t.length <= 12 || (b === 16 && t.length <= 13)) v = parseInt(t, b);
+ else {
+ let big = 0n;
+ const B = BigInt(b);
+ for (const c of t.toLowerCase()) big = big * B + BigInt(digits.indexOf(c));
+ v = fromBig(neg ? -big : big);
+ return v;
+ }
+ return neg ? -v : v;
+}
+
+/** Python bool(int(...)) style truthiness for common values. */
+export function truthy(x) {
+ if (x === null || x === undefined || x === false || x === 0 || x === "" || x === 0n) return false;
+ if (Array.isArray(x)) return x.length > 0;
+ if (x instanceof Map || x instanceof Set) return x.size > 0;
+ return true;
+}
+
+// ---------------------------------------------------------------- floats
+
+/** Python `repr(float)` / `str(float)`. */
+export function float_repr(x) {
+ if (Number.isNaN(x)) return "nan";
+ if (x === Infinity) return "inf";
+ if (x === -Infinity) return "-inf";
+ if (x === 0) return Object.is(x, -0) ? "-0.0" : "0.0";
+ const e = x.toExponential(); // shortest round-trip digits
+ const m = /^(-?)(\d)(?:\.(\d+))?e([+-]\d+)$/.exec(e);
+ const sign = m[1];
+ const digits = m[2] + (m[3] ?? "");
+ const exp = parseInt(m[4], 10);
+ if (exp < -4 || exp >= 16) {
+ const mant = digits.length > 1 ? digits[0] + "." + digits.slice(1) : digits;
+ const es = Math.abs(exp) < 10 ? "0" + Math.abs(exp) : String(Math.abs(exp));
+ return `${sign}${mant}e${exp < 0 ? "-" : "+"}${es}`;
+ }
+ if (exp < 0) return `${sign}0.${"0".repeat(-exp - 1)}${digits}`;
+ if (digits.length <= exp + 1) return `${sign}${digits}${"0".repeat(exp + 1 - digits.length)}.0`;
+ return `${sign}${digits.slice(0, exp + 1)}.${digits.slice(exp + 1)}`;
+}
+
+/** Python `str()` of a value, as used in f-strings. */
+export function str(x) {
+ if (x === null || x === undefined) return "None";
+ if (x === true) return "True";
+ if (x === false) return "False";
+ if (typeof x === "number") return Number.isInteger(x) && !Object.is(x, -0) && Math.abs(x) < 1e21 && !x.__float ? String(x) : String(x);
+ if (typeof x === "string") return x;
+ if (typeof x === "bigint") return x.toString();
+ if (typeof x.__str__ === "function") return x.__str__();
+ if (Array.isArray(x)) return "[" + x.map(repr).join(", ") + "]";
+ return String(x);
+}
+
+/** Python `repr()` for the simple cases m2c prints. */
+export function repr(x) {
+ if (typeof x === "string") return pyStrRepr(x);
+ if (x === null || x === undefined) return "None";
+ if (x === true) return "True";
+ if (x === false) return "False";
+ if (typeof x === "number") return String(x);
+ if (Array.isArray(x)) return "[" + x.map(repr).join(", ") + "]";
+ if (x && typeof x.__repr__ === "function") return x.__repr__();
+ return str(x);
+}
+
+/** Python repr of a str. */
+export function pyStrRepr(s) {
+ const q = s.includes("'") && !s.includes('"') ? '"' : "'";
+ let out = q;
+ for (const ch of s) {
+ const c = ch.codePointAt(0);
+ if (ch === "\\") out += "\\\\";
+ else if (ch === q) out += "\\" + q;
+ else if (ch === "\n") out += "\\n";
+ else if (ch === "\r") out += "\\r";
+ else if (ch === "\t") out += "\\t";
+ else if (c < 0x20 || c === 0x7f) out += "\\x" + c.toString(16).padStart(2, "0");
+ else if (c >= 0x80 && c < 0xa0) out += "\\x" + c.toString(16).padStart(2, "0");
+ else out += ch;
+ }
+ return out + q;
+}
+
+// Round a non-negative finite float to `prec` digits after the point, as
+// Python's correctly-rounded formatting does (round-half-even on the exact
+// binary value). Returns the digit string (no point) and the exponent shift.
+function exactDecimal(x) {
+ // Exact decimal expansion of a finite double, as [digits, pointPos] where
+ // value = 0.digits * 10^pointPos ... we instead return integer + scale.
+ const buf = new DataView(new ArrayBuffer(8));
+ buf.setFloat64(0, x);
+ const hi = buf.getUint32(0), lo = buf.getUint32(4);
+ const expBits = (hi >>> 20) & 0x7ff;
+ let mant = (BigInt(hi & 0xfffff) << 32n) | BigInt(lo);
+ let e2;
+ if (expBits === 0) e2 = -1074;
+ else { mant |= 1n << 52n; e2 = expBits - 1075; }
+ // value = mant * 2^e2
+ if (e2 >= 0) return { num: mant << BigInt(e2), scale: 0 };
+ // mant * 2^e2 = mant * 5^-e2 / 10^-e2
+ return { num: mant * 5n ** BigInt(-e2), scale: -e2 };
+}
+
+function roundDigits(num, scale, keepScale) {
+ // num / 10^scale, rounded to keepScale decimal places, half-even. Returns BigInt of value*10^keepScale.
+ if (keepScale >= scale) return num * 10n ** BigInt(keepScale - scale);
+ const div = 10n ** BigInt(scale - keepScale);
+ let q = num / div;
+ const r = num % div;
+ const twice = r * 2n;
+ if (twice > div || (twice === div && q % 2n === 1n)) q += 1n;
+ return q;
+}
+
+/** Python `format(x, ".Nf")` for floats. */
+export function format_fixed(x, prec) {
+ if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf";
+ const neg = x < 0 || Object.is(x, -0);
+ const { num, scale } = exactDecimal(Math.abs(x));
+ const q = roundDigits(num, scale, prec);
+ let s = q.toString();
+ if (prec > 0) {
+ s = s.padStart(prec + 1, "0");
+ s = s.slice(0, s.length - prec) + "." + s.slice(s.length - prec);
+ }
+ return (neg ? "-" : "") + s;
+}
+
+/** Python `format(x, ".Ne")` for floats. */
+export function format_exp(x, prec, upper = false) {
+ if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf";
+ const neg = x < 0 || Object.is(x, -0);
+ const ax = Math.abs(x);
+ let digits, exp;
+ if (ax === 0) { digits = "0".repeat(prec + 1); exp = 0; }
+ else {
+ const { num, scale } = exactDecimal(ax);
+ // number of integer digits
+ const intDigits = num.toString().length - scale; // exponent of leading digit + 1
+ exp = intDigits - 1;
+ let q = roundDigits(num, scale, prec - exp);
+ if (q.toString().length > prec + 1) { exp += 1; q = roundDigits(num, scale, prec - exp); }
+ digits = q.toString();
+ }
+ const mant = prec > 0 ? digits[0] + "." + digits.slice(1) : digits;
+ const es = Math.abs(exp) < 10 ? "0" + Math.abs(exp) : String(Math.abs(exp));
+ return (neg ? "-" : "") + mant + (upper ? "E" : "e") + (exp < 0 ? "-" : "+") + es;
+}
+
+/** Python `format(x, ".Ng")` for floats (no '#' flag). */
+export function format_general(x, prec = 6, upper = false) {
+ if (!Number.isFinite(x)) return Number.isNaN(x) ? "nan" : x > 0 ? "inf" : "-inf";
+ if (prec === 0) prec = 1;
+ if (x === 0) return Object.is(x, -0) ? "-0" : "0";
+ const es = format_exp(x, prec - 1);
+ const exp = parseInt(es.slice(es.indexOf("e") + 1), 10);
+ let s;
+ if (exp >= -4 && exp < prec) {
+ s = format_fixed(x, prec - 1 - exp);
+ if (s.includes(".")) s = s.replace(/0+$/, "").replace(/\.$/, "");
+ } else {
+ let [mant, e] = es.split("e");
+ if (mant.includes(".")) mant = mant.replace(/0+$/, "").replace(/\.$/, "");
+ s = mant + "e" + e;
+ }
+ return upper ? s.toUpperCase() : s;
+}
+
+/**
+ * Python `format(value, spec)` for int/float/str values and the common
+ * format-spec features ([[fill]align][sign][#][0][width][,][.precision][type]).
+ */
+export function format(value, spec = "") {
+ if (!spec) return str(value);
+ const m = /^(?:(.)?([<>=^]))?([+\- ])?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/su.exec(spec);
+ if (!m) throw new ValueError(`Invalid format specifier '${spec}'`);
+ let [, fill, align, sign, alt, zero, width, grouping, precision, type] = m;
+ const w = width ? parseInt(width, 10) : 0;
+ const p = precision !== undefined ? parseInt(precision, 10) : undefined;
+ if (zero && !align) { fill = "0"; align = "="; }
+ fill = fill ?? " ";
+ let body, prefix = "", isNum = typeof value === "number" || typeof value === "bigint";
+ if (typeof value === "string") {
+ body = p !== undefined ? value.slice(0, p) : value;
+ align = align ?? "<";
+ } else {
+ let v = value;
+ let neg = false;
+ if (typeof v === "boolean") v = v ? 1 : 0;
+ const t = type ?? (Number.isInteger(v) && !(value && value.__isFloat) ? "d" : "g_repr");
+ if (["d", "x", "X", "o", "b", "c", "n"].includes(t)) {
+ let n = typeof v === "bigint" ? v : BigInt(v);
+ if (n < 0n) { neg = true; n = -n; }
+ if (t === "x") body = n.toString(16);
+ else if (t === "X") body = n.toString(16).toUpperCase();
+ else if (t === "o") body = n.toString(8);
+ else if (t === "b") body = n.toString(2);
+ else if (t === "c") body = String.fromCodePoint(Number(n));
+ else body = n.toString();
+ if (alt) prefix = t === "x" ? "0x" : t === "X" ? "0X" : t === "o" ? "0o" : t === "b" ? "0b" : "";
+ if (grouping) body = body.replace(/\B(?=(\d{3})+(?!\d))/g, grouping);
+ } else {
+ let f = Number(v);
+ if (f < 0 || Object.is(f, -0)) { neg = true; f = -f; }
+ if (t === "f" || t === "F") body = format_fixed(f, p ?? 6);
+ else if (t === "e" || t === "E") body = format_exp(f, p ?? 6, t === "E");
+ else if (t === "g" || t === "G") body = format_general(f, p ?? 6, t === "G");
+ else if (t === "%") body = format_fixed(f * 100, p ?? 6) + "%";
+ else body = p !== undefined ? format_general(f, p) : float_repr(f);
+ if (t === "F" || t === "E" || t === "G") body = body.toUpperCase();
+ }
+ const signStr = neg ? "-" : sign === "+" ? "+" : sign === " " ? " " : "";
+ prefix = signStr + prefix;
+ align = align ?? ">";
+ }
+ const len = [...(prefix + body)].length;
+ if (w <= len) return prefix + body;
+ const pad = w - len;
+ if (align === "=" && isNum) return prefix + fill.repeat(pad) + body;
+ if (align === "<") return prefix + body + fill.repeat(pad);
+ if (align === "^") return fill.repeat(Math.floor(pad / 2)) + prefix + body + fill.repeat(pad - Math.floor(pad / 2));
+ return fill.repeat(pad) + prefix + body;
+}
+
+/** Python `"%..." % args` printf-style formatting (subset). */
+export function percent(fmt, args) {
+ if (!Array.isArray(args)) args = [args];
+ let i = 0;
+ return fmt.replace(/%([-+ #0]*)(\d+|\*)?(?:\.(\d+))?([diouxXeEfFgGcrs%])/g, (_, flags, width, prec, conv) => {
+ if (conv === "%") return "%";
+ let spec = "";
+ if (flags.includes("-")) spec += "<";
+ if (flags.includes("+")) spec += "+";
+ else if (flags.includes(" ")) spec += " ";
+ if (flags.includes("#")) spec += "#";
+ if (flags.includes("0") && !flags.includes("-")) spec += "0";
+ if (width === "*") width = String(args[i++]);
+ if (width) spec += width;
+ if (prec !== undefined) spec += "." + prec;
+ const v = args[i++];
+ if (conv === "s") return format(str(v), spec);
+ if (conv === "r") return format(repr(v), spec);
+ const c = conv === "i" || conv === "u" ? "d" : conv;
+ return format(v, spec + c);
+ });
+}
+
+// ---------------------------------------------------------------- strings
+
+/** Python `str.isspace()`. */
+export function isspace(s) {
+ return s.length > 0 && /^\s+$/u.test(s);
+}
+/** Python `str.isdigit()` (ASCII digits). */
+export function isdigit(s) {
+ return s.length > 0 && /^[0-9]+$/.test(s);
+}
+/** Python `str.isalnum()` (ASCII). */
+export function isalnum(s) {
+ return s.length > 0 && /^[A-Za-z0-9]+$/.test(s);
+}
+/** Python `str.isidentifier()` (ASCII subset). */
+export function isidentifier(s) {
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(s);
+}
+/** Python `str.split()` with no separator. */
+export function split_ws(s, maxsplit = -1) {
+ const out = [];
+ let rest = s.replace(/^\s+/, "");
+ while (rest) {
+ if (maxsplit >= 0 && out.length === maxsplit) { out.push(rest); return out; }
+ const m = /\s/.exec(rest);
+ if (!m) { out.push(rest); break; }
+ out.push(rest.slice(0, m.index));
+ rest = rest.slice(m.index).replace(/^\s+/, "");
+ }
+ return out;
+}
+/** Python `str.split(sep, maxsplit)`. */
+export function split(s, sep, maxsplit = -1) {
+ if (sep === undefined || sep === null) return split_ws(s, maxsplit);
+ const parts = s.split(sep);
+ if (maxsplit < 0 || parts.length <= maxsplit + 1) return parts;
+ return [...parts.slice(0, maxsplit), parts.slice(maxsplit).join(sep)];
+}
+/** Python `str.rsplit(sep, maxsplit)`. */
+export function rsplit(s, sep, maxsplit = -1) {
+ const parts = s.split(sep);
+ if (maxsplit < 0 || parts.length <= maxsplit + 1) return parts;
+ const keep = parts.length - maxsplit;
+ return [parts.slice(0, keep).join(sep), ...parts.slice(keep)];
+}
+/** Python `str.partition(sep)`. */
+export function partition(s, sep) {
+ const i = s.indexOf(sep);
+ if (i < 0) return [s, "", ""];
+ return [s.slice(0, i), sep, s.slice(i + sep.length)];
+}
+/** Python `str.rpartition(sep)`. */
+export function rpartition(s, sep) {
+ const i = s.lastIndexOf(sep);
+ if (i < 0) return ["", "", s];
+ return [s.slice(0, i), sep, s.slice(i + sep.length)];
+}
+const PY_WS = " \t\n\r\x0b\x0c\x1c\x1d\x1e\x1f\x85\xa0";
+function charsSet(chars) {
+ return chars === undefined || chars === null ? null : new Set(chars);
+}
+/** Python `str.strip(chars)`. */
+export function strip(s, chars) {
+ return rstrip(lstrip(s, chars), chars);
+}
+/** Python `str.lstrip(chars)`. */
+export function lstrip(s, chars) {
+ const set = charsSet(chars);
+ let i = 0;
+ while (i < s.length && (set ? set.has(s[i]) : PY_WS.includes(s[i]) || /\s/u.test(s[i]))) i++;
+ return s.slice(i);
+}
+/** Python `str.rstrip(chars)`. */
+export function rstrip(s, chars) {
+ const set = charsSet(chars);
+ let i = s.length;
+ while (i > 0 && (set ? set.has(s[i - 1]) : PY_WS.includes(s[i - 1]) || /\s/u.test(s[i - 1]))) i--;
+ return s.slice(0, i);
+}
+/** Python `str.splitlines()`. */
+export function splitlines(s, keepends = false) {
+ const out = [];
+ const re = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;
+ let last = 0;
+ let m;
+ while ((m = re.exec(s))) {
+ out.push(s.slice(last, keepends ? m.index + m[0].length : m.index));
+ last = m.index + m[0].length;
+ }
+ if (last < s.length) out.push(s.slice(last));
+ return out;
+}
+/** Python `str.count(sub)`. */
+export function count(s, sub) {
+ if (!sub) return s.length + 1;
+ let n = 0;
+ let i = 0;
+ while ((i = s.indexOf(sub, i)) >= 0) { n++; i += sub.length; }
+ return n;
+}
+/** Python slice with negative indices, for strings and arrays. */
+export function slice(x, start, end) {
+ const n = x.length;
+ const norm = (v, d) => (v === undefined || v === null ? d : v < 0 ? Math.max(0, n + v) : Math.min(v, n));
+ return x.slice(norm(start, 0), norm(end, n));
+}
+/** Python `x[i]` with negative index support (throws IndexError). */
+export function at(x, i) {
+ const j = i < 0 ? x.length + i : i;
+ if (j < 0 || j >= x.length) throw new IndexError("index out of range");
+ return x[j];
+}
+
+/** Python `ljust` / `rjust`. */
+export function ljust(s, w, fill = " ") {
+ return s.length >= w ? s : s + fill.repeat(w - s.length);
+}
+export function rjust(s, w, fill = " ") {
+ return s.length >= w ? s : fill.repeat(w - s.length) + s;
+}
+
+// ---------------------------------------------------------------- containers
+
+/** Python `collections.defaultdict` over a Map. */
+export class DefaultMap extends Map {
+ constructor(factory, entries) {
+ super(entries);
+ this.factory = factory;
+ }
+ get(key) {
+ if (!super.has(key)) {
+ const v = this.factory();
+ super.set(key, v);
+ return v;
+ }
+ return super.get(key);
+ }
+ /** Python dict.get(key) on a defaultdict: no insertion; undefined if missing. */
+ peek(key) {
+ return super.get(key);
+ }
+}
+
+/** Python `list.index(x)` raising ValueError. */
+export function list_index(arr, x) {
+ const i = arr.indexOf(x);
+ if (i < 0) throw new ValueError(`${str(x)} is not in list`);
+ return i;
+}
+
+/** Python `max(iterable, key=...)` (first maximal element wins). */
+export function max_by(items, key) {
+ let best, bestK, first = true;
+ for (const it of items) {
+ const k = key(it);
+ if (first || compare(k, bestK) > 0) { best = it; bestK = k; first = false; }
+ }
+ if (first) throw new ValueError("max() arg is an empty sequence");
+ return best;
+}
+/** Python `min(iterable, key=...)` (first minimal element wins). */
+export function min_by(items, key) {
+ let best, bestK, first = true;
+ for (const it of items) {
+ const k = key(it);
+ if (first || compare(k, bestK) < 0) { best = it; bestK = k; first = false; }
+ }
+ if (first) throw new ValueError("min() arg is an empty sequence");
+ return best;
+}
+
+/** Python rich comparison for numbers, strings, booleans, and tuples (arrays). */
+export function compare(a, b) {
+ if (Array.isArray(a) && Array.isArray(b)) {
+ const n = Math.min(a.length, b.length);
+ for (let i = 0; i < n; i++) {
+ const c = compare(a[i], b[i]);
+ if (c !== 0) return c;
+ }
+ return a.length - b.length;
+ }
+ if (typeof a === "boolean") a = a ? 1 : 0;
+ if (typeof b === "boolean") b = b ? 1 : 0;
+ if (a && typeof a.__lt__ === "function") return a.__lt__(b) ? -1 : b.__lt__(a) ? 1 : 0;
+ if (typeof a === "string" && typeof b === "string") {
+ // Python compares by code point.
+ if (a === b) return 0;
+ const n = Math.min(a.length, b.length);
+ for (let i = 0; i < n; i++) {
+ const ca = a.codePointAt(i), cb = b.codePointAt(i);
+ if (ca !== cb) return ca < cb ? -1 : 1;
+ }
+ return a.length - b.length;
+ }
+ if (a === null || a === undefined || b === null || b === undefined) throw new TypeError("'<' not supported with None");
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+/** Python `sorted(items, key=..., reverse=...)` (stable). */
+export function sorted(items, key = (x) => x, reverse = false) {
+ const arr = [...items].map((v, i) => [key(v), i, v]);
+ arr.sort((x, y) => {
+ const c = compare(x[0], y[0]);
+ if (c !== 0) return reverse ? -c : c;
+ return x[1] - y[1];
+ });
+ return arr.map((x) => x[2]);
+}
+
+/** Python `range(...)` as an array. */
+export function range(a, b, step = 1) {
+ if (b === undefined) { b = a; a = 0; }
+ const out = [];
+ if (step > 0) for (let i = a; i < b; i += step) out.push(i);
+ else for (let i = a; i > b; i += step) out.push(i);
+ return out;
+}
+/** Python `zip(a, b, ...)` as an array (truncates to the shortest). */
+export function zip(...arrs) {
+ const n = Math.min(...arrs.map((a) => a.length));
+ const out = [];
+ for (let i = 0; i < n; i++) out.push(arrs.map((a) => a[i]));
+ return out;
+}
+/** Python `enumerate`. */
+export function enumerate(arr, start = 0) {
+ return [...arr].map((v, i) => [i + start, v]);
+}
+/** Python `any` / `all` over an iterable of values. */
+export function any(it) {
+ for (const x of it) if (truthy(x)) return true;
+ return false;
+}
+export function all(it) {
+ for (const x of it) if (!truthy(x)) return false;
+ return true;
+}
+
+// ---------------------------------------------------------------- value interning
+
+let internSeq = 0;
+const internTables = new Map();
+
+/**
+ * Canonicalise a frozen value object: the first instance with a given class
+ * and field key is returned for every later construction, so `===` and Map
+ * keys behave like Python's dataclass __eq__/__hash__.
+ * Call from a constructor as `return intern(this, [fields...])`.
+ */
+export function intern(obj, parts) {
+ const cls = obj.constructor;
+ let table = internTables.get(cls);
+ if (!table) internTables.set(cls, (table = new Map()));
+ const key = parts.map(internKeyPart).join("\u0001");
+ const hit = table.get(key);
+ if (hit) return hit;
+ Object.defineProperty(obj, "__iid", { value: ++internSeq, enumerable: false });
+ table.set(key, obj);
+ return obj;
+}
+function internKeyPart(p) {
+ if (p === null || p === undefined) return "N";
+ switch (typeof p) {
+ case "number": return Object.is(p, -0) ? "n-0" : "n" + p;
+ case "string": return "s" + p;
+ case "boolean": return p ? "T" : "F";
+ case "bigint": return "b" + p;
+ default:
+ if (Array.isArray(p)) return "[" + p.map(internKeyPart).join(",") + "]";
+ if (p.__iid !== undefined) return "#" + p.__iid;
+ if (p.__enum_key !== undefined) return "E" + p.__enum_key;
+ throw new TypeError("intern: unhashable field " + p?.constructor?.name);
+ }
+}
+
+/** Deep copy of plain data / class instances (Python copy.deepcopy). */
+export function deepcopy(x, memo = new Map()) {
+ if (x === null || typeof x !== "object") return x;
+ if (memo.has(x)) return memo.get(x);
+ if (x.__iid !== undefined) return x; // interned immutables
+ if (Array.isArray(x)) {
+ const out = [];
+ memo.set(x, out);
+ for (const v of x) out.push(deepcopy(v, memo));
+ return out;
+ }
+ if (x instanceof Map) {
+ const out = new (x.constructor)();
+ if (x.factory) out.factory = x.factory;
+ memo.set(x, out);
+ for (const [k, v] of x) out.set(deepcopy(k, memo), deepcopy(v, memo));
+ return out;
+ }
+ if (x instanceof Set) {
+ const out = new Set();
+ memo.set(x, out);
+ for (const v of x) out.add(deepcopy(v, memo));
+ return out;
+ }
+ const out = Object.create(Object.getPrototypeOf(x));
+ memo.set(x, out);
+ for (const k of Object.keys(x)) out[k] = deepcopy(x[k], memo);
+ return out;
+}
+
+/** Shallow copy of a class instance (Python copy.copy / dataclasses.replace base). */
+export function shallowcopy(x) {
+ const out = Object.create(Object.getPrototypeOf(x));
+ Object.assign(out, x);
+ return out;
+}
+
+// ---------------------------------------------------------------- Python equality / hashing
+
+const objIds = new WeakMap();
+let nextObjId = 0;
+/** Stable identity number for an object (Python id()). */
+export function objId(o) {
+ let id = objIds.get(o);
+ if (id === undefined) {
+ id = ++nextObjId;
+ objIds.set(o, id);
+ }
+ return id;
+}
+
+/**
+ * A string key that is equal for two values iff Python's `==` holds (and
+ * therefore their hashes agree). Classes opt into structural (dataclass
+ * eq=True) equality with a static `__eq_fields` array naming the compared
+ * fields, or a custom `__pykey()` method; interned values compare by
+ * identity-of-canonical-instance; everything else is identity.
+ */
+export function pykey(x) {
+ if (x === null || x === undefined) return "N";
+ switch (typeof x) {
+ case "number":
+ return "n" + (Object.is(x, -0) ? 0 : x);
+ case "boolean":
+ return x ? "n1" : "n0";
+ case "string":
+ return "s" + x.length + ":" + x;
+ case "bigint":
+ return "n" + x;
+ case "function":
+ return "@" + objId(x);
+ }
+ if (Array.isArray(x)) return "(" + x.map(pykey).join(",") + ")";
+ if (x.__iid !== undefined) return "#" + x.__iid;
+ if (typeof x.__pykey === "function") return x.__pykey();
+ const ctor = x.constructor;
+ if (ctor && Object.prototype.hasOwnProperty.call(ctor, "__eq_fields")) {
+ return ctor.name + "{" + ctor.__eq_fields.map((k) => pykey(x[k])).join(",") + "}";
+ }
+ return "@" + objId(x);
+}
+
+/** Python `a == b`. */
+export function pyeq(a, b) {
+ if (a === b) return true;
+ if (a === null || a === undefined || b === null || b === undefined) return a == b;
+ if (typeof a !== "object" || typeof b !== "object") return a === b || (typeof a === typeof b ? false : pykey(a) === pykey(b));
+ if (typeof a.equals === "function") return a.equals(b);
+ return pykey(a) === pykey(b);
+}
+
+/** Python `x in arr` for a list, with Python equality. */
+export function pyin(x, arr) {
+ for (const y of arr) if (pyeq(x, y)) return true;
+ return false;
+}
+
+/** dict with Python key semantics (see pykey). Map-like API; iteration yields [key, value]. */
+export class PyDict {
+ constructor(entries) {
+ this._m = new Map();
+ if (entries) for (const [k, v] of entries) this.set(k, v);
+ }
+ get size() {
+ return this._m.size;
+ }
+ has(k) {
+ return this._m.has(pykey(k));
+ }
+ get(k) {
+ const e = this._m.get(pykey(k));
+ return e === undefined ? undefined : e[1];
+ }
+ set(k, v) {
+ const key = pykey(k);
+ const e = this._m.get(key);
+ if (e) e[1] = v;
+ else this._m.set(key, [k, v]);
+ return this;
+ }
+ delete(k) {
+ return this._m.delete(pykey(k));
+ }
+ clear() {
+ this._m.clear();
+ }
+ *keys() {
+ for (const e of this._m.values()) yield e[0];
+ }
+ *values() {
+ for (const e of this._m.values()) yield e[1];
+ }
+ *entries() {
+ for (const e of this._m.values()) yield [e[0], e[1]];
+ }
+ [Symbol.iterator]() {
+ return this.entries();
+ }
+}
+
+/** defaultdict with Python key semantics. */
+export class DefaultPyDict extends PyDict {
+ constructor(factory, entries) {
+ super(entries);
+ this.factory = factory;
+ }
+ get(k) {
+ const key = pykey(k);
+ const e = this._m.get(key);
+ if (e) return e[1];
+ const v = this.factory();
+ this._m.set(key, [k, v]);
+ return v;
+ }
+ peek(k) {
+ return super.get(k);
+ }
+}
+
+/** set with Python element semantics (see pykey). Iteration yields elements in insertion order. */
+export class PySet {
+ constructor(items) {
+ this._m = new Map();
+ if (items) for (const x of items) this.add(x);
+ }
+ get size() {
+ return this._m.size;
+ }
+ has(x) {
+ return this._m.has(pykey(x));
+ }
+ add(x) {
+ const key = pykey(x);
+ if (!this._m.has(key)) this._m.set(key, x);
+ return this;
+ }
+ delete(x) {
+ return this._m.delete(pykey(x));
+ }
+ clear() {
+ this._m.clear();
+ }
+ values() {
+ return this._m.values();
+ }
+ [Symbol.iterator]() {
+ return this._m.values();
+ }
+}
+
+// ---------------------------------------------------------------- dataclasses
+
+/** Default-value marker for a dataclass field built by a factory (field(default_factory=...)). */
+export function factory(fn) {
+ return { __factory: fn };
+}
+
+function isKw(x) {
+ return x !== null && typeof x === "object" && Object.getPrototypeOf(x) === Object.prototype;
+}
+
+/**
+ * Python dataclass __init__: `static __fields = [[name], [name, default], [name, factory(fn)]]`
+ * on the class; constructors call `dcinit(this, args)` with their rest args.
+ * Accepts positional args in field order, optionally followed by (or replaced by)
+ * a plain object of keyword args.
+ */
+export function dcinit(self, args) {
+ const fields = self.constructor.__fields;
+ let kw = null;
+ if (args.length && isKw(args[args.length - 1])) {
+ kw = args[args.length - 1];
+ args = args.slice(0, -1);
+ }
+ if (args.length > fields.length) throw new TypeError(`${self.constructor.name}: too many positional arguments`);
+ for (let i = 0; i < fields.length; i++) {
+ const f = fields[i];
+ const name = f[0];
+ let v;
+ if (i < args.length) v = args[i];
+ else if (kw && Object.prototype.hasOwnProperty.call(kw, name)) v = kw[name];
+ else if (f.length < 2) throw new TypeError(`${self.constructor.name}: missing required argument '${name}'`);
+ else v = f[1] !== null && typeof f[1] === "object" && f[1].__factory ? f[1].__factory() : f[1];
+ self[name] = v === undefined ? null : v;
+ }
+ if (kw) for (const k of Object.keys(kw)) if (!fields.some((f) => f[0] === k)) throw new TypeError(`${self.constructor.name}: unexpected keyword argument '${k}'`);
+}
+
+/** dataclasses.replace(obj, **changes) */
+export function dcreplace(obj, changes) {
+ const kw = {};
+ for (const f of obj.constructor.__fields) kw[f[0]] = obj[f[0]];
+ Object.assign(kw, changes);
+ return new obj.constructor(kw);
+}
+
+/** Object.hasOwn for plain-object dicts (Python `key in dict`). */
+export function has(obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key);
+}
+
+/** Python round() (round-half-even) for floats to int. */
+export function pyround(x) {
+ const r = Math.round(x);
+ if (Math.abs(x % 1) === 0.5) return 2 * Math.round(x / 2);
+ return r;
+}
+
+/** Python int.bit_length() */
+export function bit_length(n) {
+ if (n < 0) n = -n;
+ if (n === 0) return 0;
+ if (n < 2 ** 31) return 32 - Math.clz32(n);
+ return BigInt(n).toString(2).length;
+}
diff --git a/packages/romdev-m2c/src/translate.js b/packages/romdev-m2c/src/translate.js
new file mode 100644
index 00000000..b22e7963
--- /dev/null
+++ b/packages/romdev-m2c/src/translate.js
@@ -0,0 +1,3464 @@
+// Port of m2c/translate.py
+/* eslint no-unused-vars: ["error", { "args": "none" }] -- keeps upstream's parameter lists */
+import { ArchC, is_unk_type } from "./c_types.js";
+import { parse as demangle_codewarrior_parse } from "./demangle_codewarrior.js";
+import { DecompFailure, assert_never } from "./error.js";
+import {
+ ArchFlowGraph,
+ BasicNode,
+ ConditionalNode,
+ InstrRef,
+ PrologueRef,
+ ReturnNode,
+ SwitchNode,
+ TerminalNode,
+ locs_clobbered_until_dominator,
+} from "./flow_graph.js";
+import { simplify_ir_patterns } from "./ir_pattern.js";
+import { CodingStyle, Formatter, Options, Target } from "./options.js";
+import { AsmSymbolicData } from "./asm_file.js";
+import { AsmAddressMode, AsmGlobalSymbol, AsmLiteral, BinOp, Macro, Register, RegisterList, Writeback } from "./asm_instruction.js";
+import { Instruction, InstrProcessingFailure, StackLocation, set_current_instr } from "./instruction.js";
+import { FunctionParam, StructDeclaration, Type } from "./types.js";
+import {
+ AssertionError,
+ DefaultMap,
+ DefaultPyDict,
+ PyDict,
+ PySet,
+ ValueError,
+ band,
+ bnot,
+ bor,
+ compare,
+ dcinit,
+ dcreplace,
+ factory,
+ floordiv,
+ float_repr,
+ format,
+ format_exp,
+ format_fixed,
+ format_general,
+ has,
+ hex,
+ int_,
+ objId,
+ pyassert,
+ pyeq,
+ pyin,
+ pymod,
+ rstrip,
+ shl,
+ sorted,
+ str,
+} from "./py.js";
+import { py_float } from "./asm_file.js";
+import { print } from "./io.js";
+
+/** Sort an array in place with a Python-style key (stable). */
+function sort_inplace(arr, key) {
+ const s = sorted(arr, key);
+ arr.splice(0, arr.length, ...s);
+}
+
+/**
+ * Arch-specific information that relates to the translation level. Extends ArchFlowGraph.
+ */
+export class Arch extends ArchFlowGraph {
+ arg_name(loc) {
+ throw new Error("abstract");
+ }
+ function_abi(fn_sig, likely_regs, { for_call }) {
+ throw new Error("abstract");
+ }
+ function_return(expr) {
+ throw new Error("abstract");
+ }
+ is_likely_partial_offset(addend) {
+ return 0 <= addend && addend < 0x1000000 && [0, 2 ** 15 - 1].includes(pymod(addend, 2 ** 15));
+ }
+ c_symbol_name(asm_name) {
+ return asm_name;
+ }
+ simplify_ir(asm_data, flow_graph, { debug_patterns }) {
+ simplify_ir_patterns(this, asm_data, flow_graph, this.ir_patterns, { debug_patterns });
+ }
+}
+Arch.prototype.ir_patterns = [];
+Arch.prototype.base_struct_align = ArchC.prototype.base_struct_align;
+
+export const ASSOCIATIVE_OPS = new Set(["+", "&&", "||", "&", "|", "^", "*"]);
+export const COMPOUND_ASSIGNMENT_OPS = new Set(["+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"]);
+export const PSEUDO_FUNCTION_OPS = new Set(["MULT_HI", "MULTU_HI", "DMULT_HI", "DMULTU_HI", "GLUE_F64", "CLZ"]);
+
+export function as_type(expr, type, silent, { unify = true } = {}) {
+ type = type.weaken_void_ptr();
+ if (expr instanceof Literal) {
+ // For literals we (try to) avoid ever propagating information backwards,
+ // by creating a clone of the literal before casting it.
+ expr = new Literal(expr.value, expr.type.clone_literal_type());
+ unify = true;
+ }
+ const ptr_target_type = type.get_pointer_target();
+ if (unify && expr.type.unify(type)) {
+ if (silent || expr instanceof Literal) return expr;
+ } else if (ptr_target_type !== null) {
+ const ptr_target_type_size = ptr_target_type.get_size_bytes();
+ const [field_path, field_type] = expr.type.get_deref_field(0, { target_size: ptr_target_type_size });
+ if (field_path !== null && field_type.unify(ptr_target_type)) {
+ expr = new AddressOf(
+ new StructAccess({ struct_var: expr, offset: 0, target_size: ptr_target_type_size, field_path, stack_info: null, type: field_type }),
+ { type },
+ );
+ if (silent) return expr;
+ }
+ }
+ return new Cast({ expr, reinterpret: true, silent: false, type });
+}
+
+export function as_f32(expr) {
+ return as_type(expr, Type.f32(), true);
+}
+export function as_f64(expr) {
+ return as_type(expr, Type.f64(), true);
+}
+export function as_sintish(expr, { silent = false } = {}) {
+ return as_type(expr, Type.sintish(), silent);
+}
+export function as_uintish(expr) {
+ return as_type(expr, Type.uintish(), false);
+}
+export function as_s16(expr) {
+ return as_type(expr, Type.s16(), false);
+}
+export function as_u16(expr) {
+ return as_type(expr, Type.u16(), false);
+}
+export function as_u32(expr) {
+ return as_type(expr, Type.u32(), false);
+}
+export function as_s64(expr, { silent = false } = {}) {
+ return as_type(expr, Type.s64(), silent);
+}
+export function as_u64(expr, { silent = false } = {}) {
+ return as_type(expr, Type.u64(), silent);
+}
+export function as_intish(expr) {
+ return as_type(expr, Type.intish(), true);
+}
+export function as_int64(expr) {
+ return as_type(expr, Type.int64(), true);
+}
+export function as_intptr(expr) {
+ return as_type(expr, Type.intptr(), true);
+}
+export function as_ptr(expr) {
+ return as_type(expr, Type.ptr(), true);
+}
+export function as_function_ptr(expr) {
+ return as_type(expr, Type.ptr(Type.function()), true);
+}
+
+/** A persistent Var, that can be merged with other ones using a union-find-based setup. */
+export class PlannedVar {
+ constructor(_parent = null) {
+ this._parent = _parent;
+ }
+ get_representative() {
+ let root = this;
+ const seen = [];
+ while (root._parent !== null) {
+ seen.push(root);
+ root = root._parent;
+ }
+ for (const v of seen) v._parent = root;
+ return root;
+ }
+ join(other) {
+ const a = this.get_representative();
+ const b = other.get_representative();
+ if (a !== b) a._parent = b;
+ }
+}
+
+export const PhiInheritSource = Object.freeze({ DOMINATOR: "DOMINATOR", ANY_PARENT: "ANY_PARENT" });
+
+/** Function state that's persistent between multiple translation passes. */
+export class PersistentFunctionState {
+ constructor() {
+ // (Register, Reference) -> PlannedVar
+ this.planned_vars = new PyDict();
+ // (Register, Node) -> PhiInheritSource
+ this.planned_inherited_phis = new PyDict();
+ }
+}
+
+export class StackInfo {
+ constructor(fn, persistent_state, global_info, flow_graph) {
+ this.function = fn;
+ this.persistent_state = persistent_state;
+ this.global_info = global_info;
+ this.flow_graph = flow_graph;
+ this.warnings = [];
+ this.allocated_stack_size = 0;
+ this.is_leaf = true;
+ this.is_variadic = false;
+ this.frame_pointer_reg = null;
+ this.subroutine_arg_top = 0;
+ this.callee_save_regs = new Set();
+ this.callee_save_reg_region = [0, 0];
+ this.unique_type_map = new PyDict();
+ this.local_vars = [];
+ this.temp_vars = [];
+ this.naive_phi_vars = [];
+ this.reg_vars = new Map();
+ this.planned_vars = new PyDict();
+ this.used_reg_vars = new Set();
+ this.arguments = [];
+ this.temp_name_counter = new Map();
+ this.nonzero_accesses = new PySet();
+ this.param_names = new PyDict();
+ this.stack_pointer_type = null;
+ this.replace_first_arg = null;
+ this.weak_stack_var_types = new Map();
+ this.weak_stack_var_locations = new Set();
+ }
+
+ temp_var(prefix) {
+ const counter = (this.temp_name_counter.get(prefix) ?? 0) + 1;
+ this.temp_name_counter.set(prefix, counter);
+ return prefix + (counter > 1 ? `_${counter}` : "");
+ }
+
+ in_subroutine_arg_region(location) {
+ if (this.global_info.arch.arch === Target.ArchEnum.PPC) return false;
+ if (this.is_leaf) return false;
+ return location < this.subroutine_arg_top;
+ }
+
+ in_callee_save_reg_region(location) {
+ const [lower_bound, upper_bound] = this.callee_save_reg_region;
+ if (lower_bound <= location && location < upper_bound) return true;
+ // PPC saves LR in the header of the previous stack frame
+ if (this.global_info.arch.arch === Target.ArchEnum.PPC && location === this.allocated_stack_size + 4) return true;
+ return false;
+ }
+
+ location_above_stack(location) {
+ return location >= this.allocated_stack_size;
+ }
+
+ add_known_param(loc, name, type) {
+ if (loc.sort_index === 0 && type.is_pointer() && this.replace_first_arg === null) {
+ const namespace = this.function.name.split("_")[0];
+ const base_struct_type = type.get_pointer_target();
+ const self_struct = this.global_info.typepool.get_struct_by_tag_name(namespace, this.global_info.typemap);
+ if (self_struct !== null && base_struct_type !== null && base_struct_type.is_struct()) {
+ const self_struct_type = Type.struct(self_struct);
+ const [field_path, field_type] = self_struct_type.get_field(0, { target_size: base_struct_type.get_size_bytes() });
+ if (field_path !== null && field_type.unify(base_struct_type) && !self_struct_type.unify(base_struct_type)) {
+ this.replace_first_arg = [name || "_self", type];
+ name = name === "thisx" ? "this" : "self";
+ type = Type.ptr(Type.struct(self_struct));
+ }
+ }
+ }
+ if (name) this.param_names.set(loc, name);
+ const arg = this.get_argument(loc);
+ this.arguments.push(arg);
+ sort_inplace(this.arguments, (a) => a.loc);
+ arg.type.unify(type);
+ return type;
+ }
+
+ get_param_name(loc) {
+ return this.param_names.get(loc) ?? null;
+ }
+
+ add_local_var(v) {
+ if (this.local_vars.some((x) => x.value === v.value)) return;
+ this.local_vars.push(v);
+ sort_inplace(this.local_vars, (x) => x.value);
+ }
+
+ add_argument(arg) {
+ for (const a of this.arguments) {
+ if (a.loc.equals(arg.loc)) {
+ if (a.loc.reg === null && arg.loc.reg !== null) {
+ this.arguments.splice(this.arguments.indexOf(a), 1);
+ break;
+ }
+ return;
+ }
+ }
+ this.arguments.push(arg);
+ sort_inplace(this.arguments, (a) => a.loc);
+ }
+
+ get_argument(loc) {
+ return new PassedInArg(loc, { stack_info: this, type: this.unique_type_for("arg", loc, Type.any_reg()) });
+ }
+
+ get_argument_above_stack(offset) {
+ const aligned_offset = band(offset, -4);
+ const loc = new ArgLoc(aligned_offset, null, null);
+ const arg = this.get_argument(loc);
+ if (aligned_offset === offset - 3) return [as_type(arg, Type.int_of_size(8), true), arg];
+ if (aligned_offset === offset - 2) return [as_type(arg, Type.int_of_size(16), true), arg];
+ return [arg, arg];
+ }
+
+ record_struct_access(ptr, location) {
+ if (location) this.nonzero_accesses.add(unwrap_deep(ptr));
+ }
+
+ has_nonzero_access(ptr) {
+ return this.nonzero_accesses.has(unwrap_deep(ptr));
+ }
+
+ unique_type_for(category, key, def) {
+ const k = [category, key];
+ if (!this.unique_type_map.has(k)) this.unique_type_map.set(k, def);
+ return this.unique_type_map.get(k);
+ }
+
+ saved_reg_symbol(reg_name) {
+ const sym_name = "saved_reg_" + reg_name;
+ const type = this.unique_type_for("saved_reg", sym_name, Type.any_reg());
+ return new GlobalSymbol({ c_symbol_name: sym_name, type });
+ }
+
+ should_save(expr, offset) {
+ expr = early_unwrap(expr);
+ if (expr instanceof GlobalSymbol && (expr.c_symbol_name.startsWith("saved_reg_") || expr.c_symbol_name === "sp")) return true;
+ if (expr instanceof PassedInArg && expr.loc.offset !== null && (offset === null || offset === this.allocated_stack_size + expr.loc.offset)) return true;
+ return false;
+ }
+
+ get_stack_var(location, { store }) {
+ if (this.in_callee_save_reg_region(location)) {
+ return new LocalVar(location, { type: Type.any_reg(), path: null });
+ } else if (this.location_above_stack(location)) {
+ const offset = location - this.allocated_stack_size;
+ const [ret, arg] = this.get_argument_above_stack(offset);
+ if (!store) this.add_argument(arg);
+ return ret;
+ } else if (this.in_subroutine_arg_region(location)) {
+ return new SubroutineArg(location, { type: Type.any_reg() });
+ } else {
+ pyassert(this.stack_pointer_type !== null);
+ let [field_path, field_type] = this.stack_pointer_type.get_deref_field(location, { target_size: null });
+
+ const previous_stored_type = this.weak_stack_var_types.get(location) ?? null;
+ if (previous_stored_type !== null) {
+ if (!previous_stored_type.unify(field_type)) this.weak_stack_var_locations.add(location);
+ if (store) field_type = Type.any_field();
+ else field_type = previous_stored_type;
+ }
+ if (store) this.weak_stack_var_types.set(location, field_type);
+ return new LocalVar(location, { type: field_type, path: field_path });
+ }
+ }
+
+ maybe_get_register_var(reg) {
+ return this.reg_vars.get(reg) ?? null;
+ }
+
+ add_register_var(reg, name) {
+ const type = reg.is_float() ? Type.floatish() : Type.intptr();
+ const v = new Var(this, { prefix: `var_${name}`, is_planned: true, type });
+ this.reg_vars.set(reg, v);
+ this.temp_vars.push(v);
+ }
+
+ get_planned_var(reg, source) {
+ const v = this.reg_vars.get(reg) ?? null;
+ if (v && source instanceof InstrRef && source.instruction.function_target === null) return v;
+ return this.planned_vars.get([reg, source]) ?? null;
+ }
+
+ get_persistent_planned_var(reg, source) {
+ let ret = this.persistent_state.planned_vars.get([reg, source]) ?? null;
+ if (!ret) {
+ ret = new PlannedVar();
+ this.persistent_state.planned_vars.set([reg, source], ret);
+ }
+ return ret;
+ }
+
+ add_planned_inherited_phi(node, reg, source) {
+ this.persistent_state.planned_inherited_phis.set([reg, node], source);
+ }
+
+ get_planned_inherited_phi(node, reg) {
+ return this.persistent_state.planned_inherited_phis.get([reg, node]) ?? null;
+ }
+
+ is_stack_reg(reg) {
+ if (reg === this.global_info.arch.stack_pointer_reg) return true;
+ if (reg === this.frame_pointer_reg) return true;
+ return false;
+ }
+
+ /** Reorganize struct information in unique_type_map by var & offset */
+ get_struct_type_map() {
+ const struct_type_map = new PyDict();
+ for (const [[category, key], type] of this.unique_type_map) {
+ if (category !== "struct") continue;
+ const [v, offset] = key;
+ if (!struct_type_map.has(v)) struct_type_map.set(v, new Map());
+ struct_type_map.get(v).set(offset, type);
+ }
+ return struct_type_map;
+ }
+
+ toString() {
+ return [
+ `Stack info for function ${this.function.name}:`,
+ `Allocated stack size: ${this.allocated_stack_size}`,
+ `Leaf? ${this.is_leaf ? "True" : "False"}`,
+ `Bounds of callee-saved vars region: (${this.callee_save_reg_region[0]}, ${this.callee_save_reg_region[1]})`,
+ `Subroutine arg top: ${this.subroutine_arg_top}`,
+ `Callee save registers: {${[...this.callee_save_regs].map((r) => `Register(register_name='${r.register_name}')`).join(", ")}}`,
+ ].join("\n");
+ }
+}
+
+export function get_stack_info(fn, persistent_state, global_info, flow_graph) {
+ const arch = global_info.arch;
+ const info = new StackInfo(fn, persistent_state, global_info, flow_graph);
+
+ const callee_saved_offsets = [];
+ const allowed_callee_save_gaps = new Set();
+ const temp_reg_values = new Map();
+ for (const inst of flow_graph.entry_node().block.instructions) {
+ const arch_mnemonic = inst.arch_mnemonic(arch);
+ if (inst.function_target) {
+ break;
+ } else if (arch_mnemonic === "mips:addiu" && inst.args[0] === arch.stack_pointer_reg) {
+ pyassert(inst.args[2] instanceof AsmLiteral);
+ info.allocated_stack_size = Math.abs(inst.args[2].as_s16());
+ } else if (arch_mnemonic === "mips:subu" && inst.args[0] === arch.stack_pointer_reg && inst.args[1] === arch.stack_pointer_reg && temp_reg_values.has(inst.args[2])) {
+ pyassert(inst.args[2] instanceof Register);
+ info.allocated_stack_size = temp_reg_values.get(inst.args[2]);
+ } else if (arch_mnemonic === "ppc:stwu" && inst.args[0] === arch.stack_pointer_reg) {
+ pyassert(inst.args[1] instanceof AsmAddressMode);
+ pyassert(inst.args[1].addend instanceof AsmLiteral);
+ info.allocated_stack_size = Math.abs(inst.args[1].addend.value);
+ } else if (arch_mnemonic === "arm:push" || arch_mnemonic === "arm:vpush") {
+ pyassert(inst.args[0] instanceof RegisterList);
+ for (const reg of [...inst.args[0].regs].reverse()) {
+ const [tp] = reg.arm_regtype_index();
+ const num_words = { r: 1, s: 1, d: 2, q: 4 }[tp];
+ for (let i = 0; i < num_words; i++) {
+ info.allocated_stack_size += 4;
+ if (arch.saved_regs.includes(reg)) callee_saved_offsets.push(-info.allocated_stack_size);
+ }
+ if (arch.saved_regs.includes(reg)) info.callee_save_regs.add(reg);
+ if (reg === new Register("lr")) info.is_leaf = false;
+ }
+ } else if ((arch_mnemonic === "arm:sub" || arch_mnemonic === "arm:add") && inst.args[0] === arch.stack_pointer_reg && inst.args[1] === arch.stack_pointer_reg && inst.args[2] instanceof AsmLiteral) {
+ const imm = inst.args[2].value * (arch_mnemonic === "arm:add" ? -1 : 1);
+ info.allocated_stack_size += Math.max(imm, 0);
+ } else if (
+ ["mips:move", "arm:mov", "ppc:mr"].includes(arch_mnemonic) &&
+ inst.args[0] instanceof Register &&
+ arch.frame_pointer_regs.includes(inst.args[0]) &&
+ inst.args[1] === arch.stack_pointer_reg
+ ) {
+ info.frame_pointer_reg = inst.args[0];
+ } else if (arch_mnemonic === "sh:mov" && inst.args[0] === arch.stack_pointer_reg && inst.args[1] instanceof Register && arch.frame_pointer_regs.includes(inst.args[1])) {
+ info.frame_pointer_reg = inst.args[1];
+ } else if (arch_mnemonic === "sh:add" && inst.args[0] instanceof AsmLiteral && inst.args[0].as_s8() < 0 && inst.args[1] === arch.stack_pointer_reg) {
+ info.allocated_stack_size += -inst.args[0].as_s8();
+ } else if (
+ (arch_mnemonic === "sh:mov.l" || arch_mnemonic === "sh:sts.l") &&
+ inst.args[0] instanceof Register &&
+ arch.saved_regs.includes(inst.args[0]) &&
+ inst.args[1] instanceof AsmAddressMode &&
+ inst.args[1].base === arch.stack_pointer_reg &&
+ inst.args[1].writeback === Writeback.PRE
+ ) {
+ info.allocated_stack_size += 4;
+ info.callee_save_regs.add(inst.args[0]);
+ callee_saved_offsets.push(-info.allocated_stack_size);
+ if (inst.args[0] === arch.return_address_reg) info.is_leaf = false;
+ } else if (
+ ["mips:sw", "mips:sd", "mips:sq", "mips:swc1", "mips:sdc1", "ppc:stw", "ppc:stmw", "ppc:stfd", "ppc:psq_st"].includes(arch_mnemonic) &&
+ inst.args[0] instanceof Register &&
+ arch.saved_regs.includes(inst.args[0]) &&
+ inst.args[1] instanceof AsmAddressMode &&
+ inst.args[1].base === arch.stack_pointer_reg &&
+ (!info.callee_save_regs.has(inst.args[0]) || arch_mnemonic === "ppc:psq_st")
+ ) {
+ if (inst.args[0] === arch.return_address_reg || inst.args[0] === new Register("r0")) info.is_leaf = false;
+ const n = Math.min(inst.inputs.length, inst.outputs.length);
+ for (let k = 0; k < n; k++) {
+ const inp = inst.inputs[k];
+ const mem = inst.outputs[k];
+ if (inp instanceof Register && mem instanceof StackLocation) {
+ pyassert(mem.symbolic_offset === null);
+ const stack_offset = mem.offset;
+ if (arch_mnemonic !== "ppc:psq_st") info.callee_save_regs.add(inp);
+ callee_saved_offsets.push(stack_offset);
+ if (arch_mnemonic === "mips:sd") allowed_callee_save_gaps.add(stack_offset + 8);
+ if (arch_mnemonic === "mips:swc1") allowed_callee_save_gaps.add(stack_offset + 4);
+ }
+ }
+ } else if (arch_mnemonic === "ppc:mflr" && inst.args[0] === new Register("r0")) {
+ info.is_leaf = false;
+ } else if (arch_mnemonic === "mips:li" && arch.temp_regs.includes(inst.args[0])) {
+ pyassert(inst.args[0] instanceof Register);
+ pyassert(inst.args[1] instanceof AsmLiteral);
+ temp_reg_values.set(inst.args[0], inst.args[1].value);
+ } else if (arch_mnemonic === "mips:ori" && inst.args[0] === inst.args[1] && temp_reg_values.has(inst.args[0])) {
+ pyassert(inst.args[0] instanceof Register);
+ pyassert(inst.args[2] instanceof AsmLiteral);
+ temp_reg_values.set(inst.args[0], bor(temp_reg_values.get(inst.args[0]), inst.args[2].value));
+ }
+ }
+
+ if (arch.arch === Target.ArchEnum.ARM || arch.arch === Target.ArchEnum.SH) {
+ for (let i = 0; i < callee_saved_offsets.length; i++) callee_saved_offsets[i] += info.allocated_stack_size;
+ }
+
+ if (!info.is_leaf) {
+ info.subroutine_arg_top = info.allocated_stack_size;
+ for (const node of flow_graph.nodes) {
+ for (const inst of node.block.instructions) {
+ const arch_mnemonic = inst.arch_mnemonic(arch);
+ if (inst.is_load) {
+ for (const arg of inst.args) {
+ if (arg instanceof AsmAddressMode && info.is_stack_reg(arg.base) && arg.addend instanceof AsmLiteral) {
+ const offset = band(arg.addend.value, -4);
+ if (offset >= arch.home_space_size) info.subroutine_arg_top = Math.min(info.subroutine_arg_top, offset);
+ }
+ }
+ }
+ if (
+ ["mips:addiu", "ppc:addi", "arm:add"].includes(arch_mnemonic) &&
+ inst.args[1] instanceof Register &&
+ info.is_stack_reg(inst.args[1]) &&
+ inst.args[0] instanceof Register &&
+ !info.is_stack_reg(inst.args[0]) &&
+ inst.args[2] instanceof AsmLiteral &&
+ inst.args[2].value < info.allocated_stack_size
+ ) {
+ info.subroutine_arg_top = Math.min(info.subroutine_arg_top, inst.args[2].value);
+ }
+ if (arch_mnemonic === "arm:mov" && inst.args[1] instanceof Register && info.is_stack_reg(inst.args[1]) && inst.args[0] instanceof Register && !info.is_stack_reg(inst.args[0])) {
+ info.subroutine_arg_top = 0;
+ }
+ }
+ }
+ }
+
+ if (callee_saved_offsets.length) {
+ callee_saved_offsets.sort((a, b) => a - b);
+ const bottom = callee_saved_offsets[0];
+ let top = bottom;
+ let internal_padding_added = false;
+ let has_warned = false;
+ for (const offset of callee_saved_offsets) {
+ while (top < offset && allowed_callee_save_gaps.has(top)) top += 4;
+ if (offset !== top) {
+ if (!internal_padding_added && offset === top + 4) internal_padding_added = true;
+ else if (!has_warned) {
+ has_warned = true;
+ info.warnings.push(`Gap in callee-saved word stack region.\n` + `Saved: [${callee_saved_offsets.map((o) => hex(o)).join(", ")}], ` + `gap at: ${hex(top)}.`);
+ }
+ }
+ top = offset + 4;
+ }
+ info.callee_save_reg_region = [bottom, top];
+ info.subroutine_arg_top = Math.min(info.subroutine_arg_top, bottom);
+ }
+
+ const stack_struct_name = `_m2c_stack_${fn.name}`;
+ let stack_struct = global_info.typepool.get_struct_by_tag_name(stack_struct_name, global_info.typemap);
+ if (stack_struct !== null) {
+ if (stack_struct.size !== info.allocated_stack_size) {
+ throw new DecompFailure(
+ `Function ${fn.name} has a provided stack type ${stack_struct_name} ` + `with size ${stack_struct.size}, but the detected stack size was ` + `${info.allocated_stack_size}.`,
+ );
+ }
+ } else {
+ stack_struct = StructDeclaration.unknown(global_info.typepool, info.allocated_stack_size, stack_struct_name);
+ }
+ stack_struct.is_stack = true;
+ stack_struct.new_field_prefix = "sp";
+ info.stack_pointer_type = Type.ptr(Type.struct(stack_struct));
+ return info;
+}
+
+export function format_hex(val) {
+ return format(val, "x").toUpperCase();
+}
+
+const ESCAPE_TABLE = new Map([
+ [0, "\\0"],
+ [8, "\\b"],
+ [12, "\\f"],
+ [10, "\\n"],
+ [13, "\\r"],
+ [9, "\\t"],
+ [11, "\\v"],
+ [0x5c, "\\\\"],
+ [0x22, '\\"'],
+]);
+
+/** Returns the escaped byte as an array of byte values. */
+export function escape_byte(b) {
+ if (ESCAPE_TABLE.has(b)) return [...ESCAPE_TABLE.get(b)].map((c) => c.charCodeAt(0));
+ if (b < 0x20 || b === 0xff || b === 0x7f) return [..."\\x" + b.toString(16).padStart(2, "0")].map((c) => c.charCodeAt(0));
+ return [b];
+}
+
+export class Var {
+ static __fields = [["stack_info"], ["prefix"], ["is_planned"], ["type"], ["is_emitted", false], ["name", null], ["debug_exprs", factory(() => [])]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ format(fmt) {
+ pyassert(this.is_emitted);
+ if (this.name === null) this.name = this.stack_info.temp_var(this.prefix);
+ return this.name;
+ }
+ toString() {
+ return ``;
+ }
+}
+
+export class Expression {
+ dependencies() {
+ throw new Error("abstract");
+ }
+ /** Mark an expression as "will occur in the output". */
+ use() {
+ for (const expr of this.dependencies()) expr.use();
+ }
+ format(fmt) {
+ throw new Error("abstract");
+ }
+ toString() {
+ const fmt = new Formatter({ debug: true });
+ return '"' + this.format(fmt) + '"';
+ }
+}
+
+export class Condition extends Expression {
+ negated() {
+ throw new Error("abstract");
+ }
+}
+
+export class Statement {
+ should_write() {
+ throw new Error("abstract");
+ }
+ format(fmt) {
+ throw new Error("abstract");
+ }
+ toString() {
+ const fmt = new Formatter({ debug: true });
+ return '"' + this.format(fmt) + '"';
+ }
+}
+
+export class ErrorExpr extends Condition {
+ static __fields = [["desc", null], ["type", factory(() => Type.any_reg())]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ negated() {
+ return this;
+ }
+ format(fmt) {
+ if (this.desc !== null) return `M2C_ERROR(/* ${this.desc} */)`;
+ return "M2C_ERROR()";
+ }
+}
+
+export class CommentExpr extends Expression {
+ static __fields = [["expr"], ["type"], ["prefix", null], ["suffix", null]];
+ static __eq_fields = ["expr", "prefix", "suffix"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.expr];
+ }
+ format(fmt) {
+ const expr_str = this.expr.format(fmt);
+ if (fmt.coding_style.comment_style === CodingStyle.CommentStyle.NONE) return expr_str;
+ const prefix_str = this.prefix !== null ? `/* ${this.prefix} */ ` : "";
+ const suffix_str = this.suffix !== null ? ` /* ${this.suffix} */` : "";
+ return `${prefix_str}${expr_str}${suffix_str}`;
+ }
+ static wrap(expr, prefix = null, suffix = null) {
+ if (prefix === null && suffix === null) return expr;
+ return new CommentExpr({ expr, type: expr.type, prefix, suffix });
+ }
+}
+
+export class SecondF64Half extends Expression {
+ static __fields = [["type", factory(() => Type.any_reg())]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ format(fmt) {
+ return "(second half of f64)";
+ }
+}
+
+export class CarryBit extends Expression {
+ static __fields = [["expr", null], ["type", factory(() => Type.intish())]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return this.expr !== null ? [this.expr] : [];
+ }
+ format(fmt) {
+ if (this.expr !== null) return `M2C_CARRY(${this.expr.format(fmt)})`;
+ return "M2C_CARRY";
+ }
+}
+
+function swap_lt_gt(op) {
+ return [...op].map((c) => (c === "<" ? ">" : c === ">" ? "<" : c)).join("");
+}
+
+export class BinaryOp extends Condition {
+ static __fields = [["left"], ["op"], ["right"], ["type"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ static int(left, op, right) {
+ return new BinaryOp({ left: as_intish(left), op, right: as_intish(right), type: Type.intish() });
+ }
+ static int64(left, op, right) {
+ return new BinaryOp({ left: as_int64(left), op, right: as_int64(right), type: Type.int64() });
+ }
+ static intptr(left, op, right) {
+ return new BinaryOp({ left: as_intptr(left), op, right: as_intptr(right), type: Type.intptr() });
+ }
+ static icmp(left, op, right) {
+ return new BinaryOp({ left: as_intptr(left), op, right: as_intptr(right), type: Type.boolean() });
+ }
+ static scmp(left, op, right) {
+ return new BinaryOp({ left: as_sintish(left, { silent: true }), op, right: as_sintish(right, { silent: true }), type: Type.boolean() });
+ }
+ static sintptr_cmp(left, op, right) {
+ return new BinaryOp({ left: as_type(left, Type.sintptr(), false), op, right: as_type(right, Type.sintptr(), false), type: Type.boolean() });
+ }
+ static ucmp(left, op, right) {
+ return new BinaryOp({ left: as_uintish(left), op, right: as_uintish(right), type: Type.boolean() });
+ }
+ static uintptr_cmp(left, op, right) {
+ return new BinaryOp({ left: as_type(left, Type.uintptr(), false), op, right: as_type(right, Type.uintptr(), false), type: Type.boolean() });
+ }
+ static fcmp(left, op, right) {
+ return new BinaryOp({ left: as_f32(left), op, right: as_f32(right), type: Type.boolean() });
+ }
+ static dcmp(left, op, right) {
+ return new BinaryOp({ left: as_f64(left), op, right: as_f64(right), type: Type.boolean() });
+ }
+ static sint(left, op, right, { silent = false } = {}) {
+ return new BinaryOp({ left: as_sintish(left, { silent }), op, right: as_sintish(right, { silent }), type: Type.s32() });
+ }
+ static uint(left, op, right) {
+ return new BinaryOp({ left: as_uintish(left), op, right: as_uintish(right), type: Type.u32() });
+ }
+ static sshift(left, op, right) {
+ return new BinaryOp({ left: as_sintish(left), op, right: as_intish(right), type: Type.s32() });
+ }
+ static ushift(left, op, right) {
+ return new BinaryOp({ left: as_uintish(left), op, right: as_intish(right), type: Type.u32() });
+ }
+ static s64(left, op, right) {
+ return new BinaryOp({ left: as_s64(left), op, right: as_s64(right), type: Type.s64() });
+ }
+ static u64(left, op, right) {
+ return new BinaryOp({ left: as_u64(left), op, right: as_u64(right), type: Type.u64() });
+ }
+ static f32(left, op, right) {
+ return new BinaryOp({ left: as_f32(left), op, right: as_f32(right), type: Type.f32() });
+ }
+ static f64(left, op, right) {
+ return new BinaryOp({ left: as_f64(left), op, right: as_f64(right), type: Type.f64() });
+ }
+
+ is_comparison() {
+ return ["==", "!=", ">", "<", ">=", "<="].includes(this.op);
+ }
+ is_floating() {
+ return this.left.type.is_float() && this.right.type.is_float();
+ }
+ negated() {
+ if ((this.op === "&&" || this.op === "||") && this.left instanceof Condition && this.right instanceof Condition) {
+ return new BinaryOp({ left: this.left.negated(), op: { "&&": "||", "||": "&&" }[this.op], right: this.right.negated(), type: Type.boolean() });
+ }
+ if (!this.is_comparison() || (this.is_floating() && ["<", ">", "<=", ">="].includes(this.op))) {
+ return new UnaryOp("!", this, { type: Type.boolean() });
+ }
+ return new BinaryOp({ left: this.left, op: { "==": "!=", "!=": "==", ">": "<=", "<": ">=", ">=": "<", "<=": ">" }[this.op], right: this.right, type: Type.boolean() });
+ }
+ dependencies() {
+ return [this.left, this.right];
+ }
+ normalize_for_formatting() {
+ const right_expr = late_unwrap(this.right);
+ if (!this.is_floating() && right_expr instanceof Literal && right_expr.value < 0) {
+ if (this.op === "+") {
+ const neg = new Literal({ value: -right_expr.value, type: right_expr.type });
+ return new BinaryOp({ op: "-", left: this.left, right: neg, type: this.type });
+ }
+ if (this.op === "&" || this.op === "|") {
+ const neg = new Literal({ value: bnot(right_expr.value), type: right_expr.type });
+ const right = new UnaryOp("~", neg, { type: Type.any_reg() });
+ return new BinaryOp({ op: this.op, left: this.left, right, type: this.type });
+ }
+ }
+ return this;
+ }
+ format(fmt) {
+ const left_expr = late_unwrap(this.left);
+ let right_expr = late_unwrap(this.right);
+
+ const adj = this.normalize_for_formatting();
+ if (adj !== this) return adj.format(fmt);
+
+ if (this.is_comparison() && left_expr instanceof Literal && !(right_expr instanceof Literal)) {
+ return new BinaryOp({ left: right_expr, op: swap_lt_gt(this.op), right: left_expr, type: this.type }).format(fmt);
+ }
+
+ if ((this.op === "==" || this.op === "!=") && right_expr instanceof Literal) {
+ right_expr = elide_literal_casts(as_type(right_expr, left_expr.type, true));
+ }
+
+ let lhs = left_expr.format(fmt);
+ if (left_expr instanceof BinaryOp && left_expr.op === this.op && ASSOCIATIVE_OPS.has(this.op)) lhs = lhs.slice(1, -1);
+
+ let rhs;
+ if ((this.op === "/" || this.op === "%") && right_expr instanceof Literal) rhs = right_expr.format(fmt, true);
+ else rhs = right_expr.format(fmt);
+
+ if (PSEUDO_FUNCTION_OPS.has(this.op)) return `${this.op}(${lhs}, ${rhs})`;
+ return `(${lhs} ${this.op} ${rhs})`;
+ }
+}
+
+export class TernaryOp extends Expression {
+ static __fields = [["cond"], ["left"], ["right"], ["type"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.cond, this.left, this.right];
+ }
+ format(fmt) {
+ const cond_str = simplify_condition(this.cond).format(fmt);
+ const left_str = this.left.format(fmt);
+ const right_str = this.right.format(fmt);
+ return `(${cond_str} ? ${left_str} : ${right_str})`;
+ }
+}
+
+export class UnaryOp extends Condition {
+ static __fields = [["op"], ["expr"], ["type"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.expr];
+ }
+ static int(op, expr) {
+ return new UnaryOp({ op, expr: as_intish(expr), type: expr.type });
+ }
+ static sint(op, expr) {
+ expr = as_sintish(expr, { silent: true });
+ return new UnaryOp({ op, expr, type: expr.type });
+ }
+ negated() {
+ if (this.op === "!" && (this.expr instanceof UnaryOp || this.expr instanceof BinaryOp)) return this.expr;
+ return new UnaryOp("!", this, { type: Type.boolean() });
+ }
+ format(fmt) {
+ if (PSEUDO_FUNCTION_OPS.has(this.op)) return `${this.op}(${format_expr(this.expr, fmt)})`;
+ return `${this.op}${this.expr.format(fmt)}`;
+ }
+}
+
+export class ExprCondition extends Condition {
+ static __fields = [["expr"], ["type"], ["is_negated", false]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.expr];
+ }
+ negated() {
+ return new ExprCondition(this.expr, this.type, !this.is_negated);
+ }
+ format(fmt) {
+ const neg = this.is_negated ? "!" : "";
+ return `${neg}${this.expr.format(fmt)}`;
+ }
+}
+
+const COMMA_CONDITION_DEFAULT_TYPE = Type.boolean();
+
+export class CommaConditionExpr extends Condition {
+ static __fields = [["statements"], ["condition"], ["type", COMMA_CONDITION_DEFAULT_TYPE]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ pyassert(false, "CommaConditionExpr should not be used within translate.py");
+ return [];
+ }
+ negated() {
+ return new CommaConditionExpr(this.statements, this.condition.negated());
+ }
+ format(fmt) {
+ const comma_joined = this.statements.map((stmt) => rstrip(stmt.format(fmt), ";")).join(", ");
+ return `(${comma_joined}, ${this.condition.format(fmt)})`;
+ }
+}
+
+export class Cast extends Expression {
+ static __fields = [["expr"], ["type"], ["reinterpret", false], ["silent", true]];
+ static __eq_fields = ["expr", "reinterpret", "silent"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.expr];
+ }
+ use() {
+ this.expr.type.unify(this.type);
+ super.use();
+ }
+ needed_for_store() {
+ if (!this.reinterpret) return true;
+ if (!this.expr.type.unify(this.type)) return true;
+ return false;
+ }
+ should_wrap_transparently() {
+ return this.reinterpret && this.expr.type.is_float() === this.type.is_float() && should_wrap_transparently(this.expr);
+ }
+ format(fmt) {
+ if (this.reinterpret && this.expr.type.is_float() !== this.type.is_float()) {
+ if (fmt.valid_syntax) return `M2C_BITWISE(${this.type.format(fmt)}, ${this.expr.format(fmt)})`;
+ return `(bitwise ${this.type.format(fmt)}) ${this.expr.format(fmt)}`;
+ }
+ if (this.reinterpret && (this.silent || (is_type_obvious(this.expr) && this.expr.type.unify(this.type)))) return this.expr.format(fmt);
+ if (fmt.skip_casts) return this.expr.format(fmt);
+ const fn_sig = this.type.get_function_pointer_signature();
+ if (fn_sig) return `((${this.type.format(fmt)}) ${this.expr.format(fmt)})`;
+ return `(${this.type.format(fmt)}) ${this.expr.format(fmt)}`;
+ }
+}
+
+export class FuncCall extends Expression {
+ static __fields = [["function"], ["args"], ["type"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [...this.args, this.function];
+ }
+ format(fmt) {
+ const target = late_unwrap(this.function);
+ const fn_sig = target.type.get_function_pointer_signature();
+ if (fn_sig && target instanceof Cast && target.reinterpret) {
+ const prototype_sig = target.expr.type.get_function_pointer_signature();
+ if (prototype_sig && prototype_sig.unify_with_args(fn_sig)) {
+ return new Cast(new FuncCall(target.expr, this.args, prototype_sig.return_type), this.type, { reinterpret: true, silent: true }).format(fmt);
+ }
+ }
+ const args = this.args.map((arg) => format_expr(arg, fmt)).join(", ");
+ return `${target.format(fmt)}(${args})`;
+ }
+}
+
+export class LocalVar extends Expression {
+ static __fields = [["value"], ["type"], ["path"]];
+ static __eq_fields = ["value"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ format(fmt) {
+ const fallback_name = `unksp${format_hex(this.value)}`;
+ if (this.path === null) return fallback_name;
+ const name = StructAccess.access_path_to_field_name(this.path, fmt);
+ if (name.startsWith("->")) return name.slice(2);
+ return fallback_name;
+ }
+ /** Return a declaration for this LocalVar, if required. */
+ toplevel_decl(fmt) {
+ if (this.path === null || this.path.length !== 2 || typeof this.path[1] !== "string") return null;
+ return this.type.to_decl(this.path[1], fmt);
+ }
+}
+
+export class PlannedPhiExpr extends Expression {
+ static __fields = [["var"], ["type"], ["sources"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ format(fmt) {
+ return this.var.format(fmt);
+ }
+}
+
+export class PassedInArg extends Expression {
+ static __fields = [["loc"], ["stack_info"], ["type"]];
+ static __eq_fields = ["loc"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ format(fmt) {
+ const name = this.stack_info.get_param_name(this.loc);
+ if (name) return name;
+ return this.stack_info.global_info.arch.arg_name(this.loc);
+ }
+}
+
+export class SubroutineArg extends Expression {
+ static __fields = [["value"], ["type"]];
+ static __eq_fields = ["value"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ format(fmt) {
+ return `subroutine_arg${format_hex(floordiv(this.value, 4))}`;
+ }
+}
+
+/**
+ * Represents struct_var->offset. eq=True since it represents a live expression.
+ */
+export class StructAccess extends Expression {
+ static __fields = [["struct_var"], ["offset"], ["target_size"], ["field_path"], ["stack_info"], ["type"], ["checked_late_field_path", false]];
+ static __eq_fields = ["struct_var", "offset", "target_size"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ pyassert(this.stack_info !== null || this.field_path !== null, "Must provide at least one of (stack_info, field_path)");
+ StructAccess.assert_valid_field_path(this.field_path);
+ }
+ static assert_valid_field_path(path) {
+ pyassert(path === null || (path.length && typeof path[0] === "number"), "The first element of the field path, if present, must be an int");
+ }
+ /** Convert an access path into a dereferencing field name. */
+ static access_path_to_field_name(path, fmt) {
+ StructAccess.assert_valid_field_path(path);
+ let output = "";
+ if (path.length >= 2 && path[0] === 0 && typeof path[1] === "string") {
+ output += `->${path[1]}`;
+ path = path.slice(2);
+ }
+ for (const p of path) {
+ if (typeof p === "string") output += `.${p}`;
+ else if (typeof p === "number") output += `[${fmt.format_int(p)}]`;
+ else assert_never(p);
+ }
+ return output;
+ }
+ dependencies() {
+ return [this.struct_var];
+ }
+ make_reference() {
+ const field_path = this.late_field_path();
+ if (field_path && field_path.length >= 2 && field_path[field_path.length - 1] === 0) return dcreplace(this, { field_path: field_path.slice(0, -1) });
+ return null;
+ }
+ late_field_path() {
+ if (this.field_path === null && !this.checked_late_field_path) {
+ const v = late_unwrap(this.struct_var);
+ v.format(new Formatter());
+ const [field_path, field_type] = v.type.get_deref_field(this.offset, { target_size: this.target_size });
+ if (field_path !== null) {
+ StructAccess.assert_valid_field_path(field_path);
+ this.field_path = field_path;
+ this.type.unify(field_type);
+ }
+ this.checked_late_field_path = true;
+ }
+ return this.field_path;
+ }
+ late_has_known_type() {
+ if (this.late_field_path() !== null) return true;
+ pyassert(this.stack_info !== null, "StructAccess must have stack_info if field_path isn't set");
+ if (this.offset === 0) {
+ const v = late_unwrap(this.struct_var);
+ if (!this.stack_info.has_nonzero_access(v) && v instanceof AddressOf && v.expr instanceof GlobalSymbol && v.expr.type_provided) return true;
+ }
+ return false;
+ }
+ format(fmt) {
+ let v = late_unwrap(this.struct_var);
+ let has_nonzero_access = false;
+ if (this.stack_info !== null) has_nonzero_access = this.stack_info.has_nonzero_access(v);
+
+ let field_path = this.late_field_path();
+
+ if (field_path !== null && !(field_path.length === 1 && field_path[0] === 0)) {
+ has_nonzero_access = true;
+ } else if (fmt.valid_syntax && (this.offset !== 0 || has_nonzero_access)) {
+ const offset_str = fmt.format_int(this.offset);
+ return `M2C_FIELD(${v.format(fmt)}, ${Type.ptr(this.type).format(fmt)}, ${offset_str})`;
+ } else {
+ const prefix = "unk" + (fmt.coding_style.unknown_underscore ? "_" : "");
+ field_path = [0, prefix + format_hex(this.offset)];
+ }
+ let field_name = StructAccess.access_path_to_field_name(field_path, fmt);
+
+ let deref = true;
+ if (v instanceof AddressOf && !v.expr.type.is_array() && !(v.expr instanceof GlobalSymbol && v.expr.is_string_constant()) && field_name.startsWith("->")) {
+ v = v.expr;
+ field_name = field_name.replace("->", ".");
+ deref = false;
+ }
+
+ if (this.offset === 0 && !has_nonzero_access) return `${deref ? "*" : ""}${v.format(fmt)}`;
+ return `${parenthesize_for_struct_access(v, fmt)}${field_name}`;
+ }
+}
+
+export class ArrayAccess extends Expression {
+ static __fields = [["ptr"], ["index"], ["type"]];
+ static __eq_fields = ["ptr", "index"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.ptr, this.index];
+ }
+ format(fmt) {
+ const base = parenthesize_for_struct_access(this.ptr, fmt);
+ const index = format_expr(this.index, fmt);
+ return `${base}[${index}]`;
+ }
+}
+
+export class GlobalSymbol extends Expression {
+ static __fields = [
+ ["c_symbol_name"],
+ ["type"],
+ ["asm_data_entry", null],
+ ["symbol_in_context", false],
+ ["type_provided", false],
+ ["initializer_in_typemap", false],
+ ["demangled_str", null],
+ ["is_referenced", false],
+ ];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ use() {
+ this.is_referenced = true;
+ }
+ is_string_constant() {
+ const ent = this.asm_data_entry;
+ if (!ent || ent.data.length !== 1 || !(ent.data[0] instanceof Uint8Array)) return false;
+ return ent.is_string;
+ }
+ format_string_constant(fmt) {
+ pyassert(this.is_string_constant(), "checked by caller");
+ let has_trailing_null = false;
+ let data = this.asm_data_entry.data[0];
+ let end = data.length;
+ while (end > 0 && data[end - 1] === 0) {
+ end -= 1;
+ has_trailing_null = true;
+ }
+ const escaped = [];
+ for (let i = 0; i < end; i++) escaped.push(...escape_byte(data[i]));
+ const strdata = decode_utf8_backslashreplace(Uint8Array.from(escaped));
+ let ret = `"${strdata}"`;
+ if (!has_trailing_null) ret += " /* not null-terminated */";
+ return ret;
+ }
+ format(fmt) {
+ return this.c_symbol_name;
+ }
+ /** Returns [array_dim, extra_bytes]. */
+ potential_array_dim(element_size) {
+ pyassert(element_size !== 0, "potential_array_dim cannot be called on zero size");
+ if (this.asm_data_entry === null || this.asm_data_entry.is_jtbl) return [0, element_size];
+ const [min_data_size, max_data_size] = this.asm_data_entry.size_range_bytes();
+ if (element_size > max_data_size) return [0, max_data_size];
+ if (min_data_size <= element_size && element_size <= max_data_size && !this.type.is_array()) return [1, 0];
+ const array_dim = floordiv(min_data_size, element_size);
+ const extra_bytes = pymod(min_data_size, element_size);
+ if (extra_bytes !== 0) {
+ const padding_bytes = element_size - extra_bytes;
+ if (min_data_size + padding_bytes > max_data_size) return [array_dim, extra_bytes];
+ }
+ return [floordiv(max_data_size, element_size), 0];
+ }
+}
+
+/** bytes.decode("utf-8", "backslashreplace") */
+export function decode_utf8_backslashreplace(bytes) {
+ let out = "";
+ let i = 0;
+ while (i < bytes.length) {
+ const b = bytes[i];
+ let n = 0;
+ let cp = 0;
+ if (b < 0x80) {
+ out += String.fromCharCode(b);
+ i++;
+ continue;
+ } else if (b >= 0xc2 && b <= 0xdf) {
+ n = 1;
+ cp = b & 0x1f;
+ } else if (b >= 0xe0 && b <= 0xef) {
+ n = 2;
+ cp = b & 0x0f;
+ } else if (b >= 0xf0 && b <= 0xf4) {
+ n = 3;
+ cp = b & 0x07;
+ } else {
+ out += "\\x" + b.toString(16).padStart(2, "0");
+ i++;
+ continue;
+ }
+ let ok = i + n < bytes.length + 0 && i + n <= bytes.length - 1 + 1;
+ let j = 1;
+ for (; j <= n; j++) {
+ const c = bytes[i + j];
+ if (c === undefined || (c & 0xc0) !== 0x80) {
+ ok = false;
+ break;
+ }
+ // Reject overlongs / surrogates / out of range like CPython's decoder
+ if (j === 1) {
+ if (b === 0xe0 && c < 0xa0) ok = false;
+ if (b === 0xed && c > 0x9f) ok = false;
+ if (b === 0xf0 && c < 0x90) ok = false;
+ if (b === 0xf4 && c > 0x8f) ok = false;
+ if (!ok) break;
+ }
+ cp = (cp << 6) | (c & 0x3f);
+ }
+ if (!ok || j <= n) {
+ out += "\\x" + b.toString(16).padStart(2, "0");
+ i++;
+ continue;
+ }
+ out += String.fromCodePoint(cp);
+ i += n + 1;
+ }
+ return out;
+}
+
+export class Literal extends Expression {
+ static __fields = [["value"], ["type", factory(() => Type.any())], ["elide_cast", false]];
+ static __eq_fields = ["value"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ format(fmt, force_dec = false) {
+ const enum_name = this.type.get_enum_name(this.value);
+ if (enum_name !== null) return enum_name;
+
+ if (this.type.is_likely_float()) {
+ if (this.type.get_size_bits() === 64) return format_f64_imm(this.value);
+ return format_f32_imm(this.value) + "f";
+ }
+ if (this.type.is_pointer() && this.value === 0) return "NULL";
+
+ let prefix = "";
+ let suffix = "";
+ if (!fmt.skip_casts && !this.elide_cast) {
+ if (this.type.is_pointer()) prefix = `(${this.type.format(fmt)})`;
+ if (this.type.is_unsigned()) suffix = "U";
+ }
+
+ let value;
+ if (force_dec) value = str(this.value);
+ else {
+ const size_bits = this.type.get_size_bits();
+ let v = this.value;
+ if (this.type.is_signed() && size_bits && band(v, shl(1, size_bits - 1)) && v > shl(3, size_bits - 2) && v < 2 ** size_bits) {
+ v -= shl(1, size_bits);
+ }
+ value = fmt.format_int(v, size_bits);
+ }
+ return prefix + value + suffix;
+ }
+}
+
+export class AddressOf extends Expression {
+ static __fields = [["expr"], ["type", factory(() => Type.ptr())]];
+ static __eq_fields = ["expr"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.expr];
+ }
+ format(fmt) {
+ if (this.expr instanceof GlobalSymbol) {
+ if (this.expr.is_string_constant()) return this.expr.format_string_constant(fmt);
+ }
+ if (this.expr.type.is_array()) return `${this.expr.format(fmt)}`;
+ if (this.expr.type.is_function()) return `${this.expr.format(fmt)}`;
+ if (this.expr instanceof StructAccess) {
+ const ref = this.expr.make_reference();
+ if (ref) return `${ref.format(fmt)}`;
+ }
+ return `&${this.expr.format(fmt)}`;
+ }
+}
+
+export class Lwl extends Expression {
+ static __fields = [["load_expr"], ["key"], ["type", factory(() => Type.any_reg())]];
+ static __eq_fields = ["load_expr", "key"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.load_expr];
+ }
+ format(fmt) {
+ return `M2C_LWL(${this.load_expr.format(fmt)})`;
+ }
+}
+
+export class Load3Bytes extends Expression {
+ static __fields = [["load_expr"], ["type", factory(() => Type.any_reg())]];
+ static __eq_fields = ["load_expr"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.load_expr];
+ }
+ format(fmt) {
+ if (fmt.valid_syntax) return `M2C_FIRST3BYTES(${this.load_expr.format(fmt)})`;
+ return `(first 3 bytes) ${this.load_expr.format(fmt)}`;
+ }
+}
+
+export class UnalignedLoad extends Expression {
+ static __fields = [["load_expr"], ["type", factory(() => Type.any_reg())]];
+ static __eq_fields = ["load_expr"];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [this.load_expr];
+ }
+ format(fmt) {
+ if (fmt.valid_syntax) return `M2C_UNALIGNED32(${this.load_expr.format(fmt)})`;
+ return `(unaligned s32) ${this.load_expr.format(fmt)}`;
+ }
+}
+
+export class EvalOnceExpr extends Expression {
+ static __fields = [
+ ["wrapped_expr"],
+ ["var"],
+ ["type"],
+ ["sources"],
+ ["emit_exactly_once"],
+ ["trivial"],
+ ["transparent"],
+ ["is_fictive_temp"],
+ ["forced_emit", false],
+ ["is_used", false],
+ ];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependency(may_move_forward) {
+ if (this.trivial) return this.wrapped_expr;
+ if (this.var.is_emitted) return null;
+ if (!this.transparent && this.is_used && !may_move_forward) return null;
+ return this.wrapped_expr;
+ }
+ dependencies() {
+ pyassert(false, "never called, and it's unclear what to pass for may_move_forward");
+ }
+ use() {
+ if (this.trivial || (this.transparent && !this.var.is_emitted)) {
+ this.wrapped_expr.use();
+ } else if (!this.is_used) {
+ if (!this.emit_exactly_once) this.wrapped_expr.use();
+ } else {
+ this.var.is_emitted = true;
+ }
+ this.is_used = true;
+ }
+ force() {
+ if (!this.forced_emit && !this.trivial) {
+ this.forced_emit = true;
+ this.var.is_emitted = true;
+ this.use();
+ this.use();
+ }
+ }
+ uses_var() {
+ return this.var.is_emitted && !this.trivial;
+ }
+ format(fmt) {
+ if (!this.uses_var()) return this.wrapped_expr.format(fmt);
+ return this.var.format(fmt);
+ }
+}
+
+/** A NaivePhiExpr acts as a phi node (see upstream docs). */
+export class NaivePhiExpr extends Expression {
+ static __fields = [["reg"], ["node"], ["type"], ["sources"], ["uses_dominator"], ["used_naive_phis"], ["name", null], ["num_usages", 0], ["replacement_expr", null]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ dependencies() {
+ return [];
+ }
+ get_var_name() {
+ return this.name || `unnamed-phi(${this.reg.register_name})`;
+ }
+ use() {
+ if (this.num_usages === 0) this.used_naive_phis.push(this);
+ this.num_usages += 1;
+ if (this.replacement_expr !== null) this.replacement_expr.use();
+ }
+ format(fmt) {
+ if (this.replacement_expr !== null) return this.replacement_expr.format(fmt);
+ return this.get_var_name();
+ }
+}
+
+export class SwitchControl {
+ static __fields = [["control_expr"], ["num_cases", null], ["jump_table", null], ["offset", 0], ["is_irregular", false]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ /** Return true if `cond` is the bounds check before using `jump_table`. */
+ matches_guard_condition(cond) {
+ const cmp_expr = simplify_condition(cond);
+ if (!(cmp_expr instanceof BinaryOp) || !(cmp_expr.op === ">=" || cmp_expr.op === ">")) return false;
+ const cmp_exclusive = cmp_expr.op === ">";
+ const left_expr = late_unwrap_ints(cmp_expr.left);
+ if (this.offset !== 0) {
+ if (
+ !(left_expr instanceof BinaryOp) ||
+ !pyeq(late_unwrap(left_expr.left), late_unwrap(this.control_expr)) ||
+ left_expr.op !== "+" ||
+ !pyeq(late_unwrap(left_expr.right), new Literal(-this.offset))
+ ) {
+ return false;
+ }
+ } else if (!pyeq(left_expr, late_unwrap_ints(this.control_expr))) return false;
+ const right_expr = late_unwrap(cmp_expr.right);
+ if (!(right_expr instanceof Literal)) return false;
+ return right_expr.value + (cmp_exclusive ? 1 : 0) === this.num_cases;
+ }
+ static irregular_from_expr(control_expr) {
+ return new SwitchControl({ control_expr, offset: 0, is_irregular: true });
+ }
+ static from_expr(expr, num_cases) {
+ const error_expr = new SwitchControl(expr);
+ const struct_expr = early_unwrap(expr);
+ if (!(struct_expr instanceof StructAccess) || struct_expr.offset !== 0) return error_expr;
+ const add_expr = early_unwrap(struct_expr.struct_var);
+ if (!(add_expr instanceof BinaryOp) || add_expr.op !== "+") return error_expr;
+ const left_expr = early_unwrap(add_expr.left);
+ const right_expr = early_unwrap(add_expr.right);
+ let jtbl_addr_expr, mul_expr;
+ if (left_expr instanceof AddressOf && left_expr.expr instanceof GlobalSymbol) {
+ jtbl_addr_expr = left_expr;
+ mul_expr = right_expr;
+ } else if (right_expr instanceof AddressOf && right_expr.expr instanceof GlobalSymbol) {
+ mul_expr = left_expr;
+ jtbl_addr_expr = right_expr;
+ } else return error_expr;
+ const jump_table = jtbl_addr_expr.expr;
+ pyassert(jump_table instanceof GlobalSymbol);
+ if (!(mul_expr instanceof BinaryOp) || mul_expr.op !== "*" || !pyeq(early_unwrap(mul_expr.right), new Literal(4))) return error_expr;
+ let control_expr = mul_expr.left;
+ let offset = 0;
+ const uw_control_expr = early_unwrap(control_expr);
+ if (uw_control_expr instanceof BinaryOp && uw_control_expr.op === "+") {
+ const offset_lit = early_unwrap(uw_control_expr.right);
+ if (offset_lit instanceof Literal) {
+ control_expr = uw_control_expr.left;
+ offset = -offset_lit.value;
+ }
+ }
+ if (jump_table.asm_data_entry === null || !jump_table.asm_data_entry.is_jtbl) return error_expr;
+ return new SwitchControl(control_expr, num_cases, jump_table, offset);
+ }
+}
+
+export class EvalOnceStmt extends Statement {
+ static __fields = [["expr"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ should_write() {
+ if (this.expr.emit_exactly_once && !this.expr.is_used) return true;
+ if (!this.expr.var.is_emitted) return false;
+ if (var_for_expr(late_unwrap(this.expr.wrapped_expr)) === this.expr.var) return false;
+ return true;
+ }
+ format(fmt) {
+ const val = elide_literal_casts(this.expr.wrapped_expr);
+ if (this.expr.emit_exactly_once && !this.expr.is_used) {
+ const val_str = format_expr(val, fmt);
+ return `${val_str};`;
+ }
+ return format_assignment(this.expr.var, val, fmt);
+ }
+}
+
+export class SetNaivePhiStmt extends Statement {
+ static __fields = [["phi"], ["expr"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ should_write() {
+ return !pyeq(late_unwrap(this.expr), this.phi);
+ }
+ format(fmt) {
+ return format_assignment(this.phi, this.expr, fmt);
+ }
+}
+
+export class ExprStmt extends Statement {
+ static __fields = [["expr"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ should_write() {
+ return true;
+ }
+ format(fmt) {
+ return `${format_expr(this.expr, fmt)};`;
+ }
+}
+
+export class StoreStmt extends Statement {
+ static __fields = [["source"], ["dest"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ should_write() {
+ return true;
+ }
+ format(fmt) {
+ const dest = this.dest;
+ let source = this.source;
+ if ((dest instanceof StructAccess && dest.late_has_known_type()) || dest instanceof ArrayAccess || dest instanceof LocalVar || dest instanceof SubroutineArg) {
+ source = elide_literal_casts(source);
+ }
+ return format_assignment(dest, source, fmt);
+ }
+}
+
+export class CommentStmt extends Statement {
+ static __fields = [["contents"]];
+ constructor(...args) {
+ super();
+ dcinit(this, args);
+ }
+ should_write() {
+ return true;
+ }
+ format(fmt) {
+ return `// ${this.contents}`;
+ }
+}
+
+export class AddressMode {
+ static __fields = [["offset"], ["base"]];
+ static __eq_fields = ["offset", "base"];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ toString() {
+ if (this.offset) return `${this.offset}(${this.base})`;
+ return `(${this.base})`;
+ }
+}
+
+export class RawSymbolRef {
+ static __fields = [["offset"], ["sym"]];
+ static __eq_fields = ["offset", "sym"];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ toString() {
+ if (this.offset) return `${this.sym.symbol_name} + ${this.offset}`;
+ return this.sym.symbol_name;
+ }
+}
+
+/** Metadata associated with a register value assignment. */
+export class RegMeta {
+ static __fields = [
+ ["inherited", false],
+ ["initial", false],
+ ["is_read", false],
+ ["function_return", false],
+ ["uninteresting", false],
+ ["force", false],
+ ["in_pattern", false],
+ ];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+}
+
+export class RegData {
+ constructor(value, meta) {
+ this.value = value;
+ this.meta = meta;
+ }
+}
+
+export class RegInfo {
+ constructor({ stack_info, contents = new Map(), read_inherited = new Set(), _current_instr_ref = null }) {
+ this.stack_info = stack_info;
+ this.contents = contents;
+ this.read_inherited = read_inherited;
+ this._current_instr_ref = _current_instr_ref;
+ }
+ current_instr_ref() {
+ pyassert(this._current_instr_ref !== null);
+ return this._current_instr_ref;
+ }
+ current_instr() {
+ return this.current_instr_ref().instruction;
+ }
+ has_current_instr() {
+ return this._current_instr_ref !== null;
+ }
+ /** Python `with regs.set_current_instr(ref): fn()` */
+ set_current_instr(instr_ref, fn) {
+ pyassert(this._current_instr_ref === null);
+ this._current_instr_ref = instr_ref;
+ try {
+ return set_current_instr(instr_ref.instruction, fn);
+ } finally {
+ this._current_instr_ref = null;
+ }
+ }
+ /** Python __getitem__ */
+ get(key) {
+ if (this.has_current_instr() && !this.current_instr().inputs.includes(key)) {
+ const lineno = this.get_instruction_lineno();
+ return new ErrorExpr(`Read from unset register ${key} on line ${lineno}`);
+ }
+ if (key === new Register("zero")) return new Literal(0);
+ const data = this.contents.get(key) ?? null;
+ if (data === null) return new ErrorExpr(`Read from unset register ${key}`);
+ const ret = data.value;
+ const meta = data.meta;
+ meta.is_read = true;
+ if (meta.inherited) this.read_inherited.add(key);
+ if (ret instanceof EvalOnceExpr && ret.trivial) return ret.wrapped_expr;
+ if (meta.initial) {
+ const uw_ret = unwrap_deep(ret);
+ if (uw_ret instanceof PassedInArg) {
+ const arg = this.stack_info.get_argument(uw_ret.loc);
+ this.stack_info.add_argument(arg);
+ arg.type.unify(ret.type);
+ }
+ }
+ if (meta.force) {
+ pyassert(ret instanceof EvalOnceExpr);
+ ret.force();
+ }
+ return ret;
+ }
+ /** Python __contains__ */
+ has(key) {
+ return this.contents.has(key);
+ }
+ /** Assign a value to a register from inside an instruction context. */
+ set_with_meta(key, value, meta) {
+ const instr = this.current_instr();
+ if (!instr.outputs.includes(key)) throw new DecompFailure(`Undeclared write to ${key} in ${instr}`);
+ pyassert(key !== new Register("zero"));
+ this.contents.set(key, new RegData(value, meta));
+ }
+ /** Assign a value to a register from outside an instruction context. */
+ global_set_with_meta(key, value, meta) {
+ pyassert(!this.has_current_instr());
+ pyassert(key !== new Register("zero"));
+ this.contents.set(key, new RegData(value, meta));
+ }
+ update_meta(key, meta) {
+ pyassert(key !== new Register("zero"));
+ if (!this.contents.has(key)) throw new Error(`KeyError: ${key}`);
+ this.contents.set(key, new RegData(this.contents.get(key).value, meta));
+ }
+ /** Python __delitem__ */
+ delete(key) {
+ pyassert(key !== new Register("zero"));
+ if (!this.contents.has(key)) throw new Error(`KeyError: ${key}`);
+ this.contents.delete(key);
+ }
+ get_raw(key) {
+ const data = this.contents.get(key) ?? null;
+ return data !== null ? data.value : null;
+ }
+ get_meta(key) {
+ const data = this.contents.get(key) ?? null;
+ return data !== null ? data.meta : null;
+ }
+ get_instruction_lineno() {
+ if (!this.has_current_instr()) return 0;
+ return this.current_instr().meta.lineno;
+ }
+ toString() {
+ return sorted(this.contents.entries(), (x) => x[0].register_name)
+ .filter(([, v]) => !this.stack_info.should_save(v.value, null))
+ .map(([k, v]) => `${k}: ${v.value}`)
+ .join(", ");
+ }
+}
+
+/** Contains translated assembly code, the block's branch condition, and block's final register states. */
+export class BlockInfo {
+ static __fields = [["to_write"], ["return_value"], ["switch_control"], ["branch_condition"], ["final_register_states"], ["has_function_call"]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ toString() {
+ const newline = "\n\t";
+ return [
+ `Statements: ${this.statements_to_write().map((w) => String(w)).join(newline)}`,
+ `Branch condition: ${this.branch_condition === null ? "None" : this.branch_condition}`,
+ `Final register states: ${this.final_register_states}`,
+ ].join("\n");
+ }
+ statements_to_write() {
+ return this.to_write.filter((st) => st.should_write());
+ }
+}
+
+export function visualize_flowgraph(flow_graph, viz_type) {
+ const fmt = new Formatter({ debug: true });
+ const nodes = [];
+ const edges = [];
+ const emit_node = (name, lines) => nodes.push([name, lines]);
+ const emit_edge = (source, target, attrs = {}) => edges.push([source, target, attrs]);
+
+ for (const node of flow_graph.nodes) {
+ const block_info = _get_optional_block_info(node);
+ let asm_lines = [];
+ let c_lines = [];
+ if (block_info) {
+ asm_lines = node.block.instructions.map((i) => `${i.meta.synthetic ? "*" : " "} ${i}`);
+ c_lines = block_info.to_write.filter((w) => w.should_write()).map((w) => w.format(fmt));
+ }
+ if (node instanceof BasicNode) {
+ emit_edge(node.name(), node.successor.name(), { color: "black" });
+ } else if (node instanceof ConditionalNode) {
+ if (block_info) {
+ pyassert(block_info.branch_condition !== null);
+ c_lines.push(`if (${block_info.branch_condition.format(fmt)})`);
+ }
+ emit_edge(node.name(), node.fallthrough_edge.name(), { label: "F", color: "blue" });
+ emit_edge(node.name(), node.conditional_edge.name(), { label: "T", color: "red" });
+ } else if (node instanceof ReturnNode) {
+ if (block_info !== null && block_info.return_value) c_lines.push(`return (${block_info.return_value.format(fmt)});`);
+ else c_lines.push("return;");
+ emit_edge(node.name(), node.terminal.name());
+ } else if (node instanceof SwitchNode) {
+ pyassert(block_info !== null);
+ const switch_control = block_info.switch_control;
+ pyassert(switch_control !== null);
+ c_lines.push(`switch (${switch_control.control_expr.format(fmt)})`);
+ node.cases.forEach((c, i) => emit_edge(node.name(), c.name(), { label: String(i + switch_control.offset), color: "green" }));
+ } else {
+ pyassert(node instanceof TerminalNode);
+ asm_lines.push("// exit");
+ c_lines.push("// exit");
+ }
+ let line_label = "";
+ const first_instr = node.block.instructions[0] ?? null;
+ if (first_instr !== null && first_instr.meta.lineno > 0) line_label = ` (line ${first_instr.meta.lineno})`;
+ let lines = [`// Node ${node.name()}${line_label}`];
+ if (viz_type === Options.VisualizeTypeEnum.ASM) lines = lines.concat(asm_lines);
+ else if (viz_type === Options.VisualizeTypeEnum.C) lines = lines.concat(c_lines);
+ else throw new ValueError("Invalid viz_type: {viz_type!r}");
+ emit_node(node.name(), lines);
+ }
+ const escape = (value) => value.replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("\n", "\\n");
+ const quote = (value) => '"' + escape(value) + '"';
+ const lines = ["digraph {", ' node [shape="rect", fontname="Monospace"];', ' edge [fontname="Monospace"];'];
+ for (const [name, source] of nodes) {
+ const label = source.map((line) => escape(line) + "\\l").join("");
+ lines.push(` ${quote(name)} [label="${label}"];`);
+ }
+ for (const [source, target, attrs] of edges) {
+ const attr_strs = Object.entries(attrs).map(([name, value]) => `${name}=${quote(value)}`);
+ const attr_text = attr_strs.length ? ` [${attr_strs.join(", ")}]` : "";
+ lines.push(` ${quote(source)} -> ${quote(target)}${attr_text};`);
+ }
+ lines.push("}");
+ return lines.join("\n") + "\n";
+}
+
+export function get_block_info_for_block(block) {
+ const ret = block.block_info;
+ pyassert(ret instanceof BlockInfo);
+ return ret;
+}
+export function get_block_info(node) {
+ return get_block_info_for_block(node.block);
+}
+function _get_optional_block_info(node) {
+ if (node.block.block_info === null) return null;
+ return get_block_info(node);
+}
+
+export class InstrArgs {
+ static __fields = [["instruction_ref"], ["raw_args"], ["regs"], ["stack_info"]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ raw_arg(index) {
+ pyassert(index >= 0);
+ if (index >= this.raw_args.length) throw new DecompFailure(`Too few arguments for instruction, expected at least ${index + 1}`);
+ return this.raw_args[index];
+ }
+ reg_ref(index) {
+ const ret = this.raw_arg(index);
+ if (!(ret instanceof Register)) throw new DecompFailure(`Expected instruction argument to be a register, but found ${ret}`);
+ return ret;
+ }
+ imm_value(index) {
+ const arg = this.full_imm(index);
+ pyassert(arg instanceof Literal);
+ return arg.value;
+ }
+ reg(index) {
+ return this.regs.get(this.reg_ref(index));
+ }
+ /** Extract a double from a register (may read the paired register). */
+ dreg(index) {
+ const reg = this.reg_ref(index);
+ if (this.stack_info.global_info.arch.arch !== Target.ArchEnum.ARM && !reg.is_float()) throw new DecompFailure(`Expected instruction argument ${reg} to be a float register`);
+ const ret = this.regs.get(reg);
+ if (this.stack_info.global_info.arch.arch === Target.ArchEnum.PPC) return ret;
+ if (!(ret instanceof Literal) || ret.type.get_size_bits() === 64) return ret;
+ const reg_num = int_(reg.register_name.slice(1));
+ if (reg_num % 2 !== 0) throw new DecompFailure("Tried to use a double-precision instruction with odd-numbered float " + `register ${reg}`);
+ const other = this.regs.get(new Register(`${reg.register_name[0]}${reg_num + 1}`));
+ if (other instanceof Literal && other.type.get_size_bits() !== 64) {
+ const value = bor(ret.value, shl(other.value, 32));
+ return new Literal(value, { type: Type.f64() });
+ }
+ ret.type.unify(Type.uintish());
+ other.type.unify(Type.uintish());
+ return new BinaryOp({ op: "GLUE_F64", left: other, right: ret, type: Type.f64() });
+ }
+ cmp_reg(key) {
+ let cond = this.regs.get(new Register(key));
+ if (!(cond instanceof Condition)) cond = BinaryOp.icmp(cond, "!=", new Literal(0));
+ return cond;
+ }
+ full_imm(index) {
+ const arg = strip_macros(this.raw_arg(index));
+ return literal_expr(arg, this.stack_info);
+ }
+ s8_imm(index) {
+ const ret = this.full_imm(index);
+ if (ret instanceof Literal) return new Literal(band(ret.value + 0x80, 0xff) - 0x80);
+ return ret;
+ }
+ s16_imm(index) {
+ const ret = this.full_imm(index);
+ if (ret instanceof Literal) return new Literal(band(ret.value + 0x8000, 0xffff) - 0x8000);
+ return ret;
+ }
+ u16_imm(index) {
+ const ret = this.full_imm(index);
+ if (ret instanceof Literal) return new Literal(band(ret.value, 0xffff));
+ return ret;
+ }
+ reg_or_imm(index) {
+ const arg = this.raw_arg(index);
+ if (arg instanceof Register) return this.regs.get(arg);
+ return this.full_imm(index);
+ }
+ reg_or_s8_imm(index) {
+ const arg = this.raw_arg(index);
+ if (arg instanceof Register) return this.regs.get(arg);
+ return this.s8_imm(index);
+ }
+ hi_imm(index) {
+ const arg = this.raw_arg(index);
+ if (!(arg instanceof Macro) || !["hi", "ha", "h"].includes(arg.macro_name)) throw new DecompFailure(`lui/lis argument must be a literal or %hi/@ha/@h macro, found ${arg}`);
+ const ref = parse_symbol_ref(arg.argument);
+ if (ref === null) throw new DecompFailure(`Invalid macro argument ${arg.argument}`);
+ return ref;
+ }
+ maybe_gprel_imm(index) {
+ const val = this.raw_arg(index);
+ if (!(val instanceof Macro) || val.macro_name !== "gp_rel") return null;
+ const ref = parse_symbol_ref(val.argument);
+ if (ref === null) throw new DecompFailure(`Invalid macro argument ${val.argument}`);
+ return ref;
+ }
+ maybe_got_imm(index) {
+ const arg = this.raw_arg(index);
+ if (!(arg instanceof AsmAddressMode) || arg.base !== new Register("gp")) return null;
+ const val = arg.addend;
+ if (!(val instanceof Macro) || !["got", "call16"].includes(val.macro_name)) return null;
+ const ref = parse_symbol_ref(val.argument);
+ if (ref === null) throw new DecompFailure(`Invalid macro argument ${val.argument}`);
+ return ref;
+ }
+ shifted_u16_imm(index) {
+ const raw_imm = this.u16_imm(index);
+ pyassert(raw_imm instanceof Literal);
+ return new Literal(shl(raw_imm.value, 16));
+ }
+ sym_imm(index) {
+ const arg = this.raw_arg(index);
+ if (arg instanceof AsmGlobalSymbol) return this.stack_info.global_info.address_of_gsym(arg.symbol_name);
+ if (arg instanceof AsmLiteral) return this.full_imm(index);
+ throw new DecompFailure(`Bad function call operand ${arg}`);
+ }
+ memory_ref(index) {
+ const ret = strip_macros(this.raw_arg(index));
+ const ref = parse_symbol_ref(ret);
+ if (ref !== null) return ref;
+ if (!(ret instanceof AsmAddressMode)) throw new DecompFailure("Expected instruction argument to be of the form offset($register), " + `but found ${ret}`);
+ if (!(ret.addend instanceof AsmLiteral)) throw new DecompFailure(`Unable to parse offset for instruction argument ${ret}. ` + "Expected a constant or a %lo macro.");
+ return new AddressMode({ offset: ret.addend.value, base: ret.base });
+ }
+ count() {
+ return this.raw_args.length;
+ }
+}
+
+/** Compute whether an EvalOnceExpr should be marked as `trivial = True`. */
+export function is_trivial_expression(expr) {
+ if (expr instanceof Literal || expr instanceof GlobalSymbol || expr instanceof SecondF64Half) return true;
+ if (expr instanceof AddressOf) return expr.dependencies().every((e) => is_trivial_expression(e));
+ return false;
+}
+
+/** Compute whether an EvalOnceExpr should be marked as `transparent = True`. */
+export function should_wrap_transparently(expr) {
+ if (
+ expr instanceof Literal ||
+ expr instanceof LocalVar ||
+ expr instanceof PassedInArg ||
+ expr instanceof NaivePhiExpr ||
+ expr instanceof PlannedPhiExpr ||
+ expr instanceof SecondF64Half ||
+ expr instanceof SubroutineArg
+ ) {
+ return true;
+ }
+ if (expr instanceof EvalOnceExpr) return !expr.is_fictive_temp;
+ if (expr instanceof GlobalSymbol) return !expr.is_string_constant();
+ if (expr instanceof AddressOf) return should_wrap_transparently(expr.expr);
+ if (expr instanceof Cast) return expr.should_wrap_transparently();
+ if (expr instanceof StructAccess && expr.struct_var instanceof AddressOf && expr.struct_var.expr instanceof GlobalSymbol && should_wrap_transparently(expr.struct_var.expr)) return true;
+ return false;
+}
+
+/** Determine whether an expression's type is "obvious". */
+export function is_type_obvious(expr) {
+ if (
+ expr instanceof Cast ||
+ expr instanceof Literal ||
+ expr instanceof AddressOf ||
+ expr instanceof LocalVar ||
+ expr instanceof NaivePhiExpr ||
+ expr instanceof PassedInArg ||
+ expr instanceof PlannedPhiExpr ||
+ expr instanceof FuncCall
+ ) {
+ return true;
+ }
+ if (expr instanceof EvalOnceExpr) {
+ if (expr.uses_var()) return true;
+ return is_type_obvious(expr.wrapped_expr);
+ }
+ return false;
+}
+
+/** Simplify a boolean expression. */
+export function simplify_condition(expr) {
+ if (expr instanceof EvalOnceExpr && !expr.uses_var()) return simplify_condition(expr.wrapped_expr);
+ if (expr instanceof UnaryOp) {
+ const inner = simplify_condition(expr.expr);
+ if (expr.op === "!" && inner instanceof Condition) return inner.negated();
+ return new UnaryOp({ expr: inner, op: expr.op, type: expr.type });
+ }
+ if (expr instanceof BinaryOp) {
+ const left = simplify_condition(expr.left);
+ const right = simplify_condition(expr.right);
+ if (left instanceof UnaryOp && left.op === "!" && pyeq(right, new Literal(0))) {
+ if (expr.op === "==") return left.expr;
+ if (expr.op === "!=") return left;
+ }
+ if (left instanceof BinaryOp && (left.is_comparison() || left.op === "&") && pyeq(right, new Literal(0))) {
+ if (expr.op === "==") return simplify_condition(left.negated());
+ if (expr.op === "!=") return left;
+ }
+ if (expr.is_comparison() && left instanceof Literal && !(right instanceof Literal)) {
+ return new BinaryOp({ left: right, op: swap_lt_gt(expr.op), right: left, type: expr.type });
+ }
+ return new BinaryOp({ left, op: expr.op, right, type: expr.type });
+ }
+ return expr;
+}
+
+/** Check if parentheses in a string are balanced. */
+export function balanced_parentheses(string) {
+ let bal = 0;
+ for (const c of string) {
+ if (c === "(") bal += 1;
+ else if (c === ")") {
+ if (bal === 0) return false;
+ bal -= 1;
+ }
+ }
+ return bal === 0;
+}
+
+/** Stringify an expression, stripping unnecessary parentheses around it. */
+export function format_expr(expr, fmt) {
+ const ret = expr.format(fmt);
+ if (ret.startsWith("(") && balanced_parentheses(ret.slice(1, -1))) return ret.slice(1, -1);
+ return ret;
+}
+
+/** Stringify `dest = source;`. */
+export function format_assignment(dest, source, fmt) {
+ let is_dest;
+ if (dest instanceof Expression) {
+ dest = late_unwrap(dest);
+ const d = dest;
+ is_dest = (e) => pyeq(e, d);
+ } else {
+ const d = dest;
+ is_dest = (e) => var_for_expr(e) === d;
+ }
+ source = late_unwrap(source);
+ if (source instanceof BinaryOp && COMPOUND_ASSIGNMENT_OPS.has(source.op)) {
+ source = source.normalize_for_formatting();
+ let rhs = null;
+ if (is_dest(late_unwrap(source.left))) rhs = source.right;
+ else if (is_dest(late_unwrap(source.right)) && ASSOCIATIVE_OPS.has(source.op)) rhs = source.left;
+ if (rhs !== null) return `${dest.format(fmt)} ${source.op}= ${format_expr(rhs, fmt)};`;
+ }
+ return `${dest.format(fmt)} = ${format_expr(source, fmt)};`;
+}
+
+/** If an expression *may* expand to the read of a Var, return that var. */
+export function var_for_expr(expr) {
+ if (expr instanceof PlannedPhiExpr) return expr.var;
+ if (expr instanceof EvalOnceExpr && !expr.trivial) return expr.var;
+ return null;
+}
+
+export function parenthesize_for_struct_access(expr, fmt) {
+ const s = expr.format(fmt);
+ if (s.startsWith("*") || s.startsWith("&") || (expr instanceof Cast && expr.needed_for_store())) return `(${s})`;
+ return s;
+}
+
+export function elide_literal_casts(expr) {
+ const uw_expr = late_unwrap(expr);
+ if (uw_expr instanceof Cast && !uw_expr.needed_for_store()) return elide_literal_casts(uw_expr.expr);
+ if (uw_expr instanceof Literal && uw_expr.type.is_int() && uw_expr.value >= 0) return dcreplace(uw_expr, { elide_cast: true });
+ return uw_expr;
+}
+
+export function uses_expr_sub(expr, expr_filter, is_parent_addressof, may_move_forward, seen) {
+ const cache_key = `${objId(expr)},${may_move_forward ? 1 : 0},${is_parent_addressof ? 1 : 0}`;
+ if (seen.has(cache_key)) return false;
+ seen.add(cache_key);
+ if (expr_filter(expr) && !is_parent_addressof) return true;
+ if (expr instanceof EvalOnceExpr) {
+ const e = expr.dependency(may_move_forward);
+ return e !== null && uses_expr_sub(e, expr_filter, false, may_move_forward || expr.emit_exactly_once, seen);
+ } else if (expr instanceof AddressOf) {
+ return uses_expr_sub(expr.expr, expr_filter, true, may_move_forward, seen);
+ } else {
+ for (const e of expr.dependencies()) if (uses_expr_sub(e, expr_filter, false, may_move_forward, seen)) return true;
+ return false;
+ }
+}
+
+export function uses_expr(expr, expr_filter) {
+ return uses_expr_sub(expr, expr_filter, false, false, new Set());
+}
+
+/** Unwrap EvalOnceExpr's, stopping at variable boundaries. */
+export function late_unwrap(expr) {
+ if (expr instanceof EvalOnceExpr && !expr.uses_var()) return late_unwrap(expr.wrapped_expr);
+ if (expr instanceof NaivePhiExpr && expr.replacement_expr !== null) return late_unwrap(expr.replacement_expr);
+ return expr;
+}
+
+/** Unwrap transparent EvalOnceExpr's. */
+export function transparent_unwrap(expr) {
+ if (expr instanceof EvalOnceExpr && expr.transparent && !expr.uses_var()) return transparent_unwrap(expr.wrapped_expr);
+ return expr;
+}
+
+/** Unwrap EvalOnceExpr's, even past variable boundaries. */
+export function early_unwrap(expr) {
+ if (expr instanceof EvalOnceExpr && !expr.forced_emit && !expr.emit_exactly_once) return early_unwrap(expr.wrapped_expr);
+ return expr;
+}
+
+export function early_unwrap_ints(expr) {
+ const uw_expr = early_unwrap(expr);
+ if (uw_expr instanceof Cast && uw_expr.reinterpret && uw_expr.type.is_int()) return early_unwrap_ints(uw_expr.expr);
+ return uw_expr;
+}
+
+export function late_unwrap_ints(expr) {
+ const uw_expr = late_unwrap(expr);
+ if (uw_expr instanceof Cast && uw_expr.reinterpret && uw_expr.type.is_int()) return late_unwrap_ints(uw_expr.expr);
+ return uw_expr;
+}
+
+export function unwrap_deep(expr) {
+ if (expr instanceof EvalOnceExpr) return unwrap_deep(expr.wrapped_expr);
+ return expr;
+}
+
+export function literal_expr(arg, stack_info) {
+ if (arg instanceof AsmGlobalSymbol) return stack_info.global_info.address_of_gsym(arg.symbol_name);
+ if (arg instanceof AsmLiteral) return new Literal(arg.value);
+ if (arg instanceof BinOp) {
+ const lhs = literal_expr(arg.lhs, stack_info);
+ const rhs = literal_expr(arg.rhs, stack_info);
+ return BinaryOp.int(lhs, arg.op, rhs);
+ }
+ throw new DecompFailure(`Instruction argument ${arg} must be a literal`);
+}
+
+export function parse_symbol_ref(arg) {
+ if (arg instanceof AsmGlobalSymbol) return new RawSymbolRef({ offset: 0, sym: arg });
+ if (arg instanceof BinOp && "+-".includes(arg.op) && arg.lhs instanceof AsmGlobalSymbol && arg.rhs instanceof AsmLiteral) {
+ return new RawSymbolRef({ offset: arg.rhs.value * (arg.op === "-" ? -1 : 1), sym: arg.lhs });
+ }
+ return null;
+}
+
+function pack_f32_bits(value) {
+ if (Number.isFinite(value) && !Number.isFinite(Math.fround(value))) throw new Error("OverflowError: float too large to pack with f format");
+ const dv = new DataView(new ArrayBuffer(4));
+ dv.setFloat32(0, value);
+ return dv.getUint32(0);
+}
+
+export function format_f32_imm(num) {
+ const bits = Number(BigInt.asUintN(32, BigInt(num)));
+ const dv = new DataView(new ArrayBuffer(4));
+ dv.setUint32(0, bits);
+ const value = dv.getFloat32(0);
+ const packed = bits;
+
+ if (!value || value === 4294967296.0) return float_repr(value);
+
+ let fmt_char;
+ if (Math.abs(Math.log10(Math.abs(value))) > 6.9) fmt_char = "e";
+ else if (Math.abs(value) < 1) fmt_char = "f";
+ else fmt_char = "g";
+
+ const fmt = (prec) => {
+ let ret;
+ if (fmt_char === "e") ret = format_exp(value, prec);
+ else if (fmt_char === "f") ret = format_fixed(value, prec);
+ else ret = format_general(value, prec);
+ if (fmt_char === "e") return ret.replaceAll("e+", "e").replaceAll("e0", "e").replaceAll("e-0", "e-");
+ if (ret.includes("e")) return "0";
+ return ret;
+ };
+
+ let prec = 20;
+ while (prec > 0) {
+ prec -= 1;
+ const value2 = py_float(fmt(prec));
+ if (pack_f32_bits(value2) !== packed) {
+ prec += 1;
+ break;
+ }
+ }
+ if (prec === 20) return float_repr(value);
+ let ret = fmt(prec);
+ if (!ret.includes(".") && !ret.includes("e")) ret += ".0";
+ return ret;
+}
+
+export function format_f64_imm(num) {
+ const dv = new DataView(new ArrayBuffer(8));
+ dv.setBigUint64(0, BigInt.asUintN(64, BigInt(num)));
+ return float_repr(dv.getFloat64(0));
+}
+
+/** Replace %lo(...) by 0, and assert that there are no %hi(...). */
+export function strip_macros(arg) {
+ if (arg instanceof Macro) {
+ if (arg.macro_name === "sda2" || arg.macro_name === "sda21") return arg.argument;
+ if (arg.macro_name === "hi") throw new DecompFailure("%hi macro outside of lui");
+ if (arg.macro_name !== "lo" && arg.macro_name !== "l") throw new DecompFailure(`Unrecognized linker macro %${arg.macro_name}`);
+ if (arg.argument instanceof AsmLiteral) return new AsmLiteral(arg.argument.value);
+ return new AsmLiteral(0);
+ } else if (arg instanceof AsmAddressMode && arg.addend instanceof Macro) {
+ if (["sda2", "sda21", "gp_rel"].includes(arg.addend.macro_name)) return arg.addend.argument;
+ if (arg.addend.macro_name !== "lo" && arg.addend.macro_name !== "l") throw new DecompFailure(`Bad linker macro in instruction argument ${arg}, expected %lo`);
+ return new AsmAddressMode(arg.base, new AsmLiteral(0), arg.writeback);
+ }
+ return arg;
+}
+
+export class ArgLoc {
+ static __fields = [["offset"], ["sort_index"], ["reg"]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+ __lt__(other) {
+ if (this.sort_index !== null) {
+ if (other.sort_index === null) return true;
+ return this.sort_index < other.sort_index;
+ }
+ if (other.sort_index !== null) return false;
+ pyassert(this.offset !== null);
+ pyassert(other.offset !== null);
+ return this.offset < other.offset;
+ }
+ equals(other) {
+ if (!(other instanceof ArgLoc)) return false;
+ if (this.offset !== null) return other.offset === this.offset;
+ return other.offset === null && this.reg === other.reg;
+ }
+ __pykey() {
+ if (this.offset !== null) return `AL:o${this.offset}`;
+ return `AL:r${this.reg === null ? "N" : "#" + this.reg.__iid}`;
+ }
+}
+
+export class AbiArgSlot {
+ static __fields = [["loc"], ["type"], ["name", null], ["comment", null]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+}
+
+export class Abi {
+ static __fields = [["arg_slots"], ["possible_slots"]];
+ constructor(...args) {
+ dcinit(this, args);
+ }
+}
+
+export function find_clobbers_until_dominator(stack_info, node) {
+ pyassert(node.immediate_dominator !== null);
+ const seen = new Set([node.immediate_dominator]);
+ const stack = [...node.parents];
+ const clobbered_vars = new Set();
+ let has_fn_call = false;
+ while (stack.length) {
+ const n = stack.pop();
+ if (seen.has(n)) continue;
+ seen.add(n);
+ for (const instr_ref of n.block.instruction_refs) {
+ const instr = instr_ref.instruction;
+ for (const loc of instr.outputs) {
+ if (loc instanceof Register) {
+ const v = stack_info.get_planned_var(loc, instr_ref);
+ if (v !== null) clobbered_vars.add(v);
+ }
+ }
+ if (instr.function_target !== null) has_fn_call = true;
+ }
+ stack.push(...n.parents);
+ }
+ return [clobbered_vars, has_fn_call];
+}
+
+export function reg_sources(node, reg) {
+ pyassert(node.immediate_dominator !== null);
+ const seen = new Set([node.immediate_dominator]);
+ const stack = [...node.parents];
+ const sources = [];
+ let uses_dominator = false;
+ while (stack.length) {
+ const n = stack.pop();
+ if (n === node.immediate_dominator) uses_dominator = true;
+ if (seen.has(n)) continue;
+ seen.add(n);
+ let broke = false;
+ const refs = n.block.instruction_refs;
+ for (let i = refs.length - 1; i >= 0; i--) {
+ const instr_ref = refs[i];
+ const instr = instr_ref.instruction;
+ if (instr.outputs.includes(reg)) {
+ sources.push(instr_ref);
+ broke = true;
+ break;
+ } else if (instr.clobbers.includes(reg)) {
+ return [[], false];
+ }
+ }
+ if (!broke) stack.push(...n.parents);
+ }
+ return [sources, uses_dominator];
+}
+
+export function assign_naive_phis(used_naive_phis, stack_info) {
+ let i = 0;
+ while (i < used_naive_phis.length) {
+ const phi = used_naive_phis[i];
+ pyassert(phi.num_usages > 0);
+ pyassert(phi.sources.length >= 2);
+ pyassert(phi.node.parents.length >= 2);
+
+ const equivalent_blocks = new DefaultPyDict(() => []);
+ for (const source of phi.sources) {
+ let block;
+ if (source instanceof InstrRef) block = source.block;
+ else block = stack_info.flow_graph.entry_node().block;
+ const expr = get_block_info_for_block(block).final_register_states.get(phi.reg);
+ expr.type.unify(phi.type);
+ equivalent_blocks.get(transparent_unwrap(expr)).push(block);
+ }
+
+ const exprs = [...equivalent_blocks.keys()];
+ const first_uw = early_unwrap(exprs[0]);
+ if (exprs.slice(1).every((e) => pyeq(early_unwrap(e), first_uw))) {
+ const phi_expr = exprs.length === 1 ? exprs[0] : first_uw;
+ phi.replacement_expr = as_type(phi_expr, phi.type, true);
+ for (let k = 0; k < phi.num_usages; k++) phi_expr.use();
+ if (exprs.length === 1) {
+ if (phi.uses_dominator) stack_info.add_planned_inherited_phi(phi.node, phi.reg, PhiInheritSource.DOMINATOR);
+ else if (is_trivial_expression(exprs[0])) stack_info.add_planned_inherited_phi(phi.node, phi.reg, PhiInheritSource.ANY_PARENT);
+ }
+ } else {
+ for (const [, blocks] of equivalent_blocks) {
+ for (const block of blocks) {
+ const block_info = get_block_info_for_block(block);
+ const expr = block_info.final_register_states.get(phi.reg);
+ expr.use();
+ const typed_expr = as_type(expr, phi.type, true);
+ block_info.to_write.push(new SetNaivePhiStmt(phi, typed_expr));
+ }
+ }
+ }
+ i += 1;
+ }
+
+ for (const phi of used_naive_phis) {
+ if (!phi.replacement_expr) {
+ const output_reg_name = stack_info.function.reg_formatter.format(phi.reg);
+ let prefix = `phi_${output_reg_name}`;
+ if (stack_info.global_info.deterministic_vars) prefix = `${prefix}_${phi.node.block.index}`;
+ phi.name = stack_info.temp_var(prefix);
+ stack_info.naive_phi_vars.push(phi);
+ const v = stack_info.get_persistent_planned_var(phi.reg, phi.sources[0]);
+ for (const source of phi.sources.slice(1)) stack_info.get_persistent_planned_var(phi.reg, source).join(v);
+ }
+ }
+}
+
+/** Propagate RegMeta bits forwards/backwards. */
+export function propagate_register_meta(nodes, reg) {
+ const non_terminal = nodes.filter((n) => !(n instanceof TerminalNode));
+
+ for (const n of non_terminal) {
+ if (get_block_info(n).final_register_states.read_inherited.has(reg)) {
+ for (const p of n.parents) {
+ const par_meta = get_block_info(p).final_register_states.get_meta(reg);
+ if (par_meta) par_meta.is_read = true;
+ }
+ }
+ }
+
+ let todo = [...non_terminal];
+ while (todo.length) {
+ const n = todo.pop();
+ const meta = get_block_info(n).final_register_states.get_meta(reg);
+ for (const p of n.parents) {
+ const par_meta = get_block_info(p).final_register_states.get_meta(reg);
+ if (par_meta && !par_meta.is_read && meta && meta.inherited && meta.is_read) {
+ par_meta.is_read = true;
+ todo.push(p);
+ }
+ }
+ }
+
+ for (const n of non_terminal) {
+ const meta = get_block_info(n).final_register_states.get_meta(reg);
+ if (meta) {
+ if (meta.inherited) {
+ meta.uninteresting = true;
+ meta.function_return = true;
+ meta.in_pattern = true;
+ } else {
+ meta.uninteresting = meta.uninteresting || meta.is_read || meta.function_return || meta.in_pattern;
+ }
+ }
+ }
+
+ todo = [...non_terminal];
+ while (todo.length) {
+ const n = todo.pop();
+ if (n instanceof TerminalNode) continue;
+ const meta = get_block_info(n).final_register_states.get_meta(reg);
+ if (!meta || !meta.inherited) continue;
+ let all_uninteresting = true;
+ let all_function_return = true;
+ let all_in_pattern = true;
+ for (const p of n.parents) {
+ const par_meta = get_block_info(p).final_register_states.get_meta(reg);
+ if (par_meta) {
+ all_uninteresting = all_uninteresting && par_meta.uninteresting;
+ all_function_return = all_function_return && par_meta.function_return;
+ all_in_pattern = all_in_pattern && par_meta.in_pattern;
+ }
+ }
+ if (meta.uninteresting && !all_uninteresting && !meta.is_read) {
+ meta.uninteresting = false;
+ todo.push(...n.children());
+ }
+ if (meta.function_return && !all_function_return) {
+ meta.function_return = false;
+ todo.push(...n.children());
+ }
+ if (meta.in_pattern && !all_in_pattern) {
+ meta.in_pattern = false;
+ todo.push(...n.children());
+ }
+ }
+}
+
+/** Determine which of the arch's base_return_regs is most likely to contain the return value. */
+export function determine_return_register(return_blocks, fn_decl_provided, arch) {
+ const priority = (block_info, reg) => {
+ const meta = block_info.final_register_states.get_meta(reg);
+ if (!meta) return 4;
+ if (meta.uninteresting) return 2;
+ if (meta.in_pattern) return 1;
+ if (meta.function_return) return 0;
+ return 3;
+ };
+ if (!return_blocks.length) return null;
+ let best_reg = null;
+ let best_prio = -1;
+ for (const [reg, floating] of arch.base_return_regs) {
+ const prios = return_blocks.map((b) => priority(b, reg));
+ const max_prio = Math.max(...prios);
+ if (max_prio === 4) continue;
+ if (max_prio <= 2 && !fn_decl_provided) continue;
+ if (max_prio > best_prio) {
+ best_prio = max_prio;
+ best_reg = [reg, floating];
+ }
+ }
+ return best_reg;
+}
+
+export class NodeState {
+ constructor({ node, stack_info, regs }) {
+ this.node = node;
+ this.stack_info = stack_info;
+ this.regs = regs;
+ // LocalVar -> [Register, Expression, bool]
+ this.local_var_writes = new PyDict();
+ this.subroutine_args = new Map();
+ this.in_pattern = false;
+ this.to_write = [];
+ this.branch_condition = null;
+ this.switch_control = null;
+ this.has_function_call = false;
+ }
+
+ _eval_once(expr, { emit_exactly_once, transparent, reg, source }) {
+ const planned_var = this.stack_info.get_planned_var(reg, source);
+ let is_fictive_temp = false;
+
+ if (reg.register_name.includes("_fictive_")) {
+ if (expr instanceof EvalOnceExpr && !expr.var.is_planned) {
+ pyassert(!emit_exactly_once);
+ pyassert(!planned_var);
+ return expr;
+ }
+ reg = new Register(reg.register_name.split("_fictive_")[0]);
+ is_fictive_temp = true;
+ }
+
+ const trivial = transparent && is_trivial_expression(expr);
+ if (emit_exactly_once) expr.use();
+
+ let force = false;
+ let v;
+ if (planned_var !== null) {
+ v = planned_var;
+ expr = as_type(expr, v.type, true);
+ this.prevent_later_var_uses(new Set([v]));
+ if (uses_expr(expr, (e) => var_for_expr(e) === v)) force = true;
+ } else {
+ let prefix = this.stack_info.function.reg_formatter.format(reg);
+ if (prefix === "condition_bit") prefix = "cond";
+ let temp_name = `temp_${prefix}`;
+ if (this.stack_info.global_info.deterministic_vars) temp_name = `${temp_name}_${this.regs.get_instruction_lineno()}`;
+ v = new Var(this.stack_info, temp_name, { is_planned: false, type: expr.type });
+ this.stack_info.temp_vars.push(v);
+ }
+
+ const ret = new EvalOnceExpr({
+ wrapped_expr: expr,
+ var: v,
+ type: expr.type,
+ sources: [source],
+ emit_exactly_once,
+ trivial,
+ transparent,
+ is_fictive_temp,
+ });
+ const stmt = new EvalOnceStmt(ret);
+ this.write_statement(stmt);
+ v.debug_exprs.push(ret);
+
+ if (planned_var !== null) {
+ v.is_emitted = true;
+ ret.use();
+ if (force) ret.force();
+ }
+ return ret;
+ }
+
+ /** Prevent later uses of registers that recursively contain something that matches a filter. */
+ _prevent_later_uses(expr_filter) {
+ for (const [r, data] of [...this.regs.contents.entries()]) {
+ const expr = data.value;
+ if (expr instanceof PlannedPhiExpr || expr instanceof NaivePhiExpr) continue;
+ if (!data.meta.force && uses_expr(expr, expr_filter)) {
+ if (!(expr instanceof EvalOnceExpr)) assert_never(expr);
+ this.regs.update_meta(r, dcreplace(data.meta, { force: true }));
+ }
+ }
+ for (const [loc, [reg, write, force]] of [...this.local_var_writes.entries()]) {
+ if (!force && uses_expr(write, expr_filter)) this.local_var_writes.set(loc, [reg, write, true]);
+ }
+ }
+
+ prevent_later_value_uses(sub_expr) {
+ this._prevent_later_uses((e) => pyeq(e, sub_expr));
+ }
+
+ prevent_later_var_uses(vars) {
+ if (vars.size) this._prevent_later_uses((e) => vars.has(var_for_expr(e)));
+ }
+
+ prevent_later_function_calls() {
+ this._prevent_later_uses((e) => e instanceof FuncCall);
+ }
+
+ prevent_later_reads() {
+ this._prevent_later_uses((e) => e instanceof StructAccess || e instanceof ArrayAccess);
+ }
+
+ set_initial_reg(reg, expr, meta) {
+ pyassert(meta.initial);
+ expr = this._eval_once(expr, { emit_exactly_once: false, transparent: true, reg, source: new PrologueRef(reg) });
+ this.regs.global_set_with_meta(reg, expr, meta);
+ if (expr.var.is_emitted) this.regs.get(reg);
+ }
+
+ set_reg(reg, expr) {
+ if (expr instanceof LocalVar) {
+ if (
+ this.node instanceof ReturnNode &&
+ this.stack_info.maybe_get_register_var(reg) &&
+ this.stack_info.in_callee_save_reg_region(expr.value) &&
+ this.stack_info.callee_save_regs.has(reg)
+ ) {
+ return expr;
+ }
+ if (this.stack_info.global_info.stack_spill_detection && this.local_var_writes.has(expr)) {
+ const [orig_reg, orig_expr, force] = this.local_var_writes.get(expr);
+ if (orig_reg === reg) {
+ expr = orig_expr;
+ if (force) {
+ let base_expr = expr;
+ while (base_expr instanceof Cast) base_expr = base_expr.expr;
+ if (base_expr instanceof EvalOnceExpr) base_expr.force();
+ }
+ }
+ }
+ }
+ return this.set_reg_real(reg, expr);
+ }
+
+ set_reg_real(reg, uw_expr, { transparent = null, emit_exactly_once = false, function_return = false } = {}) {
+ const source = this.regs.current_instr_ref();
+ if (transparent === null) transparent = should_wrap_transparently(uw_expr);
+ const expr = this._eval_once(uw_expr, { emit_exactly_once, transparent, reg, source });
+ if (reg === new Register("zero")) {
+ expr.use();
+ this.write_statement(new ExprStmt(expr));
+ } else {
+ const in_pattern = source.instruction.in_pattern;
+ this.regs.set_with_meta(reg, expr, new RegMeta({ in_pattern, function_return }));
+ }
+ return expr;
+ }
+
+ clear_caller_save_regs() {
+ for (const reg of this.stack_info.global_info.arch.temp_regs) if (this.regs.has(reg)) this.regs.delete(reg);
+ }
+
+ maybe_clear_local_var_writes(func_args) {
+ for (const arg of func_args) {
+ if (uses_expr(arg, (expr) => expr instanceof AddressOf && expr.expr instanceof LocalVar)) {
+ this.local_var_writes.clear();
+ return;
+ }
+ }
+ }
+
+ set_branch_condition(cond) {
+ pyassert(this.node instanceof ConditionalNode);
+ pyassert(this.branch_condition === null);
+ this.branch_condition = cond;
+ }
+
+ set_switch_expr(expr, just_index = false) {
+ pyassert(this.node instanceof SwitchNode);
+ pyassert(this.switch_control === null);
+ if (just_index) this.switch_control = new SwitchControl(expr, { num_cases: this.node.cases.length });
+ else this.switch_control = SwitchControl.from_expr(expr, this.node.cases.length);
+ }
+
+ write_statement(stmt) {
+ this.to_write.push(stmt);
+ }
+
+ store_memory(store, reg) {
+ const source = store.source;
+ const dest = store.dest;
+ if (dest instanceof SubroutineArg) {
+ if (dest.value >= this.stack_info.global_info.arch.home_space_size) this.subroutine_args.set(dest.value, source);
+ return;
+ }
+ let raw_value = source;
+ while (raw_value instanceof Cast && raw_value.reinterpret) raw_value = raw_value.expr;
+ if (dest instanceof LocalVar) {
+ this.stack_info.add_local_var(dest);
+ this.local_var_writes.set(dest, [reg, raw_value, false]);
+ }
+ if ((dest instanceof LocalVar || dest instanceof PassedInArg) && pyeq(early_unwrap(raw_value), dest)) return;
+ source.use();
+ dest.use();
+ this.prevent_later_value_uses(dest);
+ this.prevent_later_function_calls();
+ this.write_statement(store);
+ }
+
+ push_subroutine_arg(source) {
+ const m = new Map();
+ for (const [offset, arg] of this.subroutine_args) m.set(offset + 4, arg);
+ this.subroutine_args = m;
+ this.subroutine_args.set(0, source);
+ }
+
+ _reg_probably_meant_as_function_argument(reg, call_instr) {
+ for (const source of this.stack_info.flow_graph.instr_inputs.get(call_instr).get(reg)) {
+ const uses = this.stack_info.flow_graph.instr_uses.get(source).get(reg);
+ pyassert(uses.has(call_instr));
+ if (uses.length === 1 && source instanceof InstrRef && source.instruction.function_target === null && call_instr.instruction.function_target !== reg) return true;
+ }
+ return false;
+ }
+
+ make_function_call(fn_target, outputs) {
+ const call_instr = this.regs.current_instr_ref();
+ const arch = this.stack_info.global_info.arch;
+ fn_target = as_function_ptr(fn_target);
+ const fn_sig = fn_target.type.get_function_pointer_signature();
+ pyassert(fn_sig !== null, "known function pointers must have a signature");
+
+ const instr_inputs = this.stack_info.flow_graph.instr_inputs.get(call_instr);
+ const likely_regs = new Map();
+ for (const [reg, data] of this.regs.contents) {
+ if (!arch.argument_regs.includes(reg)) likely_regs.set(reg, false);
+ else if (
+ (arch.arch === Target.ArchEnum.PPC || arch.arch === Target.ArchEnum.ARM) &&
+ !fn_sig.is_variadic &&
+ (data.meta.inherited || data.meta.function_return || arch.arch === Target.ArchEnum.ARM) &&
+ !this._reg_probably_meant_as_function_argument(reg, call_instr)
+ ) {
+ likely_regs.set(reg, false);
+ } else if ([...instr_inputs.get(reg)].every((source) => !(source instanceof InstrRef) || source.instruction.in_pattern)) {
+ likely_regs.set(reg, false);
+ } else likely_regs.set(reg, true);
+ }
+
+ const abi = arch.function_abi(fn_sig, likely_regs, { for_call: true });
+
+ const func_args = [];
+ for (const slot of abi.arg_slots) {
+ let expr;
+ if (slot.loc.reg) expr = this.regs.get(slot.loc.reg);
+ else {
+ const offset = slot.loc.offset;
+ pyassert(offset !== null);
+ if (this.subroutine_args.has(offset)) {
+ expr = this.subroutine_args.get(offset);
+ this.subroutine_args.delete(offset);
+ } else expr = new ErrorExpr(`Unable to find stack arg ${format(offset, "#x")} in block`);
+ }
+ func_args.push(CommentExpr.wrap(as_type(expr, slot.type, true), slot.comment));
+ }
+
+ for (const slot of abi.possible_slots) {
+ pyassert(slot.loc.reg !== null);
+ func_args.push(this.regs.get(slot.loc.reg));
+ }
+
+ for (const [, arg] of sorted(this.subroutine_args.entries(), (e) => e[0])) {
+ if (fn_sig.params_known && !fn_sig.is_variadic) func_args.push(CommentExpr.wrap(arg, "extra?"));
+ else func_args.push(arg);
+ }
+
+ if (!fn_sig.params_known) {
+ while (func_args.length > fn_sig.params.length) fn_sig.params.push(new FunctionParam());
+ const n = Math.min(func_args.length, fn_sig.params.length);
+ for (let i = 0; i < n; i++) func_args[i] = as_type(func_args[i], fn_sig.params[i].type.decay(), true);
+ }
+
+ this.subroutine_args.clear();
+
+ const source = this.regs.current_instr_ref();
+ let call = new FuncCall(fn_target, func_args, fn_sig.return_type.weaken_void_ptr());
+ call = this._eval_once(call, { emit_exactly_once: true, transparent: false, reg: new Register("ret"), source });
+
+ this.clear_caller_save_regs();
+ this.maybe_clear_local_var_writes(func_args);
+ this.prevent_later_function_calls();
+ this.prevent_later_reads();
+
+ const return_reg_vals = arch.function_return(call);
+ for (const out of outputs) {
+ if (!(out instanceof Register)) continue;
+ if (!return_reg_vals.has(out)) throw new Error(`KeyError: ${out}`);
+ const val = return_reg_vals.get(out);
+ this.set_reg_real(out, val, { transparent: false, function_return: true });
+ }
+ this.has_function_call = true;
+ }
+}
+
+export function evaluate_instruction(instr_ref, state) {
+ const instr = instr_ref.instruction;
+ if (instr.is_return) pyassert(state.node instanceof ReturnNode);
+ if (instr.is_conditional) pyassert(state.branch_condition === null && state.switch_control === null);
+ if (instr.eval_fn !== null) {
+ const args = new InstrArgs(instr_ref, instr.args, state.regs, state.stack_info);
+ instr.eval_fn(state, args);
+ }
+ if (instr.is_conditional) pyassert(state.branch_condition !== null || state.switch_control !== null);
+}
+
+/** Given a node and current register contents, return a BlockInfo containing the translated AST. */
+export function translate_node_body(state) {
+ for (const instr_ref of state.node.block.instruction_refs) {
+ state.regs.set_current_instr(instr_ref, () => evaluate_instruction(instr_ref, state));
+ }
+ if (state.branch_condition !== null) state.branch_condition.use();
+ if (state.switch_control !== null) state.switch_control.control_expr.use();
+ return new BlockInfo({
+ to_write: state.to_write,
+ return_value: null,
+ switch_control: state.switch_control,
+ branch_condition: state.branch_condition,
+ final_register_states: state.regs,
+ has_function_call: state.has_function_call,
+ });
+}
+
+function py_exc_str(e) {
+ if (e instanceof DecompFailure) return e.message;
+ if (e && typeof e.message === "string") return e.message;
+ return String(e);
+}
+
+export function translate_block(state, options) {
+ const node = state.node;
+ if (options.debug) print(`\nNode in question: ${node}`);
+ let block_info;
+ try {
+ block_info = translate_node_body(state);
+ if (options.debug) print(String(block_info));
+ } catch (e0) {
+ let e = e0;
+ if (options.stop_on_error) throw e;
+ let instr = null;
+ if (e instanceof InstrProcessingFailure && e.cause instanceof Error) {
+ instr = e.instr;
+ e = e.cause;
+ }
+ let emsg;
+ if (e instanceof DecompFailure) {
+ emsg = py_exc_str(e);
+ print(emsg);
+ } else {
+ print(`Traceback (most recent call last):\n${e && e.stack ? e.stack : e}`, { __print_opts: true, stderr: true });
+ emsg = py_exc_str(e) || `${e && e.name ? e.name : "Error"}`;
+ const parts = emsg.trim().split("\n");
+ emsg = parts[parts.length - 1].trim();
+ }
+ const error_stmts = [new CommentStmt(`Error: ${emsg}`)];
+ if (instr !== null) {
+ print(`Error occurred while processing instruction: ${instr}`, { __print_opts: true, stderr: true });
+ error_stmts.push(new CommentStmt(`At instruction: ${instr}`));
+ }
+ print({ __print_opts: true, stderr: true });
+ block_info = new BlockInfo({
+ to_write: error_stmts,
+ return_value: null,
+ switch_control: null,
+ branch_condition: new ErrorExpr(),
+ final_register_states: state.regs,
+ has_function_call: false,
+ });
+ }
+ return block_info;
+}
+
+/** Create a NodeState for translating a child of a node in the dominator tree. */
+export function create_dominated_node_state(parent_state, child, used_naive_phis) {
+ const stack_info = parent_state.stack_info;
+ const new_regs = new RegInfo({ stack_info });
+ const child_state = new NodeState({ node: child, regs: new_regs, stack_info });
+ for (const [reg, data] of parent_state.regs.contents) {
+ new_regs.global_set_with_meta(reg, data.value, new RegMeta({ inherited: true, force: data.meta.force, initial: data.meta.initial }));
+ }
+
+ const phi_regs = [...locs_clobbered_until_dominator(child)].filter((r) => r instanceof Register);
+ for (const reg of phi_regs) {
+ let [sources, uses_dominator] = reg_sources(child, reg);
+
+ const inherited_phi = stack_info.get_planned_inherited_phi(child, reg);
+ if (inherited_phi !== null) {
+ if (inherited_phi === PhiInheritSource.DOMINATOR) {
+ const meta = new_regs.get_meta(reg);
+ if (meta !== null) {
+ new_regs.update_meta(reg, dcreplace(meta, { initial: false }));
+ continue;
+ }
+ } else {
+ let found_par_value = null;
+ for (const parent of child.parents) {
+ if (parent.block.block_info) {
+ const par_regs = get_block_info(parent).final_register_states;
+ if (!par_regs.contents.has(reg)) throw new Error(`KeyError: ${reg}`);
+ const par_value = par_regs.contents.get(reg).value;
+ if (par_value instanceof EvalOnceExpr && par_value.trivial) {
+ found_par_value = par_value;
+ break;
+ }
+ }
+ }
+ if (found_par_value !== null) {
+ const new_val = new EvalOnceExpr({
+ wrapped_expr: found_par_value.wrapped_expr,
+ var: new Var(stack_info, "_m2c_inherited_phi", { is_planned: false, type: found_par_value.type }),
+ type: found_par_value.type,
+ sources,
+ emit_exactly_once: false,
+ trivial: true,
+ transparent: true,
+ is_fictive_temp: false,
+ });
+ new_regs.global_set_with_meta(reg, new_val, new RegMeta({ inherited: true }));
+ continue;
+ }
+ }
+ }
+
+ if (uses_dominator) {
+ const dom_expr = parent_state.regs.get_raw(reg);
+ if (dom_expr === null) sources = [];
+ else if (dom_expr instanceof EvalOnceExpr || dom_expr instanceof PlannedPhiExpr || dom_expr instanceof NaivePhiExpr) sources.push(...dom_expr.sources);
+ else assert_never(dom_expr);
+ }
+
+ if (sources.length) {
+ let expr;
+ const v = stack_info.get_planned_var(reg, sources[0]);
+ if (v !== null && sources.slice(1).every((s) => stack_info.get_planned_var(reg, s) === v)) {
+ expr = new PlannedPhiExpr(v, v.type, sources);
+ } else {
+ expr = new NaivePhiExpr({ reg, node: child, type: Type.any_reg(), sources, uses_dominator, used_naive_phis });
+ }
+ new_regs.global_set_with_meta(reg, expr, new RegMeta({ inherited: true }));
+ } else if (new_regs.has(reg)) {
+ new_regs.delete(reg);
+ }
+ }
+
+ const [clobbered_vars, has_fn_call] = find_clobbers_until_dominator(stack_info, child);
+ child_state.prevent_later_var_uses(clobbered_vars);
+
+ if (child.parents.length !== 1 || parent_state.node.children().length !== 1) child_state.prevent_later_function_calls();
+ if (has_fn_call) child_state.prevent_later_reads();
+ return child_state;
+}
+
+/** Do translation for all non-terminal nodes, attaching block info to them. */
+export function translate_all_blocks(initial_state, used_naive_phis, return_blocks, options) {
+ const translate_stack = [[null, initial_state.node]];
+ while (translate_stack.length) {
+ const [parent_state, node0] = translate_stack.pop();
+ let state;
+ if (parent_state === null) state = initial_state;
+ else state = create_dominated_node_state(parent_state, node0, used_naive_phis);
+ const block_info = translate_block(state, options);
+ const node = state.node;
+ node.block.add_block_info(block_info);
+ if (node instanceof ReturnNode) return_blocks.push(block_info);
+ for (const child of [...state.node.immediately_dominates].reverse()) {
+ if (!(child instanceof TerminalNode)) translate_stack.push([state, child]);
+ }
+ }
+}
+
+/** After translating a function, perform a final type-resolution pass. */
+export function resolve_types_late(stack_info) {
+ for (const location of [...stack_info.weak_stack_var_types.keys()]) stack_info.get_stack_var(location, { store: false });
+ const struct_type_map = stack_info.get_struct_type_map();
+ for (const [v, offset_type_map] of struct_type_map) {
+ if (offset_type_map.size === 1 && offset_type_map.has(0)) {
+ const type = offset_type_map.get(0);
+ v.type.unify(Type.ptr(type));
+ }
+ }
+}
+
+export class FunctionInfo {
+ constructor(stack_info, flow_graph, return_type, symbol) {
+ this.stack_info = stack_info;
+ this.flow_graph = flow_graph;
+ this.return_type = return_type;
+ this.symbol = symbol;
+ }
+}
+
+export class FailedToGenerateInitializer extends Error {
+ constructor(reason) {
+ super(reason);
+ this.reason = reason;
+ }
+}
+
+export class GlobalInfo {
+ constructor(asm_data, arch, target, local_functions, typemap, typepool, { deterministic_vars, stack_spill_detection }) {
+ this.asm_data = asm_data;
+ this.arch = arch;
+ this.target = target;
+ this.local_functions = local_functions; // Set
+ this.typemap = typemap;
+ this.typepool = typepool;
+ this.deterministic_vars = deterministic_vars;
+ this.stack_spill_detection = stack_spill_detection;
+ this.global_symbol_map = new Map();
+ this.persistent_function_state = new DefaultMap(() => new PersistentFunctionState());
+ }
+
+ get_persistent_function_state(func_name) {
+ return this.persistent_function_state.get(func_name);
+ }
+
+ asm_data_value(sym_name) {
+ return this.asm_data.values.get(sym_name) ?? null;
+ }
+
+ address_of_gsym(sym_name) {
+ let sym;
+ if (this.global_symbol_map.has(sym_name)) sym = this.global_symbol_map.get(sym_name);
+ else {
+ const c_sym_name = this.arch.c_symbol_name(sym_name);
+ let demangled_symbol = null;
+ let demangled_str = null;
+ if (this.target.language === Target.LanguageEnum.CXX && this.target.compiler === Target.CompilerEnum.MWCC) {
+ try {
+ demangled_symbol = demangle_codewarrior_parse(sym_name);
+ demangled_str = String(demangled_symbol);
+ } catch (e) {
+ if (!(e instanceof ValueError)) throw e;
+ demangled_symbol = null;
+ }
+ }
+ sym = new GlobalSymbol({ c_symbol_name: c_sym_name, type: Type.any(), asm_data_entry: this.asm_data_value(sym_name), demangled_str });
+ this.global_symbol_map.set(sym_name, sym);
+
+ if (this.target.language === Target.LanguageEnum.CXX && this.target.compiler === Target.CompilerEnum.MWCC && sym_name.startsWith("__vt__") && sym.asm_data_entry !== null) {
+ sym.type.unify(this.vtable_type(sym_name, sym.asm_data_entry));
+ }
+
+ const fn = this.typemap.functions.get(c_sym_name) ?? null;
+ let ctype;
+ if (fn !== null) ctype = fn.type;
+ else ctype = this.typemap.var_types.get(c_sym_name) ?? null;
+
+ if (ctype !== null) {
+ sym.symbol_in_context = true;
+ sym.initializer_in_typemap = this.typemap.vars_with_initializers.has(c_sym_name);
+ let type;
+ if (this.typepool.unk_inference && is_unk_type(ctype, this.typemap)) type = Type.gsym_unk_ctype(ctype, this.typemap, this.typepool);
+ else type = Type.ctype(ctype, this.typemap, this.typepool);
+ sym.type.unify(type);
+ if (!this.typepool.unknown_decls.has(c_sym_name)) sym.type_provided = true;
+ } else if (this.local_functions.has(sym_name)) {
+ sym.type.unify(Type.function());
+ }
+
+ if (demangled_symbol !== null) sym.type.unify(Type.demangled_symbol(this.typemap, this.typepool, demangled_symbol));
+ }
+ return new AddressOf(sym, { type: sym.type.reference() });
+ }
+
+ /** Parse MWCC vtable data to create a custom struct to represent it. */
+ vtable_type(sym_name, asm_data_entry) {
+ const size = asm_data_entry.size_range_bytes()[1];
+ const struct = StructDeclaration.unknown(this.typepool, size, sym_name, 4);
+ let offset = 0;
+ for (const entry of asm_data_entry.data) {
+ if (entry instanceof Uint8Array) {
+ if (entry.length % 4 !== 0) throw new DecompFailure(`Unable to parse misaligned vtable data in ${sym_name}`);
+ for (let i = 0; i < floordiv(entry.length, 4); i++) {
+ const field_name = `${struct.new_field_prefix}${format(offset, "X")}`;
+ struct.try_add_field(Type.reg32({ likely_float: false }), offset, field_name, 4);
+ offset += 4;
+ }
+ } else {
+ const sym = entry.as_symbol_without_addend();
+ if (sym === null) throw new DecompFailure(`Unable to parse vtable data in ${sym_name}`);
+ let entry_name = sym;
+ try {
+ const demangled_field_sym = demangle_codewarrior_parse(sym);
+ if (demangled_field_sym.name.qualified_name !== null && demangled_field_sym.name.qualified_name !== undefined) {
+ const q = demangled_field_sym.name.qualified_name;
+ entry_name = String(q[q.length - 1]);
+ }
+ } catch (e) {
+ if (!(e instanceof ValueError)) throw e;
+ }
+ const field = struct.try_add_field(this.address_of_gsym(sym).type, offset, entry_name, 4);
+ pyassert(field !== null);
+ field.known = true;
+ offset += 4;
+ }
+ }
+ return Type.struct(struct);
+ }
+
+ /** Return true if the function exists in the context, and has no return value */
+ is_function_known_void(sym_name) {
+ const fn = this.typemap.functions.get(sym_name) ?? null;
+ if (fn === null) return false;
+ return fn.ret_type === null;
+ }
+
+ initializer_for_symbol(sym, fmt) {
+ pyassert(sym.asm_data_entry !== null);
+ const data = [...sym.asm_data_entry.data];
+
+ const read_uint = (n) => {
+ pyassert(0 < n && n <= 16);
+ if (!data.length) throw new FailedToGenerateInitializer("not enough data");
+ if (!(data[0] instanceof Uint8Array)) {
+ const arg = data[0].data;
+ throw new FailedToGenerateInitializer(`cannot parse ${arg} as integer`);
+ }
+ if (data[0].length < n) {
+ if (data.length > 1) {
+ const s = data[1];
+ pyassert(s instanceof AsmSymbolicData);
+ throw new FailedToGenerateInitializer(`partial read of ${s.data}`);
+ } else throw new FailedToGenerateInitializer("not enough data");
+ }
+ let bs = data[0].slice(0, n);
+ data[0] = data[0].slice(n);
+ if (!data[0].length) data.shift();
+ if (!this.target.is_big_endian()) bs = bs.reverse();
+ let value = 0n;
+ for (const b of bs) value = (value << 8n) | BigInt(b);
+ return Number(value);
+ };
+
+ const try_read_pointer = () => {
+ if (!data.length || data[0] instanceof Uint8Array) return null;
+ const label = data[0].as_symbol_without_addend();
+ if (label === null) return null;
+ data.shift();
+ const expr = this.address_of_gsym(label);
+ expr.use();
+ return expr;
+ };
+
+ const for_type = (type) => {
+ if (type.is_struct() || type.is_array()) {
+ const struct_fields = type.get_initializer_fields();
+ if (!struct_fields || !struct_fields.length) {
+ if (type.is_array()) throw new FailedToGenerateInitializer("unsized array");
+ throw new FailedToGenerateInitializer("confusing struct layout");
+ }
+ const members = [];
+ for (const field of struct_fields) {
+ if (typeof field === "number") {
+ for (let i = 0; i < field; i++) {
+ const padding = read_uint(1);
+ if (padding !== 0) throw new FailedToGenerateInitializer("non-zero padding");
+ }
+ } else members.push(for_type(field));
+ }
+ return fmt.format_array(members);
+ }
+ if (type.is_reg()) {
+ const size = type.get_size_bytes();
+ if (!size) throw new FailedToGenerateInitializer("unknown size");
+ if (size === 4) {
+ const ptr = try_read_pointer();
+ if (ptr !== null) return as_type(ptr, type, true).format(fmt);
+ }
+ const value = read_uint(size);
+ const enum_name = type.get_enum_name(value);
+ if (enum_name !== null) return enum_name;
+ const expr = as_type(new Literal(value), type, true);
+ return elide_literal_casts(expr).format(fmt);
+ }
+ if (type.get_size_bits() === null) throw new FailedToGenerateInitializer("unknown type");
+ throw new FailedToGenerateInitializer("bad type");
+ };
+
+ const type = sym.type.get_array()[0];
+ if (sym.is_string_constant() && type !== null && type.get_size_bytes() === 1) return sym.format_string_constant(fmt);
+ return for_type(sym.type);
+ }
+
+ find_forward_declares_needed(functions) {
+ const funcs_seen = new Set();
+ const forward_declares_needed = this.asm_data.mentioned_labels;
+ for (const func of functions) {
+ funcs_seen.add(func.stack_info.function.name);
+ for (const instr of func.stack_info.function.body) {
+ if (!(instr instanceof Instruction)) continue;
+ for (const arg of instr.args) {
+ let func_name;
+ if (arg instanceof AsmGlobalSymbol) func_name = arg.symbol_name;
+ else if (arg instanceof Macro && arg.argument instanceof AsmGlobalSymbol) func_name = arg.argument.symbol_name;
+ else continue;
+ if (this.local_functions.has(func_name)) {
+ if (!funcs_seen.has(func_name)) forward_declares_needed.add(func_name);
+ }
+ }
+ }
+ }
+ return forward_declares_needed;
+ }
+
+ global_decls(fmt, decls, functions) {
+ const forward_declares_needed = this.find_forward_declares_needed(functions);
+ const lines = [];
+ const processed_names = new Set();
+ for (;;) {
+ const names = new Set();
+ for (const [n, s] of this.global_symbol_map) if (s.is_referenced) names.add(n);
+ if (decls === Options.GlobalDeclsEnum.ALL) {
+ for (const [name, ent] of this.asm_data.values) if (!ent.is_text) names.add(name);
+ }
+ for (const p of processed_names) names.delete(p);
+ if (!names.size) break;
+ for (const name of sorted(names)) {
+ processed_names.add(name);
+ const sym = this.address_of_gsym(name).expr;
+ pyassert(sym instanceof GlobalSymbol);
+ let data_entry = sym.asm_data_entry;
+
+ if (data_entry !== null && data_entry.is_text) {
+ if (!sym.type.is_function()) continue;
+ data_entry = null;
+ }
+
+ const is_in_file = data_entry !== null || this.local_functions.has(name);
+ const is_global = sym.symbol_in_context;
+ const is_const = data_entry !== null && data_entry.is_readonly;
+
+ if (data_entry && data_entry.is_jtbl) continue;
+ if (is_in_file && is_global && sym.type.is_function()) continue;
+ if (this.local_functions.size === 1 && this.local_functions.has(name)) continue;
+ if (!is_in_file && sym.type_provided) continue;
+
+ let data_entry_order;
+ if (data_entry) {
+ const [file, index] = data_entry.sort_order;
+ data_entry_order = data_entry.is_bss && fmt.backwards_bss ? [file, index * -1] : [file, index];
+ } else data_entry_order = ["", 0];
+
+ const sort_order = [!sym.type.is_function(), is_in_file, !is_in_file ? is_global : false, is_const, data_entry_order, name];
+ let qualifier = "";
+ let value = null;
+ const comments = [];
+
+ if (is_in_file && is_global) qualifier = "";
+ else if (is_in_file) qualifier = "static";
+ else qualifier = "extern";
+
+ if (sym.type.is_function()) {
+ comments.push(qualifier);
+ qualifier = "";
+ }
+
+ let [element_type, array_dim] = sym.type.get_array();
+ const is_vla = element_type !== null && (array_dim === null || array_dim <= 0);
+ if (data_entry && (!sym.type_provided || is_vla)) {
+ if (element_type === null) element_type = sym.type;
+ const type_size = element_type.get_size_bytes();
+ if (type_size) {
+ const [potential_dim, extra_bytes] = sym.potential_array_dim(type_size);
+ if (potential_dim === 0 && extra_bytes > 0) comments.push(`type too large by ${fmt.format_int(type_size - extra_bytes)}`);
+ else if (potential_dim > 1 || is_vla) {
+ array_dim = potential_dim;
+ sym.type = Type.array(element_type, array_dim);
+ }
+ if (potential_dim !== 0 && extra_bytes > 0) comments.push(`extra bytes: ${fmt.format_int(extra_bytes)}`);
+ }
+ }
+
+ if (data_entry && !data_entry.is_bss && !data_entry.is_text) {
+ try {
+ value = this.initializer_for_symbol(sym, fmt);
+ } catch (e) {
+ if (!(e instanceof FailedToGenerateInitializer)) throw e;
+ comments.push(`unable to generate initializer: ${e.reason}`);
+ }
+ }
+
+ if (is_const) {
+ comments.push("const");
+ if (sym.is_string_constant()) continue;
+ if (array_dim === null && data_entry !== null && data_entry.used_as_literal) continue;
+ }
+
+ if (decls === Options.GlobalDeclsEnum.NONE) continue;
+ if (decls !== Options.GlobalDeclsEnum.ALL && sym.initializer_in_typemap) continue;
+ if (decls !== Options.GlobalDeclsEnum.ALL && this.target.language === Target.LanguageEnum.CXX && this.target.compiler === Target.CompilerEnum.MWCC && name.startsWith("__vt__")) continue;
+ if (sym.type.is_function() && decls !== Options.GlobalDeclsEnum.ALL && this.local_functions.has(name) && !forward_declares_needed.has(name)) continue;
+
+ qualifier = qualifier ? `${qualifier} ` : "";
+ const value_str = value ? ` = ${value}` : "";
+ lines.push([sort_order, fmt.with_comments(`${qualifier}${sym.type.to_decl(name, fmt)}${value_str};`, comments) + "\n"]);
+ }
+ }
+ const sorted_lines = sorted(lines, (l) => l);
+ return sorted_lines.map(([, line]) => line).join("");
+ }
+}
+
+/** Modify the `outputs` list of function call Instructions using the context file. */
+export function narrow_func_call_outputs(fn, global_info) {
+ for (const instr of fn.body) {
+ if (instr instanceof Instruction && instr.function_target instanceof AsmGlobalSymbol && global_info.is_function_known_void(instr.function_target.symbol_name)) {
+ instr.outputs.length = 0;
+ }
+ }
+}
+
+/** Set up stack_info planned vars from state from earlier translation passes. */
+export function setup_planned_vars(stack_info, persistent_state) {
+ const planned_vars = new DefaultMap(() => []);
+ for (const [key, persistent_var] of persistent_state.planned_vars) planned_vars.get(persistent_var.get_representative()).push(key);
+ for (const keys of planned_vars.values()) {
+ const reg = keys[0][0];
+ const reg_name = stack_info.function.reg_formatter.format(reg);
+ let prefix = `var_${reg_name}`;
+ if (stack_info.global_info.deterministic_vars) {
+ const lineno = Math.min(...keys.map(([, source]) => (!(source instanceof InstrRef) ? 0 : source.instruction.meta.lineno)));
+ prefix = `${prefix}_${lineno}`;
+ }
+ const v = new Var(stack_info, { prefix, is_planned: true, type: Type.any_reg() });
+ stack_info.temp_vars.push(v);
+ for (const key of keys) stack_info.planned_vars.set(key, v);
+ }
+}
+
+/** Set up per-register planned vars based on command line flags. */
+export function setup_reg_vars(stack_info, options) {
+ const arch = stack_info.global_info.arch;
+ let reg_vars;
+ const rv = options.reg_vars;
+ if (rv.length === 1 && rv[0] === "saved") reg_vars = arch.saved_regs;
+ else if (rv.length === 1 && rv[0] === "most") reg_vars = [...arch.saved_regs, ...arch.simple_temp_regs];
+ else if (rv.length === 1 && rv[0] === "all") reg_vars = [...arch.saved_regs, ...arch.simple_temp_regs, ...arch.argument_regs];
+ else reg_vars = rv.map((x) => stack_info.function.reg_formatter.parse(x, arch));
+ for (const reg of reg_vars) {
+ const reg_name = stack_info.function.reg_formatter.format(reg);
+ stack_info.add_register_var(reg, reg_name);
+ }
+}
+
+/** Set up initial register contents for translation. */
+export function setup_initial_registers(state, fn_sig) {
+ const stack_info = state.stack_info;
+ const arch = stack_info.global_info.arch;
+ state.set_initial_reg(arch.stack_pointer_reg, new GlobalSymbol("sp", { type: Type.ptr() }), new RegMeta({ initial: true }));
+ for (const reg of arch.saved_regs) state.set_initial_reg(reg, stack_info.saved_reg_symbol(reg.register_name), new RegMeta({ initial: true }));
+
+ const make_arg = (loc, type) => {
+ if (loc.offset !== null) pyassert(pymod(loc.offset, 4) === 0);
+ return new PassedInArg(loc, { stack_info, type });
+ };
+
+ const likely_regs = new Map();
+ for (const reg of arch.argument_regs) likely_regs.set(reg, true);
+ const abi = arch.function_abi(fn_sig, likely_regs, { for_call: false });
+ for (const slot of abi.arg_slots) {
+ const type = stack_info.add_known_param(slot.loc, slot.name, slot.type);
+ if (slot.loc.reg !== null) state.set_initial_reg(slot.loc.reg, make_arg(slot.loc, type), new RegMeta({ uninteresting: true, initial: true }));
+ }
+ for (const slot of abi.possible_slots) {
+ if (slot.loc.reg !== null) state.set_initial_reg(slot.loc.reg, make_arg(slot.loc, slot.type), new RegMeta({ uninteresting: true, initial: true }));
+ }
+}
+
+/** Given a function, produce a FlowGraph with AST transformations for each block. */
+export function translate_to_ast(fn, flow_graph, options, global_info) {
+ const persistent_state = global_info.get_persistent_function_state(fn.name);
+ const stack_info = get_stack_info(fn, persistent_state, global_info, flow_graph);
+ const state = new NodeState({ node: flow_graph.entry_node(), regs: new RegInfo({ stack_info }), stack_info });
+
+ setup_planned_vars(stack_info, persistent_state);
+ setup_reg_vars(stack_info, options);
+
+ const fn_sym = global_info.address_of_gsym(fn.name).expr;
+ pyassert(fn_sym instanceof GlobalSymbol);
+
+ const fn_type = fn_sym.type;
+ fn_type.unify(Type.function());
+ const fn_sig = Type.ptr(fn_type).get_function_pointer_signature();
+ pyassert(fn_sig !== null, "fn_type is known to be a function");
+ stack_info.is_variadic = fn_sig.is_variadic;
+
+ setup_initial_registers(state, fn_sig);
+
+ if (options.debug) {
+ print(String(stack_info));
+ print("\nNow, we attempt to translate:");
+ }
+
+ const used_naive_phis = [];
+ const return_blocks = [];
+ translate_all_blocks(state, used_naive_phis, return_blocks, options);
+
+ const arch = global_info.arch;
+ for (const [reg] of arch.base_return_regs) propagate_register_meta(flow_graph.nodes, reg);
+
+ const return_type = fn_sig.return_type;
+ let return_reg = null;
+ if (!options.void && !return_type.is_void()) return_reg = determine_return_register(return_blocks, fn_sym.type_provided, arch);
+
+ if (return_reg !== null) {
+ const [reg, is_floating] = return_reg;
+ if (is_floating) return_type.unify(Type.floatish());
+ else return_type.unify(Type.intptr());
+ for (const b of return_blocks) {
+ if (b.final_register_states.has(reg)) {
+ let ret_val = b.final_register_states.get(reg);
+ ret_val = as_type(ret_val, return_type, true);
+ ret_val.use();
+ b.return_value = ret_val;
+ }
+ }
+ } else {
+ return_type.unify(Type.void());
+ }
+
+ assign_naive_phis(used_naive_phis, stack_info);
+
+ if (!fn_sig.params_known) {
+ while (fn_sig.params.length < stack_info.arguments.length) fn_sig.params.push(new FunctionParam());
+ const n = Math.min(fn_sig.params.length, stack_info.arguments.length);
+ for (let i = 0; i < n; i++) {
+ const param = fn_sig.params[i];
+ const arg = stack_info.arguments[i];
+ param.type.unify(arg.type);
+ if (!param.name) param.name = arg.format(new Formatter());
+ }
+ }
+
+ resolve_types_late(stack_info);
+ return new FunctionInfo(stack_info, flow_graph, return_type, fn_sym);
+}
+
+// Re-exports used by arch modules
+export { compare, pyin, has, AssertionError, ArchC };
diff --git a/packages/romdev-m2c/src/types.js b/packages/romdev-m2c/src/types.js
new file mode 100644
index 00000000..c50876af
--- /dev/null
+++ b/packages/romdev-m2c/src/types.js
@@ -0,0 +1,1164 @@
+// Port of m2c/types.py
+import { c_ast as ca } from "romdev-pycparser";
+import { UndefinedStructError, is_unk_type, parse_constant_int, parse_function, parse_struct, primitive_size, resolve_typedefs, set_decl_name, to_c } from "./c_types.js";
+import { CxxSymbol, CxxTerm } from "./demangle_codewarrior.js";
+import { DecompFailure, assert_never } from "./error.js";
+import { Formatter } from "./options.js";
+import { bnot, compare, floordiv, format, pymod, pyassert, sorted } from "./py.js";
+
+/** Mutable shared state for Types, maintaining the set of available struct types. */
+export class TypePool {
+ constructor({ unknown_field_prefix, unk_inference, union_field_overrides = new Map() }) {
+ this.unknown_field_prefix = unknown_field_prefix;
+ this.unk_inference = unk_inference;
+ this.structs = new Set();
+ this.structs_by_tag_name = new Map();
+ this.structs_by_ctype = new Map();
+ this.unknown_decls = new Map();
+ this.warnings = [];
+ this.union_field_overrides = union_field_overrides;
+ }
+
+ /** Return the StructDeclaration for a given ctype struct, if known */
+ get_struct_for_ctype(ctype) {
+ const struct = this.structs_by_ctype.get(ctype);
+ if (struct !== undefined) return struct;
+ if (ctype.name !== null && ctype.name !== undefined) return this.structs_by_tag_name.get(ctype.name) ?? null;
+ return null;
+ }
+
+ get_or_create_struct_by_tag_name(tag_name, typemap, { size = null, with_typedef = false } = {}) {
+ let struct = this.get_struct_by_tag_name(tag_name, typemap);
+ if (struct !== null) return struct;
+ struct = StructDeclaration.unknown(this, size, tag_name, 4);
+ if (with_typedef) struct.typedef_name = tag_name;
+ return struct;
+ }
+
+ get_struct_by_tag_name(tag_name, typemap) {
+ const struct = this.structs_by_tag_name.get(tag_name);
+ if (struct !== undefined) return struct;
+ if (typemap !== null && typemap !== undefined) {
+ const cstruct = typemap.structs.get(tag_name);
+ if (cstruct !== undefined) {
+ const type = Type.ctype(cstruct.type, typemap, this);
+ return type.get_struct_declaration();
+ }
+ }
+ return null;
+ }
+
+ /** Add the struct declaration to the set of known structs for later access */
+ add_struct(struct, ctype_or_tag_name) {
+ this.structs.add(struct);
+ let tag_name;
+ if (typeof ctype_or_tag_name === "string") tag_name = ctype_or_tag_name;
+ else {
+ const ctype = ctype_or_tag_name;
+ tag_name = ctype.name ?? null;
+ this.structs_by_ctype.set(ctype, struct);
+ }
+ if (tag_name !== null) {
+ pyassert(!this.structs_by_tag_name.has(tag_name), `Duplicate tag: ${tag_name}`);
+ this.structs_by_tag_name.set(tag_name, struct);
+ }
+ }
+
+ format_type_declarations(fmt, stack_structs) {
+ const decls = [];
+ for (const struct of sorted(this.structs, (s) => s.tag_name || s.typedef_name || "")) {
+ if (!stack_structs && struct.is_stack) continue;
+ if (struct.fields.some((f) => !f.known) || struct.is_stack) decls.push(struct.format(fmt) + "\n");
+ }
+ return decls.join("\n");
+ }
+
+ /** Remove overlapping fields from all known structs */
+ prune_structs() {
+ for (const struct of this.structs) {
+ struct.prune_overlapping_fields();
+ struct.rename_inferred_vtables();
+ }
+ }
+}
+
+export class TypeData {
+ static K_INT = 1 << 0;
+ static K_PTR = 1 << 1;
+ static K_FLOAT = 1 << 2;
+ static K_FN = 1 << 3;
+ static K_VOID = 1 << 4;
+ static K_ARRAY = 1 << 5;
+ static K_STRUCT = 1 << 6;
+ static K_INTPTR = TypeData.K_INT | TypeData.K_PTR;
+ static K_ANYREG = TypeData.K_INT | TypeData.K_PTR | TypeData.K_FLOAT;
+ static K_ANY = TypeData.K_INT | TypeData.K_PTR | TypeData.K_FLOAT | TypeData.K_FN | TypeData.K_VOID | TypeData.K_ARRAY | TypeData.K_STRUCT;
+ static SIGNED = 1;
+ static UNSIGNED = 2;
+ static ANY_SIGN = 3;
+
+ constructor({
+ kind = TypeData.K_ANY,
+ likely_kind = TypeData.K_ANY,
+ size_bits = null,
+ uf_parent = null,
+ sign = TypeData.ANY_SIGN,
+ ptr_to = null,
+ fn_sig = null,
+ array_dim = null,
+ struct = null,
+ enum: enum_ = null,
+ new_field_within = new Set(),
+ } = {}) {
+ this.kind = kind;
+ this.likely_kind = likely_kind;
+ this.size_bits = size_bits;
+ this.uf_parent = uf_parent;
+ this.sign = sign;
+ this.ptr_to = ptr_to;
+ this.fn_sig = fn_sig;
+ this.array_dim = array_dim;
+ this.struct = struct;
+ this.enum = enum_;
+ this.new_field_within = new_field_within;
+ pyassert(this.kind);
+ this.likely_kind &= this.kind;
+ }
+
+ get_representative() {
+ const equivalent_typedatas = new Set();
+ let root = this;
+ while (root.uf_parent !== null) {
+ pyassert(!equivalent_typedatas.has(root), "TypeData cycle detected");
+ equivalent_typedatas.add(root);
+ root = root.uf_parent;
+ }
+ for (const td of equivalent_typedatas) td.uf_parent = root;
+ return root;
+ }
+}
+
+const DEBUG_REPR_IDS = new Map();
+
+/**
+ * Type information for an expression, which may improve over time.
+ */
+export class Type {
+ constructor(_data) {
+ this._data = _data;
+ }
+
+ /** Try to set this type equal to another. Returns true on success. */
+ unify(other, { seen = null } = {}) {
+ const x = this.data();
+ const y = other.data();
+ if (x === y) return true;
+
+ if (seen === null) seen = new Set([x, y]);
+ else if (seen.has(x) || seen.has(y)) return false;
+ else seen = new Set([...seen, x, y]);
+
+ if (x.size_bits !== null && y.size_bits !== null && x.size_bits !== y.size_bits) return false;
+
+ let kind = x.kind & y.kind;
+ let likely_kind = x.likely_kind & y.likely_kind;
+ let size_bits = x.size_bits !== null ? x.size_bits : y.size_bits;
+ const ptr_to = x.ptr_to !== null ? x.ptr_to : y.ptr_to;
+ const fn_sig = x.fn_sig !== null ? x.fn_sig : y.fn_sig;
+ let array_dim = x.array_dim !== null ? x.array_dim : y.array_dim;
+ const struct = x.struct !== null ? x.struct : y.struct;
+ const enum_ = x.enum !== null ? x.enum : y.enum;
+ const sign = x.sign & y.sign;
+ if (![null, 32, 64].includes(size_bits)) kind &= ~TypeData.K_FLOAT;
+ if (![null, 32].includes(size_bits)) kind &= ~TypeData.K_PTR;
+ if (![null].includes(size_bits)) kind &= ~TypeData.K_FN;
+ if (![null, 0].includes(size_bits)) kind &= ~TypeData.K_VOID;
+ likely_kind &= kind;
+ if (kind === 0 || sign === 0) return false;
+ if (kind === TypeData.K_PTR) size_bits = 32;
+ if (sign !== TypeData.ANY_SIGN) pyassert(kind & TypeData.K_INTPTR);
+ if (enum_ !== null) pyassert(kind === TypeData.K_INT);
+ if (x.ptr_to !== null && y.ptr_to !== null) {
+ if (!x.ptr_to.unify(y.ptr_to, { seen })) return false;
+ }
+ if (x.fn_sig !== null && y.fn_sig !== null) {
+ if (!x.fn_sig.unify(y.fn_sig, { seen })) return false;
+ }
+ if (x.array_dim !== null && y.array_dim !== null) {
+ if (kind === TypeData.K_ARRAY) {
+ if (x.array_dim !== y.array_dim) return false;
+ } else {
+ pyassert(kind === TypeData.K_PTR);
+ if (x.array_dim !== y.array_dim) array_dim = 0;
+ }
+ }
+ if (x.struct !== null && y.struct !== null) {
+ if (!x.struct.unify(y.struct, { seen })) return false;
+ }
+ if (x.enum !== null && y.enum !== null) {
+ if (x.enum !== y.enum) return false;
+ }
+ if (x.new_field_within.has(y.struct) || y.new_field_within.has(x.struct)) return false;
+ x.kind = kind;
+ x.likely_kind = likely_kind;
+ x.size_bits = size_bits;
+ x.sign = sign;
+ x.ptr_to = ptr_to;
+ x.fn_sig = fn_sig;
+ x.array_dim = array_dim;
+ x.struct = struct;
+ x.enum = enum_;
+ for (const s of y.new_field_within) x.new_field_within.add(s);
+ y.uf_parent = x;
+ return true;
+ }
+
+ data() {
+ if (this._data.uf_parent === null) return this._data;
+ this._data = this._data.get_representative();
+ return this._data;
+ }
+
+ is_float() {
+ return this.data().kind === TypeData.K_FLOAT;
+ }
+ is_likely_float() {
+ const data = this.data();
+ return data.kind === TypeData.K_FLOAT || data.likely_kind === TypeData.K_FLOAT;
+ }
+ is_pointer() {
+ return this.data().kind === TypeData.K_PTR;
+ }
+ is_pointer_or_array() {
+ const k = this.data().kind;
+ return k === TypeData.K_PTR || k === TypeData.K_ARRAY;
+ }
+ is_int() {
+ return this.data().kind === TypeData.K_INT;
+ }
+ is_reg() {
+ return (this.data().kind & ~TypeData.K_ANYREG) === 0;
+ }
+ is_function() {
+ return this.data().kind === TypeData.K_FN;
+ }
+ is_void() {
+ return this.data().kind === TypeData.K_VOID;
+ }
+ is_array() {
+ return this.data().kind === TypeData.K_ARRAY;
+ }
+ is_struct() {
+ return this.data().kind === TypeData.K_STRUCT;
+ }
+ is_signed() {
+ return this.data().sign === TypeData.SIGNED;
+ }
+ is_unsigned() {
+ return this.data().sign === TypeData.UNSIGNED;
+ }
+ get_enum_name(value) {
+ const data = this.data();
+ if (data.enum === null) return null;
+ return data.enum.names.get(value) ?? null;
+ }
+ get_size_bits() {
+ return this.data().size_bits;
+ }
+ get_size_bytes() {
+ const size_bits = this.get_size_bits();
+ return size_bits === null ? null : floordiv(size_bits, 8);
+ }
+
+ /** Return the size & alignment of self when used as a function argument */
+ get_parameter_size_align_bytes() {
+ const data = this.data();
+ if (this.is_struct()) {
+ pyassert(data.struct !== null);
+ if (data.struct.size === null) throw new DecompFailure(`Cannot use incomplete type ${this} as parameter`);
+ return [data.struct.size, data.struct.align];
+ }
+ const size = floordiv(this.get_size_bits() || 32, 8);
+ return [size, size];
+ }
+
+ /** If self is a pointer-to-a-Type, return the Type */
+ get_pointer_target() {
+ const data = this.data();
+ if (this.is_pointer() && data.ptr_to !== null) return data.ptr_to;
+ return null;
+ }
+
+ /** Return a pointer to self. If self is an array, decay the type to a pointer */
+ reference() {
+ if (this.is_array()) {
+ const data = this.data();
+ pyassert(data.ptr_to !== null);
+ return Type.ptr(data.ptr_to, { array_dim: data.array_dim });
+ }
+ return Type.ptr(this);
+ }
+
+ /** If self is an array, return a pointer to the element type. Otherwise, return self. */
+ decay() {
+ if (this.is_array()) {
+ const data = this.data();
+ pyassert(data.ptr_to !== null);
+ return Type.ptr(data.ptr_to, { array_dim: data.array_dim });
+ }
+ return this;
+ }
+
+ /** If self is an explicit `void *`, return `Type.ptr()` without an target type. */
+ weaken_void_ptr() {
+ const target = this.get_pointer_target();
+ if (target !== null && target.is_void()) return Type.ptr();
+ return this;
+ }
+
+ /** If self is an array, return [inner Type, array dimension] */
+ get_array() {
+ if (!this.is_array()) return [null, null];
+ const data = this.data();
+ pyassert(data.ptr_to !== null);
+ return [data.ptr_to, data.array_dim];
+ }
+
+ /** If self is a function pointer, return the FunctionSignature */
+ get_function_pointer_signature() {
+ const data = this.data();
+ if (this.is_pointer() && data.ptr_to !== null) {
+ const ptr_to = data.ptr_to.data();
+ if (ptr_to.kind === TypeData.K_FN) return ptr_to.fn_sig;
+ }
+ return null;
+ }
+
+ /** If self is a struct, return the StructDeclaration */
+ get_struct_declaration() {
+ if (this.is_struct()) {
+ const data = this.data();
+ pyassert(data.struct !== null);
+ return data.struct;
+ }
+ return null;
+ }
+
+ clone_literal_type() {
+ const data = this.data();
+ const size_bits = data.size_bits === 64 ? 64 : null;
+ return new Type(new TypeData({ kind: TypeData.K_ANYREG, likely_kind: data.likely_kind, size_bits }));
+ }
+
+ static _no_matching_field() {
+ return [null, Type.any(), 0];
+ }
+
+ /**
+ * Locate the field in self at the appropriate offset, and optionally with an exact
+ * target size (both values in bytes). Returns [field_path, field_type, remaining_offset].
+ */
+ get_field(offset, { target_size, exact = true }) {
+ if (offset < 0) return Type._no_matching_field();
+
+ if (this.is_array()) {
+ const data = this.data();
+ pyassert(data.ptr_to !== null);
+ const size = data.ptr_to.get_size_bytes();
+ pyassert(size !== null);
+ const index = floordiv(offset, size);
+ const remaining_offset = pymod(offset, size);
+ if (data.array_dim !== null && index >= data.array_dim) return Type._no_matching_field();
+ pyassert(index >= 0 && remaining_offset >= 0);
+ const [subpath, subtype, sub_remaining_offset] = data.ptr_to.get_field(remaining_offset, { target_size, exact });
+ if (subpath !== null) {
+ subpath.unshift(index);
+ return [subpath, subtype, sub_remaining_offset];
+ }
+ return Type._no_matching_field();
+ }
+
+ if (this.is_struct()) {
+ const data = this.data();
+ pyassert(data.struct !== null);
+ if (data.struct.size !== null && offset >= data.struct.size) return Type._no_matching_field();
+
+ let possible_fields = data.struct.fields_containing_offset(offset);
+ if (!possible_fields.length && data.struct.has_bitfields) return Type._no_matching_field();
+
+ const possible_results = [];
+ if (!data.struct.is_stack && (target_size === null || target_size === this.get_size_bytes())) possible_results.push([[], this, offset]);
+
+ if (data.struct.is_union && data.struct.preferred_union_field) {
+ possible_fields = possible_fields.filter((field) => field.name === data.struct.preferred_union_field);
+ }
+
+ for (const field of possible_fields) {
+ const inner_offset_bits = offset - field.offset;
+ const [subpath, subtype, sub_remaining_offset] = field.type.get_field(inner_offset_bits, { target_size, exact });
+ if (subpath === null) continue;
+ subpath.unshift(field.name);
+ possible_results.push([subpath, subtype, sub_remaining_offset]);
+ if (target_size !== null && target_size === subtype.get_size_bytes() && sub_remaining_offset === 0) return possible_results[possible_results.length - 1];
+ }
+
+ const zero_offset_results = possible_results.filter((r) => r[2] === 0);
+ if (zero_offset_results.length) return zero_offset_results[0];
+ else if (exact) {
+ const field_type = Type.any_field({ new_within: data.struct });
+ const field_name = `${data.struct.new_field_prefix}${format(offset, "X")}`;
+ const new_field = data.struct.try_add_field(field_type, offset, field_name, target_size);
+ if (new_field !== null) return [[field_name], field_type, 0];
+ } else if (possible_results.length) return possible_results[0];
+ }
+
+ if ((target_size === null || target_size === this.get_size_bytes()) && offset === 0) return [[], this, offset];
+
+ return Type._no_matching_field();
+ }
+
+ /** Similar to `.get_field()`, but treat self as a pointer and find the field in the pointer's target. */
+ get_deref_field(offset, { target_size, exact = true }) {
+ const target = this.get_pointer_target();
+ if (target === null) return Type._no_matching_field();
+
+ const size = target.get_size_bytes();
+ let array_index;
+ if (size !== null && size !== 0) {
+ array_index = floordiv(offset, size);
+ offset = pymod(offset, size);
+ } else array_index = 0;
+
+ if (array_index !== 0) {
+ const known_array_size = this.data().array_dim;
+ if (known_array_size === null || array_index < 0 || array_index >= known_array_size) return Type._no_matching_field();
+ }
+
+ const [field_path, field_type, remaining_offset] = target.get_field(offset, { target_size, exact });
+ if (field_path !== null) field_path.unshift(array_index);
+ return [field_path, field_type, remaining_offset];
+ }
+
+ /**
+ * If self is a struct or array, return a list of fields suitable for creating an
+ * initializer; padding is represented by an int.
+ */
+ get_initializer_fields() {
+ const data = this.data();
+ if (this.is_array()) {
+ pyassert(data.ptr_to !== null);
+ if (data.array_dim === null) return null;
+ return new Array(Math.max(0, data.array_dim)).fill(data.ptr_to);
+ }
+ if (this.is_struct()) {
+ pyassert(data.struct !== null);
+ if (data.struct.has_bitfields) return null;
+ const output = [];
+ let position = 0;
+ const add_padding = (upto) => {
+ pyassert(upto >= position);
+ if (upto > position) output.push(upto - position);
+ };
+ for (const field of data.struct.fields) {
+ if (field.offset < position) return null;
+ add_padding(field.offset);
+ const field_size = field.type.get_size_bytes();
+ if (field_size === null) return null;
+ output.push(field.type);
+ position = field.offset + field_size;
+ if (data.struct.is_union) break;
+ }
+ if (data.struct.size !== null && position > data.struct.size) return null;
+ add_padding(data.struct.min_size());
+ return output;
+ }
+ return null;
+ }
+
+ to_decl(name, fmt) {
+ const decl = new ca.Decl(name, [], [], [], [], [], this._to_ctype(new Set(), fmt), null, null, null);
+ set_decl_name(decl);
+ let ret = to_c(decl);
+ if (fmt.coding_style.pointer_style_left) {
+ for (;;) {
+ const replaced = ret.replaceAll(" *", "* ").replaceAll("* )", "*)").replaceAll("* ,", "*,");
+ if (replaced === ret) break;
+ ret = replaced;
+ }
+ }
+ return ret;
+ }
+
+ _to_ctype(seen, fmt) {
+ const simple_ctype = (typename) => new ca.TypeDecl(null, [], [], new ca.IdentifierType([typename]));
+ const unk_symbol = fmt.valid_syntax ? "M2C_UNK" : "?";
+
+ const data = this.data();
+ if (seen.has(data)) return simple_ctype(unk_symbol);
+ seen.add(data);
+ const size_bits = data.size_bits || 32;
+ const sign = data.sign & TypeData.SIGNED ? "s" : "u";
+
+ if (data.enum !== null && data.enum.tag !== null && data.enum.tag !== undefined) {
+ pyassert(data.kind === TypeData.K_INT);
+ return new ca.TypeDecl(null, [], [], new ca.Enum(data.enum.tag, [], null));
+ }
+
+ const lk = data.likely_kind & (TypeData.K_INT | TypeData.K_FLOAT);
+ if ((data.kind & TypeData.K_ANYREG) === TypeData.K_ANYREG && lk !== TypeData.K_INT && lk !== TypeData.K_FLOAT) {
+ if (data.size_bits !== null) return simple_ctype(`${unk_symbol}${size_bits}`);
+ return simple_ctype(unk_symbol);
+ }
+
+ if (data.kind === TypeData.K_FLOAT || (data.likely_kind & (TypeData.K_FLOAT | TypeData.K_INT)) === TypeData.K_FLOAT) return simple_ctype(`f${size_bits}`);
+
+ if (data.kind === TypeData.K_PTR) {
+ let target_ctype;
+ if (data.ptr_to === null) target_ctype = simple_ctype("void");
+ else target_ctype = data.ptr_to._to_ctype(new Set(seen), fmt);
+ if (target_ctype instanceof ca.FuncDecl && target_ctype.args) {
+ for (const arg of target_ctype.args.params) {
+ if (arg instanceof ca.Decl) {
+ arg.name = null;
+ set_decl_name(arg);
+ }
+ }
+ }
+ return new ca.PtrDecl([], target_ctype);
+ }
+
+ if (data.kind === TypeData.K_FN) {
+ pyassert(data.fn_sig !== null);
+ const return_ctype = data.fn_sig.return_type._to_ctype(new Set(seen), fmt);
+ const params = [];
+ for (const param of data.fn_sig.params) {
+ const decl = new ca.Decl(param.name, [], [], [], [], [], param.type._to_ctype(new Set(seen), fmt), null, null, null);
+ set_decl_name(decl);
+ params.push(decl);
+ }
+ if (data.fn_sig.is_variadic) params.push(new ca.EllipsisParam());
+ return new ca.FuncDecl(new ca.ParamList(params), return_ctype);
+ }
+
+ if (data.kind === TypeData.K_VOID) return simple_ctype("void");
+
+ if (data.kind === TypeData.K_ARRAY) {
+ pyassert(data.ptr_to !== null);
+ let dim = null;
+ if (data.array_dim !== null) dim = new ca.Constant("", fmt.format_int(data.array_dim));
+ return new ca.ArrayDecl(data.ptr_to._to_ctype(new Set(seen), fmt), dim, []);
+ }
+
+ if (data.kind === TypeData.K_STRUCT) {
+ pyassert(data.struct !== null);
+ if (data.struct.typedef_name) return simple_ctype(data.struct.typedef_name);
+ const name = data.struct.tag_name || "_anonymous";
+ const type = data.struct.is_union ? new ca.Union(name, [], null) : new ca.Struct(name, [], null);
+ return new ca.TypeDecl(name, [], [], type);
+ }
+
+ return simple_ctype(`${sign}${size_bits}`);
+ }
+
+ format(fmt) {
+ return this.to_decl("", fmt);
+ }
+ toString() {
+ return this.format(new Formatter({ debug: true }));
+ }
+ __repr__() {
+ const data = this.data();
+ const signstr = (data.sign & TypeData.SIGNED ? "+" : "") + (data.sign & TypeData.UNSIGNED ? "-" : "");
+ const kindstr =
+ (data.kind & TypeData.K_INT ? "I" : "") +
+ (data.kind & TypeData.K_PTR ? "P" : "") +
+ (data.kind & TypeData.K_FLOAT ? "F" : "") +
+ (data.kind & TypeData.K_FN ? "N" : "") +
+ (data.kind & TypeData.K_VOID ? "V" : "") +
+ (data.kind & TypeData.K_ARRAY ? "A" : "") +
+ (data.kind & TypeData.K_STRUCT ? "S" : "");
+ const sizestr = data.size_bits !== null ? String(data.size_bits) : "?";
+ if (!DEBUG_REPR_IDS.has(data)) DEBUG_REPR_IDS.set(data, DEBUG_REPR_IDS.size);
+ return `Type(${signstr + kindstr + sizestr})@${DEBUG_REPR_IDS.get(data)}`;
+ }
+
+ static any() {
+ return new Type(new TypeData());
+ }
+ static any_reg() {
+ return new Type(new TypeData({ kind: TypeData.K_ANYREG }));
+ }
+ static any_field({ new_within = null } = {}) {
+ return new Type(new TypeData({ kind: TypeData.K_ANY & ~TypeData.K_VOID, new_field_within: new_within ? new Set([new_within]) : new Set() }));
+ }
+ static intish() {
+ return new Type(new TypeData({ kind: TypeData.K_INT }));
+ }
+ static uintish() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.UNSIGNED }));
+ }
+ static sintish() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.SIGNED }));
+ }
+ static intptr() {
+ return new Type(new TypeData({ kind: TypeData.K_INTPTR }));
+ }
+ static uintptr() {
+ return new Type(new TypeData({ kind: TypeData.K_INTPTR, sign: TypeData.UNSIGNED }));
+ }
+ static sintptr() {
+ return new Type(new TypeData({ kind: TypeData.K_INTPTR, sign: TypeData.SIGNED }));
+ }
+ static ptr(type = null, { array_dim = null } = {}) {
+ return new Type(new TypeData({ kind: TypeData.K_PTR, size_bits: 32, array_dim, ptr_to: type }));
+ }
+ static function(fn_sig = null) {
+ if (fn_sig === null) fn_sig = new FunctionSignature();
+ return new Type(new TypeData({ kind: TypeData.K_FN, fn_sig }));
+ }
+ static f32() {
+ return new Type(new TypeData({ kind: TypeData.K_FLOAT, size_bits: 32 }));
+ }
+ static floatish() {
+ return new Type(new TypeData({ kind: TypeData.K_FLOAT }));
+ }
+ static f64() {
+ return new Type(new TypeData({ kind: TypeData.K_FLOAT, size_bits: 64 }));
+ }
+ static f128() {
+ return new Type(new TypeData({ kind: TypeData.K_FLOAT, size_bits: 128 }));
+ }
+ static s8() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 8, sign: TypeData.SIGNED }));
+ }
+ static u8() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 8, sign: TypeData.UNSIGNED }));
+ }
+ static s16() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 16, sign: TypeData.SIGNED }));
+ }
+ static u16() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 16, sign: TypeData.UNSIGNED }));
+ }
+ static s32() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 32, sign: TypeData.SIGNED }));
+ }
+ static u32() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 32, sign: TypeData.UNSIGNED }));
+ }
+ static s64() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 64, sign: TypeData.SIGNED }));
+ }
+ static u64() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 64, sign: TypeData.UNSIGNED }));
+ }
+ static int64() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 64 }));
+ }
+ static int_of_size(size_bits) {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits }));
+ }
+ static reg32({ likely_float }) {
+ const likely = likely_float ? TypeData.K_FLOAT : TypeData.K_INTPTR;
+ return new Type(new TypeData({ kind: TypeData.K_ANYREG, likely_kind: likely, size_bits: 32 }));
+ }
+ static reg64({ likely_float }) {
+ const kind = TypeData.K_FLOAT | TypeData.K_INT;
+ const likely = likely_float ? TypeData.K_FLOAT : TypeData.K_INT;
+ return new Type(new TypeData({ kind, likely_kind: likely, size_bits: 64 }));
+ }
+ static reg128() {
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 128 }));
+ }
+ static boolean() {
+ return Type.intish();
+ }
+ static void() {
+ return new Type(new TypeData({ kind: TypeData.K_VOID, size_bits: 0 }));
+ }
+ static array(type, dim) {
+ const el_size = type.get_size_bits();
+ pyassert(el_size !== null);
+ const size_bits = dim === null ? null : el_size * dim;
+ return new Type(new TypeData({ kind: TypeData.K_ARRAY, size_bits, ptr_to: type, array_dim: dim }));
+ }
+ static struct(st) {
+ const size_bits = st.size !== null ? st.size * 8 : null;
+ return new Type(new TypeData({ kind: TypeData.K_STRUCT, size_bits, struct: st }));
+ }
+
+ static gsym_unk_ctype(ctype, typemap, typepool) {
+ const [real_ctype] = resolve_typedefs(ctype, typemap);
+ let type = Type.any();
+ if (real_ctype instanceof ca.TypeDecl && real_ctype.type instanceof ca.IdentifierType) {
+ const size_bits = primitive_size(real_ctype.type) * 8;
+ if (size_bits < 32) type = Type.int_of_size(size_bits);
+ }
+ if (ctype instanceof ca.TypeDecl && ctype.declname) {
+ if (typepool.unknown_decls.has(ctype.declname)) return typepool.unknown_decls.get(ctype.declname);
+ typepool.unknown_decls.set(ctype.declname, type);
+ }
+ return type;
+ }
+
+ static ctype(ctype, typemap, typepool, { in_struct = false } = {}) {
+ const [real_ctype] = resolve_typedefs(ctype, typemap);
+
+ if (real_ctype instanceof ca.ArrayDecl) {
+ let dim = null;
+ try {
+ if (real_ctype.dim !== null && real_ctype.dim !== undefined) dim = parse_constant_int(real_ctype.dim, typemap);
+ else if (in_struct) dim = 1;
+ } catch (e) {
+ if (!(e instanceof DecompFailure)) throw e;
+ }
+ const elem_type = Type.ctype(real_ctype.type, typemap, typepool);
+ return Type.array(elem_type, dim);
+ }
+ if (real_ctype instanceof ca.PtrDecl) return Type.ptr(Type.ctype(real_ctype.type, typemap, typepool));
+ if (real_ctype instanceof ca.FuncDecl) {
+ const fn = parse_function(real_ctype);
+ pyassert(fn !== null);
+ const fn_sig = new FunctionSignature({ return_type: Type.void(), is_variadic: fn.is_variadic });
+ if (fn.ret_type !== null) fn_sig.return_type = Type.ctype(fn.ret_type, typemap, typepool);
+ if (fn.params !== null) {
+ fn_sig.params = fn.params.map((param) => new FunctionParam({ name: param.name || "", type: Type.ctype(param.type, typemap, typepool) }));
+ fn_sig.params_known = true;
+ }
+ return Type.function(fn_sig);
+ }
+ if (real_ctype instanceof ca.TypeDecl) {
+ const inner_type = real_ctype.type;
+ if (inner_type instanceof ca.Struct || inner_type instanceof ca.Union) return Type.struct(StructDeclaration.from_ctype(inner_type, typemap, typepool));
+ if (inner_type instanceof ca.Enum) {
+ let enum_ = null;
+ if (inner_type.name !== null && inner_type.name !== undefined) enum_ = typemap.enums.get(inner_type.name) ?? null;
+ if (enum_ === null) enum_ = typemap.enums.get(inner_type) ?? null;
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits: 32, sign: TypeData.SIGNED, enum: enum_ }));
+ }
+ pyassert(!(inner_type instanceof ca.Typeof), "handled by resolve_typedefs");
+ const names = inner_type.names;
+ if (names.includes("double")) return Type.f64();
+ if (names.includes("float")) return Type.f32();
+ if (names.includes("void")) return Type.void();
+ const size_bits = 8 * primitive_size(inner_type);
+ pyassert(size_bits > 0);
+ const sign = names.includes("unsigned") ? TypeData.UNSIGNED : TypeData.SIGNED;
+ return new Type(new TypeData({ kind: TypeData.K_INT, size_bits, sign }));
+ }
+ assert_never(real_ctype);
+ }
+
+ static demangled_symbol(typemap, typepool, sym) {
+ return Type.demangled_type(typemap, typepool, sym.type, sym.name);
+ }
+
+ static demangled_type(typemap, typepool, sym_type, sym_name = null) {
+ const type_for_class = (qualified_name) => {
+ const class_name = qualified_name.map((n) => String(n)).join("::");
+ const class_struct = typepool.get_or_create_struct_by_tag_name(class_name, typemap, { size: null, with_typedef: true });
+ return Type.struct(class_struct);
+ };
+
+ let final_name = null;
+ if (sym_name !== null && sym_name !== undefined) {
+ pyassert(sym_name.kind === CxxTerm.Kind.QUALIFIED);
+ pyassert(sym_name.qualified_name !== null && sym_name.qualified_name !== undefined);
+ pyassert(sym_name.qualified_name.length >= 1);
+ const parts = String(sym_name.qualified_name[sym_name.qualified_name.length - 1]).split("@");
+ final_name = parts[parts.length - 1];
+ }
+
+ if (final_name === "__vt") return Type.any();
+ if (final_name === "__RTTI") return Type.struct(typepool.get_or_create_struct_by_tag_name("RTTI", typemap, { size: 8 }));
+
+ let type = Type.any();
+ const K = CxxTerm.Kind;
+ for (const term of [...sym_type.terms].reverse()) {
+ if (term.kind === K.CONST) {
+ // pass
+ } else if (term.kind === K.POINTER || term.kind === K.REFERENCE) type = Type.ptr(type);
+ else if (term.kind === K.BOOL) type = Type.boolean();
+ else if (term.kind === K.CHAR) type = Type.int_of_size(8);
+ else if (term.kind === K.SHORT || term.kind === K.WIDE_CHAR) type = Type.int_of_size(16);
+ else if (term.kind === K.INT || term.kind === K.LONG) type = Type.int_of_size(32);
+ else if (term.kind === K.LONG_LONG) type = Type.int_of_size(64);
+ else if (term.kind === K.FLOAT) type = Type.f32();
+ else if (term.kind === K.DOUBLE) type = Type.f64();
+ else if (term.kind === K.LONG_DOUBLE) type = Type.f128();
+ else if (term.kind === K.SIGNED) type.unify(new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.SIGNED })));
+ else if (term.kind === K.UNSIGNED) type.unify(new Type(new TypeData({ kind: TypeData.K_INT, sign: TypeData.UNSIGNED })));
+ else if (term.kind === K.ARRAY) {
+ pyassert(term.array_dim !== null && term.array_dim !== undefined, "array CxxTerms must have array_dim");
+ type = Type.array(type, term.array_dim);
+ } else if (term.kind === K.FUNCTION) {
+ pyassert(term.function_params !== null && term.function_params !== undefined);
+ const params = [];
+ if (sym_name !== null && sym_name !== undefined && sym_name.qualified_name !== null && sym_name.qualified_name !== undefined && sym_name.qualified_name.length > 1 && !CxxSymbol.STATIC_FUNCTIONS.has(final_name)) {
+ const class_type = type_for_class(sym_name.qualified_name.slice(0, -1));
+ params.push(new FunctionParam({ type: Type.ptr(class_type), name: "this" }));
+ }
+ if (final_name === "__dt") params.push(new FunctionParam({ type: Type.s16(), name: "destroyFlag" }));
+ let is_variadic = false;
+ term.function_params.forEach((param_type, i) => {
+ const name = `arg${i}`;
+ if (param_type.terms[0].kind === K.VOID) pyassert(term.function_params.length === 1);
+ else if (param_type.terms[0].kind === K.ELLIPSIS) {
+ pyassert(i === term.function_params.length - 1);
+ is_variadic = true;
+ } else params.push(new FunctionParam({ type: Type.demangled_type(typemap, typepool, param_type), name }));
+ });
+ let return_type = Type.any();
+ if (term.function_return !== null && term.function_return !== undefined) return_type = Type.demangled_type(typemap, typepool, term.function_return);
+ else if (final_name === "__ct" || final_name === "__dt") return_type = Type.ptr();
+ type = Type.function(new FunctionSignature({ params, params_known: true, is_variadic, return_type }));
+ } else if (term.kind === K.QUALIFIED) {
+ pyassert(term.qualified_name !== null && term.qualified_name !== undefined);
+ type = type_for_class(term.qualified_name);
+ } else if (term.kind === K.VOID) type = Type.void();
+ else if (term.kind === K.ELLIPSIS) pyassert(false, String(term.kind));
+ else pyassert(false, String(term.kind));
+ }
+ return type;
+ }
+}
+
+export class FunctionParam {
+ constructor({ type = Type.any(), name = "" } = {}) {
+ this.type = type;
+ this.name = name;
+ }
+}
+
+export class FunctionSignature {
+ constructor({ return_type = Type.any(), params = [], params_known = false, is_variadic = false } = {}) {
+ this.return_type = return_type;
+ this.params = params;
+ this.params_known = params_known;
+ this.is_variadic = is_variadic;
+ }
+
+ unify(other, { seen }) {
+ if (this.params_known && other.params_known) {
+ if (this.is_variadic !== other.is_variadic) return false;
+ if (this.params.length !== other.params.length) return false;
+ }
+ let can_unify = this.return_type.unify(other.return_type, { seen });
+ const n = Math.min(this.params.length, other.params.length);
+ for (let i = 0; i < n; i++) can_unify = this.params[i].type.unify(other.params[i].type, { seen }) && can_unify;
+ if (!can_unify) return false;
+
+ if (!this.params_known) {
+ this.is_variadic = this.is_variadic || other.is_variadic;
+ this.params_known = this.params_known || other.params_known;
+ while (other.params.length > this.params.length) this.params.push(other.params[this.params.length]);
+ }
+ if (!other.params_known) {
+ other.is_variadic = other.is_variadic || this.is_variadic;
+ other.params_known = other.params_known || this.params_known;
+ while (this.params.length > other.params.length) other.params.push(this.params[other.params.length]);
+ }
+
+ const m = Math.min(this.params.length, other.params.length);
+ for (let i = 0; i < m; i++) {
+ const x = this.params[i];
+ const y = other.params[i];
+ if (!x.name && y.name) x.name = y.name;
+ else if (!y.name && x.name) y.name = x.name;
+ }
+ return true;
+ }
+
+ /** Unify a function's signature with a list of argument types (at a callsite). */
+ unify_with_args(concrete) {
+ if (this.params.length > concrete.params.length) return false;
+ if (!this.is_variadic && this.params.length !== concrete.params.length) return false;
+ let can_unify = true;
+ const n = Math.min(this.params.length, concrete.params.length);
+ for (let i = 0; i < n; i++) can_unify = this.params[i].type.unify(concrete.params[i].type) && can_unify;
+ return can_unify;
+ }
+}
+
+class StructField {
+ constructor({ type, offset, name, known }) {
+ this.type = type;
+ this.offset = offset;
+ this.name = name;
+ this.known = known;
+ }
+}
+
+class BitField {
+ constructor({ bit_offset, bit_width, name }) {
+ this.bit_offset = bit_offset;
+ this.bit_width = bit_width;
+ this.name = name;
+ }
+}
+
+/** Representation of a C struct or union */
+export class StructDeclaration {
+ static StructField = StructField;
+ static BitField = BitField;
+
+ constructor({
+ size,
+ align,
+ new_field_prefix,
+ tag_name = null,
+ typedef_name = null,
+ fields = [],
+ bitfields = [],
+ has_bitfields = false,
+ is_union = false,
+ is_stack = false,
+ preferred_union_field = null,
+ }) {
+ this.size = size;
+ this.align = align;
+ this.new_field_prefix = new_field_prefix;
+ this.tag_name = tag_name;
+ this.typedef_name = typedef_name;
+ this.fields = fields; // sorted by `.offset`
+ this.bitfields = bitfields; // sorted by `.bit_offset`
+ this.has_bitfields = has_bitfields;
+ this.is_union = is_union;
+ this.is_stack = is_stack;
+ this.preferred_union_field = preferred_union_field;
+ }
+
+ StructField(f) {
+ return new StructField(f);
+ }
+
+ min_size() {
+ if (this.size !== null) return this.size;
+ let m = 0;
+ for (const field of this.fields) m = Math.max(m, field.offset + (field.type.get_size_bytes() || 1));
+ return m;
+ }
+
+ unify(other, { seen = null } = {}) {
+ void seen;
+ return this === other;
+ }
+
+ /** Return the list of StructFields which contain the given offset (in bytes) */
+ fields_containing_offset(offset) {
+ const fields = [];
+ for (const field of this.fields) {
+ if (field.offset > offset) break;
+ const field_size = field.type.get_size_bytes() || 1;
+ if (field.offset + field_size <= offset) continue;
+ fields.push(field);
+ }
+ return fields;
+ }
+
+ /** Try to add a field into the struct, and return it if successful. */
+ try_add_field(type, offset, name, size) {
+ if (this.is_union) return null;
+ if (this.size !== null && !(0 <= offset && offset < this.size)) return null;
+ size = size || 1;
+ for (const field of this.fields) {
+ const field_size = field.type.get_size_bytes() || 1;
+ if (offset <= field.offset && field.offset < offset + size) return null;
+ if (field.offset <= offset && offset < field.offset + field_size) return null;
+ }
+ const field = new StructField({ type, offset, name, known: false });
+ this.fields.push(field);
+ this.fields = sorted(this.fields, (f) => f.offset);
+ return field;
+ }
+
+ /** Remove overlapping fields with `known=False` from the struct */
+ prune_overlapping_fields() {
+ if (this.is_union) return null;
+ this.fields = sorted(this.fields, (f) => [f.offset, -(f.type.get_size_bytes() || 0)]);
+
+ let end_pseudofield;
+ if (this.size !== null) end_pseudofield = [new StructField({ offset: this.size, type: Type.void(), known: true, name: "" })];
+ else end_pseudofield = [];
+
+ const fields_to_remove = new Set();
+ this.fields.forEach((field, i) => {
+ if (field.known || fields_to_remove.has(field)) return;
+ const field_size = field.type.get_size_bytes() || 1;
+ let conflicting_fields = [];
+ for (const f2 of [...this.fields.slice(i + 1), ...end_pseudofield]) {
+ pyassert(f2.offset >= field.offset);
+ if (f2.offset >= field.offset + field_size) break;
+ if (fields_to_remove.has(f2)) continue;
+ let offset = f2.offset - field.offset;
+ const [sub_path, sub_type] = field.type.get_field(offset, { target_size: f2.type.get_size_bytes() });
+ if (sub_path !== null && sub_type.unify(f2.type)) {
+ conflicting_fields.push(f2);
+ } else if (!f2.known && f2.type.is_int() && field.type.is_int()) {
+ // pass
+ } else {
+ if (conflicting_fields.length) {
+ offset = conflicting_fields[0].offset - field.offset;
+ conflicting_fields = [];
+ }
+ if (offset === 0) conflicting_fields = [field];
+ if (offset >= 4) field.type = Type.any_reg();
+ else field.type = Type.int_of_size(offset * 8);
+ break;
+ }
+ }
+ for (const f of conflicting_fields) fields_to_remove.add(f);
+ });
+ this.fields = this.fields.filter((f) => !fields_to_remove.has(f));
+ }
+
+ /** Rename inferred fields that are pointers to vtables */
+ rename_inferred_vtables() {
+ const sep = this.new_field_prefix.endsWith("_") ? "_" : "";
+ for (const field of this.fields) {
+ if (field.known || !field.name.startsWith(this.new_field_prefix)) continue;
+ const type_ptr = field.type.get_pointer_target();
+ if (type_ptr === null) continue;
+ const struct = type_ptr.get_struct_declaration();
+ if (struct === null || struct.tag_name === null) continue;
+ if (struct.tag_name.startsWith("__vt__")) {
+ const name = field.name.replace(this.new_field_prefix, `vtable${sep}`);
+ if (!this.fields.some((f) => f.name === name)) field.name = name;
+ }
+ }
+ }
+
+ /** Return the C representation of the struct/union. */
+ format(fmt) {
+ const keyword = this.is_union ? "union" : "struct";
+ const decl = this.tag_name ? `${keyword} ${this.tag_name}` : `${keyword}`;
+ const head = this.typedef_name ? `typedef ${decl} {` : `${decl} {`;
+ const tail = this.typedef_name ? `} ${this.typedef_name};` : "};";
+
+ if (this.size === 0 && !this.fields.length) return fmt.with_comments(head + tail, ["size 0x0"]);
+
+ const lines = [];
+ lines.push(fmt.indent(head));
+ let position = 0;
+ fmt.indented(() => {
+ const offset_str_digits = fmt.format_hex(this.min_size()).length;
+ const offset_comment = (offset) => `/* 0x${fmt.format_hex(offset).padStart(offset_str_digits, "0")} */`;
+ let prev_field = null;
+
+ const pad_to = (offset, is_final) => {
+ if (position < offset) {
+ const underscore = fmt.coding_style.unknown_underscore ? "_" : "";
+ const name = `pad${underscore}${fmt.format_hex(position)}`;
+ const padding_size = offset - position;
+ const comments = [];
+ if (prev_field !== null && !(is_final && this.is_stack)) {
+ const last_size = prev_field.type.get_size_bytes();
+ if (last_size && padding_size > last_size) {
+ const array_dim_str = fmt.format_int(floordiv(padding_size, last_size) + 1);
+ comments.push(`maybe part of ${prev_field.name}[${array_dim_str}]?`);
+ }
+ }
+ lines.push(fmt.with_comments(`${offset_comment(position)} char ${name}[${fmt.format_int(padding_size)}];`, comments));
+ position = offset;
+ }
+ };
+
+ for (const field of this.fields) {
+ pad_to(field.offset, false);
+ const field_decl = `${offset_comment(field.offset)} ${field.type.to_decl(field.name, fmt)};`;
+ const comments = [];
+ if (!this.is_union && position > field.offset) comments.push("overlap");
+ if (this.is_union && field.offset !== 0) comments.push("offset");
+ if (!field.known) comments.push("inferred");
+ lines.push(fmt.with_comments(field_decl, comments));
+ const s = field.type.get_struct_declaration();
+ if (s !== null) field.type.unify(Type.struct(s));
+ position = Math.max(position, field.offset + (field.type.get_size_bytes() || 0));
+ prev_field = field;
+ }
+ pad_to(this.min_size(), true);
+ });
+ const cmp = this.size === null ? ">=" : "=";
+ lines.push(fmt.with_comments(tail, [`size ${cmp} 0x${fmt.format_hex(position)}`]));
+ return lines.join("\n");
+ }
+
+ /** Return an StructDeclaration without any known fields */
+ static unknown(typepool, size, tag_name, align = 1) {
+ const preferred_field = typepool.union_field_overrides.get(tag_name) ?? null;
+ const decl = new StructDeclaration({ size, align, tag_name, new_field_prefix: typepool.unknown_field_prefix, preferred_union_field: preferred_field });
+ typepool.add_struct(decl, tag_name);
+ return decl;
+ }
+
+ /** Return StructDeclaration for a given ctype struct or union, registering it if needed. */
+ static from_ctype(ctype, typemap, typepool) {
+ const existing_struct = typepool.get_struct_for_ctype(ctype);
+ if (existing_struct) return existing_struct;
+
+ let typedef_name = null;
+ if (typemap.struct_typedefs.has(ctype)) {
+ const typedef = typemap.struct_typedefs.get(ctype);
+ pyassert(typedef.type instanceof ca.IdentifierType);
+ typedef_name = typedef.type.names[0];
+ } else if (ctype.name && typemap.struct_typedefs.has(ctype.name)) {
+ const typedef = typemap.struct_typedefs.get(ctype.name);
+ pyassert(typedef.type instanceof ca.IdentifierType);
+ typedef_name = typedef.type.names[0];
+ }
+
+ let struct_fields, struct_bitfields, struct_has_bitfields, struct_size, struct_align;
+ try {
+ const struct = parse_struct(ctype, typemap);
+ struct_fields = struct.fields;
+ struct_bitfields = struct.bitfields;
+ struct_has_bitfields = struct.has_bitfields;
+ struct_size = struct.size;
+ struct_align = struct.align;
+ } catch (e) {
+ if (!(e instanceof UndefinedStructError)) throw e;
+ struct_fields = new Map();
+ struct_bitfields = new Map();
+ struct_has_bitfields = false;
+ struct_size = 0;
+ struct_align = 1;
+ typepool.warnings.push(`Warning: struct ${typedef_name || ctype.name || "None"} is not defined (only forward-declared)`);
+ }
+
+ pyassert(pymod(struct_size, struct_align) === 0, "struct size must be a multiple of its alignment");
+
+ const struct_name = typedef_name || ctype.name;
+ const preferred_field = struct_name ? (typepool.union_field_overrides.get(struct_name) ?? null) : null;
+
+ const decl = new StructDeclaration({
+ size: struct_size,
+ align: struct_align,
+ tag_name: ctype.name ?? null,
+ typedef_name,
+ fields: [],
+ bitfields: [],
+ has_bitfields: struct_has_bitfields,
+ is_union: ctype instanceof ca.Union,
+ new_field_prefix: typepool.unknown_field_prefix,
+ preferred_union_field: preferred_field,
+ });
+ typepool.add_struct(decl, ctype);
+
+ for (const [bit_offset, bit_fields] of sorted(struct_bitfields.entries(), (e) => e[0])) {
+ for (const bit_field of bit_fields) decl.bitfields.push(new BitField({ bit_offset, bit_width: bit_field.width, name: bit_field.name }));
+ }
+
+ for (const [offset, fields] of sorted(struct_fields.entries(), (e) => e[0])) {
+ for (const field of fields) {
+ if (typepool.unk_inference && is_unk_type(field.type, typemap)) continue;
+ const field_type = Type.ctype(field.type, typemap, typepool, { in_struct: true });
+ pyassert(field.size === field_type.get_size_bytes(), `(${field.size}, ${field_type.get_size_bytes()}, '${field.name}', ${field_type})`);
+ decl.fields.push(new StructField({ type: field_type, offset, name: field.name, known: true }));
+ }
+ }
+ for (let i = 1; i < decl.fields.length; i++) pyassert(decl.fields[i - 1].offset <= decl.fields[i].offset);
+ return decl;
+ }
+}
+
+export { compare, bnot, to_c };
diff --git a/packages/romdev-m2c/src/worker.js b/packages/romdev-m2c/src/worker.js
new file mode 100644
index 00000000..5b8c93a4
--- /dev/null
+++ b/packages/romdev-m2c/src/worker.js
@@ -0,0 +1,11 @@
+// Worker-thread entry: runs one decompile() so a slow function cannot block the
+// caller's event loop, and so callers can enforce a timeout.
+import { parentPort, workerData } from "node:worker_threads";
+import { decompile } from "./main.js";
+
+try {
+ const r = await decompile(workerData.flags);
+ parentPort.postMessage({ ok: true, ...r });
+} catch (e) {
+ parentPort.postMessage({ ok: false, error: String(e && e.stack ? e.stack : e) });
+}
diff --git a/packages/romdev-m2c/test/demangle_codewarrior.test.mjs b/packages/romdev-m2c/test/demangle_codewarrior.test.mjs
new file mode 100644
index 00000000..15e65f4a
--- /dev/null
+++ b/packages/romdev-m2c/test/demangle_codewarrior.test.mjs
@@ -0,0 +1,15 @@
+// The self-test table from m2c/demangle_codewarrior.py (its `--test` mode),
+// run against the JS port.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { demangle, TEST_CASES, test as selfTest } from "../src/demangle_codewarrior.js";
+
+for (const [mangled, demangled] of TEST_CASES) {
+ test(`demangle ${mangled}`, () => {
+ assert.equal(demangle(mangled), demangled);
+ });
+}
+
+test("self-test reports all cases passing", () => {
+ assert.equal(selfTest(), true);
+});
diff --git a/packages/romdev-m2c/test/e2e.test.mjs b/packages/romdev-m2c/test/e2e.test.mjs
new file mode 100644
index 00000000..54dd4bba
--- /dev/null
+++ b/packages/romdev-m2c/test/e2e.test.mjs
@@ -0,0 +1,132 @@
+// Port of m2c's run_tests.py end-to-end runner (tests/end_to_end/**).
+// Each case's asm input is decompiled in-process with the JS port and compared
+// byte-for-byte against upstream's committed expected output.
+//
+// The corpus is read from the pinned upstream checkout: $M2C_SRC, else
+// ~/.romdev/tools/m2c. Filter cases with M2C_FILTER= over names like
+// "e2e:loop/irix-o2.s". Set M2C_E2E_SUMMARY=1 to print a pass/fail summary.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { decompile } from "../src/main.js";
+
+const SRC = process.env.M2C_SRC || path.join(os.homedir(), ".romdev", "tools", "m2c");
+const E2E = path.join(SRC, "tests", "end_to_end");
+const PATH_FLAGS = new Set(["--context", "--incbin-dir"]);
+const CRASH_STRING = "CRASHED\n";
+
+/** Python shlex.split (POSIX mode) for the simple flag files used by the corpus. */
+export function shlex_split(s) {
+ const out = [];
+ let cur = null;
+ let i = 0;
+ while (i < s.length) {
+ const c = s[i];
+ if (/\s/.test(c)) {
+ if (cur !== null) out.push(cur);
+ cur = null;
+ i++;
+ } else if (c === "'") {
+ const j = s.indexOf("'", i + 1);
+ if (j < 0) throw new Error("No closing quotation");
+ cur = (cur ?? "") + s.slice(i + 1, j);
+ i = j + 1;
+ } else if (c === '"') {
+ let j = i + 1;
+ let buf = "";
+ while (j < s.length && s[j] !== '"') {
+ if (s[j] === "\\" && j + 1 < s.length && '\\"$`\n'.includes(s[j + 1])) {
+ buf += s[j + 1];
+ j += 2;
+ } else buf += s[j++];
+ }
+ if (j >= s.length) throw new Error("No closing quotation");
+ cur = (cur ?? "") + buf;
+ i = j + 1;
+ } else if (c === "\\" && i + 1 < s.length) {
+ cur = (cur ?? "") + s[i + 1];
+ i += 2;
+ } else if (c === "#" && cur === null) {
+ while (i < s.length && s[i] !== "\n") i++;
+ } else {
+ cur = (cur ?? "") + c;
+ i++;
+ }
+ }
+ if (cur !== null) out.push(cur);
+ return out;
+}
+
+function get_test_flags(flags_path) {
+ if (!fs.existsSync(flags_path)) return [];
+ const flags_list = shlex_split(fs.readFileSync(flags_path, "utf8"));
+ for (let i = 0; i < flags_list.length; i++) {
+ if (!PATH_FLAGS.has(flags_list[i])) continue;
+ if (i + 1 >= flags_list.length) throw new Error(`${flags_path} contains ${flags_list[i]} without argument`);
+ flags_list[i + 1] = path.join(path.dirname(flags_path), flags_list[i + 1]);
+ }
+ return flags_list;
+}
+
+export function collect_cases() {
+ const cases = [];
+ if (!fs.existsSync(E2E)) return cases;
+ for (const dir of fs.readdirSync(E2E).sort()) {
+ const d = path.join(E2E, dir);
+ if (!fs.statSync(d).isDirectory()) continue;
+ for (const f of fs.readdirSync(d)) {
+ if (!f.endsWith(".s")) continue;
+ const stem = f.slice(0, -2);
+ cases.push({
+ name: `e2e:${dir}/${f}`,
+ asm_file: path.join(d, f),
+ output_file: path.join(d, `${stem}-out.c`),
+ flags_path: path.join(d, `${stem}-flags.txt`),
+ });
+ }
+ }
+ cases.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
+ return cases;
+}
+
+export async function run_case(c) {
+ const flags = ["--sanitize-tracebacks", "--stop-on-error", "--function", "test", ...get_test_flags(c.flags_path), c.asm_file];
+ const r = await decompile(flags);
+ const out = r.stdout.replaceAll(SRC, ".");
+ return r.code === 0 ? out : `${CRASH_STRING}\n${out}`;
+}
+
+const filter = process.env.M2C_FILTER ? new RegExp(process.env.M2C_FILTER) : null;
+const cases = collect_cases().filter((c) => !filter || filter.test(c.name));
+const results = { pass: 0, fail: 0, failed: [] };
+
+if (!cases.length) {
+ test("m2c e2e corpus", { skip: `no upstream checkout at ${SRC}` }, () => {});
+}
+for (const c of cases) {
+ test(c.name, async () => {
+ const expected = fs.readFileSync(c.output_file, "utf8");
+ let actual;
+ try {
+ actual = await run_case(c);
+ } catch (e) {
+ results.fail++;
+ results.failed.push(c.name);
+ throw e;
+ }
+ if (actual === expected) results.pass++;
+ else {
+ results.fail++;
+ results.failed.push(c.name);
+ }
+ assert.equal(actual, expected);
+ });
+}
+if (process.env.M2C_E2E_SUMMARY) {
+ test("summary", () => {
+ process.stdout.write(`\nm2c e2e: ${results.pass} passed, ${results.fail} failed of ${cases.length}\n`);
+ for (const n of results.failed) process.stdout.write(` FAIL ${n}\n`);
+ });
+}
diff --git a/packages/romdev-m2c/test/unit/test_arm.test.mjs b/packages/romdev-m2c/test/unit/test_arm.test.mjs
new file mode 100644
index 00000000..92eff6b8
--- /dev/null
+++ b/packages/romdev-m2c/test/unit/test_arm.test.mjs
@@ -0,0 +1,55 @@
+// Port of m2c tests/unit/test_arm.py
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { Cc, parse_suffix } from "../../src/arch_arm.js";
+
+function parse_cc(cc) {
+ if (!cc) return null;
+ if (cc === "hs") return Cc.CS;
+ if (cc === "lo") return Cc.CC;
+ return Cc.of(cc);
+}
+
+test("parse_suffix handles all known instructions", () => {
+ const dirs = ",ia,ib,da,db,fa,fd,ea,ed".split(",");
+ const cc_strs = ",hs,lo,eq,ne,cs,cc,mi,pl,vs,vc,hi,ls,ge,lt,gt,le,al".split(",");
+ const ccs = cc_strs.map((s) => [s, parse_cc(s)]);
+
+ for (const mn of [
+ "b", "bl", "blx", "bx", "clz", "cmn", "cmp", "cpy", "ldr", "ldrb", "ldrh", "ldrsb", "ldrsh", "mla", "nop",
+ "pop", "push", "rbit", "rev", "rev16", "sdiv", "sdiv", "smlabb", "smulbb", "str", "strb", "strh",
+ "tablejmp.fictive", "teq", "tst", "udiv",
+ ]) {
+ for (const [cc_str, cc] of ccs) assert.deepEqual(parse_suffix(mn + cc_str), [mn, cc, "", ""], mn + cc_str);
+ }
+
+ for (const [cc_str, cc] of ccs) {
+ for (const sz of ["sb", "b", "sh", "h"]) assert.deepEqual(parse_suffix(`ldr${cc_str}${sz}`), [`ldr${sz}`, cc, "", ""]);
+ for (const sz of ["b", "h"]) assert.deepEqual(parse_suffix(`str${cc_str}${sz}`), [`str${sz}`, cc, "", ""]);
+ }
+
+ for (const mn of [
+ "adc", "add", "and", "asr", "bic", "eor", "lsl", "lsr", "mov", "mul", "mvn", "neg", "orn", "orr", "ror",
+ "rrx", "rsb", "rsc", "sbc", "smlal", "smull", "sub", "umlal", "umull",
+ ]) {
+ for (const [cc_str, cc] of ccs) {
+ for (const s of ["", "s"]) {
+ assert.deepEqual(parse_suffix(mn + cc_str + s), [mn, cc, s, ""]);
+ assert.deepEqual(parse_suffix(mn + s + cc_str), [mn, cc, s, ""]);
+ }
+ }
+ }
+
+ for (const mn of ["stm", "ldm"]) {
+ for (const [cc_str, cc] of ccs) {
+ const tr = { fa: ["da", "ib"], ea: ["db", "ia"], fd: ["ia", "db"], ed: ["ib", "da"] };
+ for (const d of dirs) {
+ let exp = d;
+ if (Object.hasOwn(tr, d)) exp = tr[d][mn === "ldm" ? 0 : 1];
+ assert.deepEqual(parse_suffix(`${mn}${cc_str}${d}`), [mn, cc, "", exp]);
+ }
+ }
+ }
+
+ for (const mn of ["it", "cbz", "cbnz"]) assert.deepEqual(parse_suffix(mn), [mn, null, "", ""]);
+});
diff --git a/packages/romdev-m2c/test/visualize.test.mjs b/packages/romdev-m2c/test/visualize.test.mjs
new file mode 100644
index 00000000..d357904f
--- /dev/null
+++ b/packages/romdev-m2c/test/visualize.test.mjs
@@ -0,0 +1,51 @@
+// --visualize: upstream m2c emits the flow graph as graphviz dot and, by
+// default, pipes it through graphviz to SVG. There is no upstream fixture for
+// it, so these expectations come from reading translate.py visualize_flowgraph
+// and main.py. SVG rendering uses graphviz compiled to WASM (@viz-js/viz).
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { decompile } from "../src/index.js";
+
+const SRC = process.env.M2C_SRC || path.join(os.homedir(), ".romdev", "tools", "m2c");
+const ASM = path.join(SRC, "tests", "end_to_end", "loop", "irix-o2.s");
+const skip = fs.existsSync(ASM) ? false : `no upstream checkout at ${SRC}`;
+
+test("dot output follows visualize_flowgraph", { skip }, async () => {
+ const r = await decompile(["--visualize", "c", "--visualize-format", "dot", "--function", "test", ASM]);
+ assert.equal(r.code, 0);
+ const lines = r.stdout.split("\n");
+ assert.deepEqual(lines.slice(0, 3), ["digraph {", ' node [shape="rect", fontname="Monospace"];', ' edge [fontname="Monospace"];']);
+ assert.equal(lines.at(-2), "}");
+ assert.equal(lines.at(-1), "");
+ // One node statement per flow graph node, C lines joined with \l, exit node last.
+ const nodes = lines.filter((l) => /^ {2}"\d+" \[label=/.test(l));
+ assert.equal(nodes.length, 9);
+ assert.equal(nodes[0], ' "0" [label="// Node 0 (line 6)\\lvar_v0 = 0;\\lif ((arg1 <= 0))\\l"];');
+ assert.equal(nodes.at(-1), ' "8" [label="// Node 8\\l// exit\\l"];');
+ // Conditional edges: fallthrough F/blue then taken T/red; basic edges black; return edge bare.
+ assert.ok(lines.includes(' "0" -> "1" [label="F", color="blue"];'));
+ assert.ok(lines.includes(' "0" -> "7" [label="T", color="red"];'));
+ assert.ok(lines.includes(' "2" -> "3" [color="black"];'));
+ assert.ok(lines.includes(' "7" -> "8";'));
+});
+
+test("asm view lists instructions, marking synthetic ones with *", { skip }, async () => {
+ const r = await decompile(["--visualize", "asm", "--visualize-format", "dot", "--function", "test", ASM]);
+ assert.equal(r.code, 0);
+ assert.match(r.stdout, /"7" \[label="\/\/ Node 7 \(line 29\)\\l jr \$ra\\l nop\\l"\]/);
+});
+
+test("default --visualize renders SVG through graphviz WASM", { skip }, async () => {
+ const r = await decompile(["--visualize", "--function", "test", ASM]);
+ assert.equal(r.code, 0);
+ assert.match(r.stdout, /^<\?xml version="1.0" encoding="UTF-8" standalone="no"\?>/);
+ assert.match(r.stdout, /