Skip to content

PS2 games in the browser: static recompilation to WebAssembly with a native runtime

C++

Fix VU branch operand delay and preserve flags at program exit

Riccardo Giorato7b6b6043d418
diff --git a/recomp/vurecomp.cpp b/recomp/vurecomp.cpp
index d96cc5f..6662fc5 100644
--- a/recomp/vurecomp.cpp
+++ b/recomp/vurecomp.cpp
@@ -1,6 +1,7 @@
#include "ps2/vu_ops.hpp"
#include <cstdio>
+#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <format>
@@ -473,11 +474,18 @@ std::string local_vi(std::string o) {
return o;
}
+// The integer register a lower instruction's code writes, or -1.
+int vi_written(const std::string &code) {
+ const std::size_t at = code.find("set_vi(r, ");
+ if (at == std::string::npos) return -1;
+ return std::atoi(code.c_str() + at + 10);
+}
+
std::string generate(const Program &p, std::string &name) {
const std::vector<std::uint32_t> pcs = ps2::vu::reachable(p.code.data(), kMask, p.entry);
std::set<std::uint32_t> in(pcs.begin(), pcs.end());
std::map<std::uint32_t, Lower> lowers;
- bool any_status = false, any_flags = false, any_q = false;
+ bool any_status = false, any_q = false;
for (std::uint32_t pc : pcs) {
const std::uint32_t lo = word(p.code, pc), hi = word(p.code, pc + 4);
Lower l;
@@ -485,7 +493,6 @@ std::string generate(const Program &p, std::string &name) {
for (const std::uint32_t latency : {7u, 13u})
replace_all(l.code, std::format("fl.end_q(r, qb, {}u)", latency), std::format("fl.end_q(r, qb, {}u)", ps2::vu::q_delay(p.code.data(), kMask, pc, latency)));
any_status = any_status || l.reads_status;
- any_flags = any_flags || l.reads_flags;
any_q = any_q || l.code.find("fl.end_q(") != std::string::npos;
lowers[pc] = l;
}
@@ -526,7 +533,7 @@ std::string generate(const Program &p, std::string &name) {
for (std::uint32_t pc : pcs)
for (int reg : upper(word(p.code, pc + 4), true).shadow_reads) shadowed.insert(reg);
name = std::format("vu1_{:016X}", p.key);
- std::string o = std::format("void {}(Vu0Regs &r, std::uint8_t *mem) {{\n FlagPipe fl;\n fl.start(r);\n bool pend = false, pendj = false, ending = false;\n std::uint32_t jpc = 0;\n (void)pend;\n (void)pendj;\n (void)ending;\n (void)jpc;\n",
+ std::string o = std::format("void {}(Vu0Regs &r, std::uint8_t *mem) {{\n FlagPipe fl;\n fl.start(r);\n bool pend = false, pendj = false, ending = false;\n std::uint32_t jpc = 0;\n std::uint16_t bk = 0, next_bk = 0;\n unsigned bi = 0, next_bi = 0;\n (void)pend;\n (void)pendj;\n (void)ending;\n (void)jpc;\n (void)bk;\n (void)next_bk;\n (void)bi;\n (void)next_bi;\n",
name);
for (int reg : shadowed) o += std::format(" v4u {} = vfix(vload({}));\n", shadow(reg), raw(reg));
o += std::format(" goto {};\n", label(p.entry & kMask));
@@ -534,12 +541,23 @@ std::string generate(const Program &p, std::string &name) {
const std::uint32_t lo = word(p.code, pc), hi = word(p.code, pc + 4);
bool out_live = false;
for (std::int64_t s : successors(pc)) out_live = out_live || s < 0 || !in.count(static_cast<std::uint32_t>(s)) || live_in[static_cast<std::uint32_t>(s)];
- const Upper u = upper(hi, any_status ? true : (any_flags && out_live));
+ const Upper u = upper(hi, any_status || out_live);
const Lower &l = lowers[pc];
- std::string body = u.pre;
+ // Save the VI write for the next executed instruction, including
+ // taken branches. Branch operands use the previous instruction's view.
+ const int written = (hi & 0x80000000u) || ps2::vu::branch_delay_exempt(lo) ? -1 : vi_written(l.code);
+ std::string body = "next_bi = 0; ";
+ if (written > 0) body += std::format("next_bk = r.vi[{}]; next_bi = {}; ", written, written);
+ body += u.pre;
+ std::string lcode = l.code;
+ if (l.branch || l.jump) {
+ for (int reg = 1; reg < 16; ++reg)
+ replace_all(lcode, std::format("r.vi[{}]", reg), std::format("(bi == {} ? bk : r.vi[{}])", reg, reg));
+ }
if (hi & 0x80000000u) body += std::format("r.i = {}u; ", lo);
else if (!l.supported) body += std::format("vu::interpret(1, {}u); return; ", pc);
- else body += l.code;
+ else body += lcode;
+ body += "bk = next_bk; bi = next_bi; ";
body += u.post;
o += std::format("{}: {{ ++fl.t; ", label(pc));
if (any_q && ps2::vu::reads_q(hi)) {
diff --git a/runtime/include/ps2/vu_ops.hpp b/runtime/include/ps2/vu_ops.hpp
index a088624..f2a1c51 100644
--- a/runtime/include/ps2/vu_ops.hpp
+++ b/runtime/include/ps2/vu_ops.hpp
@@ -29,6 +29,13 @@ struct Program {
void register_programs(const Program *programs, std::uint32_t count);
inline std::uint32_t lower_major(std::uint32_t lo) { return lo >> 25; }
+// Flag reads bypass the one-instruction VI delay seen by branch operands.
+inline bool branch_delay_exempt(std::uint32_t lo) {
+ switch (lower_major(lo)) {
+ case 0x10: case 0x12: case 0x13: case 0x14: case 0x16: case 0x17: case 0x18: case 0x1A: case 0x1B: case 0x1C: return true;
+ default: return false;
+ }
+}
inline bool is_branch(std::uint32_t lo) {
const std::uint32_t op = lower_major(lo);
return op == 0x20 || op == 0x21 || op == 0x24 || op == 0x25 || (op >= 0x28 && op <= 0x2F && op != 0x2A && op != 0x2B);
diff --git a/runtime/src/vu_jit.cpp b/runtime/src/vu_jit.cpp
index 398ac4d..77264b9 100644
--- a/runtime/src/vu_jit.cpp
+++ b/runtime/src/vu_jit.cpp
@@ -30,7 +30,7 @@ constexpr ImportType kImportTypes[kImports] = {
};
enum Local : std::uint32_t {
- kR, kMem, kPend, kPendj, kEnding, kJpc, kPcw, kUclip, kUx, kUy, kUz, kUw, kTmp, kTmp2, kMacv, kStat, kSlot, kI32Locals,
+ kR, kMem, kPend, kPendj, kEnding, kJpc, kPcw, kUclip, kUx, kUy, kUz, kUw, kTmp, kTmp2, kMacv, kStat, kSlot, kBranchReg, kBranchValue, kNextBranchReg, kNextBranchValue, kI32Locals,
kUv = kI32Locals, kV0, kV1, kV2, kV3, kV4, kV5, kShadow0
};
constexpr std::uint32_t kI32Count = kI32Locals - 2;
@@ -452,8 +452,26 @@ private:
c_.load16(vi_off(i));
}
+ void branch_vi(unsigned i) {
+ if (!i) { c_.i32c(0); return; }
+ c_.get(kBranchValue);
+ vi(i);
+ c_.get(kBranchReg);
+ c_.i32c(i);
+ c_.op(kOpEq);
+ c_.op(kOpSelect);
+ }
+
+ bool delay_vi_ = false;
+
template <typename F>
void set_vi(unsigned i, F value) {
+ if (i && delay_vi_) {
+ vi(i);
+ c_.set(kNextBranchValue);
+ c_.i32c(i);
+ c_.set(kNextBranchReg);
+ }
if (i) c_.get(kR);
value();
if (i) c_.store16(vi_off(i));
@@ -1212,7 +1230,7 @@ bool Translator::lower(std::uint32_t w, std::uint32_t pc) {
break;
case 0x24:
case 0x25:
- vi(is);
+ branch_vi(is);
c_.i32c(8);
c_.op(kOpMul);
c_.i32c(kMask);
@@ -1224,14 +1242,14 @@ bool Translator::lower(std::uint32_t w, std::uint32_t pc) {
break;
case 0x28:
case 0x29:
- vi(is);
- vi(it);
+ branch_vi(is);
+ branch_vi(it);
c_.op((w >> 25) == 0x28 ? kOpEq : kOpNe);
c_.set(kPend);
break;
case 0x2C: case 0x2D: case 0x2E: case 0x2F: {
static const std::uint8_t kCompare[4] = {kOpLtS, kOpGtS, kOpLeS, kOpGeS};
- vi(is);
+ branch_vi(is);
c_.op(kOpExt16);
c_.i32c(0);
c_.op(kCompare[(w >> 25) - 0x2C]);
@@ -1247,12 +1265,11 @@ bool Translator::run(std::vector<std::uint8_t> &out) {
pcs_ = reachable(code_, kMask, entry_);
if (pcs_.empty()) return false;
in_.insert(pcs_.begin(), pcs_.end());
- bool any_status = false, any_flags = false;
+ bool any_status = false;
for (std::uint32_t pc : pcs_) {
LowerInfo l;
if (!(word(pc + 4) & 0x80000000u)) l = analyze_lower(word(pc), pc);
any_status = any_status || l.reads_status;
- any_flags = any_flags || l.reads_flags;
lowers_[pc] = l;
}
for (std::uint32_t pc : pcs_) live_in_[pc] = false;
@@ -1317,7 +1334,7 @@ bool Translator::run(std::vector<std::uint8_t> &out) {
const std::uint32_t pc = pcs_[k];
const std::uint32_t lo = word(pc), hi = word(pc + 4);
const Up u = decode_upper(hi);
- const bool flags_live = any_status ? true : (any_flags && out_live(pc));
+ const bool flags_live = any_status || out_live(pc);
const LowerInfo &li = lowers_[pc];
fl();
@@ -1333,6 +1350,10 @@ bool Translator::run(std::vector<std::uint8_t> &out) {
c_.call(kind == kQNew ? kFlushQ : kSyncQ);
}
}
+ c_.i32c(0);
+ c_.set(kNextBranchReg);
+ // Flag reads write VI without the branch operand delay.
+ delay_vi_ = !branch_delay_exempt(lo);
upper_pre(u, flags_live);
if (hi & 0x80000000u) {
c_.get(kR);
@@ -1343,6 +1364,10 @@ bool Translator::run(std::vector<std::uint8_t> &out) {
c_.i32c(pc);
c_.tail(kInterpret);
}
+ c_.get(kNextBranchReg);
+ c_.set(kBranchReg);
+ c_.get(kNextBranchValue);
+ c_.set(kBranchValue);
upper_post(u, flags_live);
const int lower_write = (hi & 0x80000000u) || !li.supported ? -1 : li.writes;
if (lower_write >= 0 && shadow_.count(lower_write)) {
diff --git a/runtime/src/vu_micro.cpp b/runtime/src/vu_micro.cpp
index 87f216c..73bebf0 100644
--- a/runtime/src/vu_micro.cpp
+++ b/runtime/src/vu_micro.cpp
@@ -34,6 +34,9 @@ struct Unit {
std::uint32_t data_qwords;
std::uint32_t tpc;
vuops::FlagPipe *pipe = nullptr;
+ // What a branch reads of the integer registers: the values from before the
+ // previous instruction when that one wrote them (see BranchView).
+ const std::uint16_t *branch_vi = nullptr;
};
Vu0Regs g_vu1;
@@ -69,6 +72,7 @@ std::uint32_t q_delay_of(const Unit &u, std::uint32_t pc, std::uint32_t latency)
}
std::uint64_t g_reported = 0;
+bool g_reference_dry = false;
Unit unit_of(int n) {
if (n == 0) return Unit{&g_cpu.vu0, g_vu0_code, g_vu0_mem, 4095u, 256u, g_cpu.vu0.tpc};
@@ -441,6 +445,7 @@ float u2f(std::uint32_t v) {
}
void xgkick(Unit &u, std::uint32_t address) {
+ if (g_reference_dry) return;
std::uint8_t buffer[16 * 1024 + 16];
std::uint32_t q = address & (u.data_qwords - 1), count = 0;
bool done = false;
@@ -463,6 +468,26 @@ void xgkick(Unit &u, std::uint32_t address) {
gif::transfer(1, buffer, count);
}
+// A VU branch that reads an integer register the instruction right before it
+// wrote sees the value from before that write: the integer pipeline commits
+// after the branch unit reads, and compiled game code counts on it (a loop
+// that decrements its counter just before testing it runs one pass more). A
+// flag reading instruction (FMAND, FCAND...) writing the register does not
+// delay it. PCSX2 calls this the branch VI delay.
+struct BranchView {
+ std::uint16_t before[16] = {};
+ bool live = false;
+
+ // Before an instruction runs: what its branch, if it is one, reads.
+ void arm(Unit &u) const { u.branch_vi = live ? before : nullptr; }
+ // Keep the registers as they are before this instruction for the next one.
+ void snapshot(const Vu0Regs &r, std::uint16_t (&now)[16]) const { std::memcpy(now, r.vi, sizeof now); }
+ void commit(const std::uint16_t (&was)[16], std::uint32_t lo, bool lower_ran) {
+ std::memcpy(before, was, sizeof before);
+ live = lower_ran && !branch_delay_exempt(lo);
+ }
+};
+
void lower(Unit &u, std::uint32_t w, std::uint32_t pc, std::uint32_t &npc, bool &branch) {
Vu0Regs &r = *u.regs;
const unsigned dest = (w >> 21) & 15u, it = (w >> 16) & 15u, is = (w >> 11) & 15u, id = (w >> 6) & 15u;
@@ -475,6 +500,7 @@ void lower(Unit &u, std::uint32_t w, std::uint32_t pc, std::uint32_t &npc, bool
npc = target & u.code_mask;
branch = true;
};
+ const auto bvi = [&](unsigned k) -> std::uint16_t { return u.branch_vi ? u.branch_vi[k] : r.vi[k]; };
if ((w >> 25) == 0x40u) {
const unsigned funct = w & 63u;
if (funct < 0x3C) {
@@ -645,14 +671,14 @@ void lower(Unit &u, std::uint32_t w, std::uint32_t pc, std::uint32_t &npc, bool
case 0x1C: store_vi(r, it, clip_flags() & 0xFFFu); break;
case 0x20: branch_to(target); break;
case 0x21: store_vi(r, it, (pc + 16u) / 8u); branch_to(target); break;
- case 0x24: branch_to(static_cast<std::uint32_t>(r.vi[is]) * 8u); break;
- case 0x25: { const std::uint32_t t = static_cast<std::uint32_t>(r.vi[is]) * 8u; store_vi(r, it, (pc + 16u) / 8u); branch_to(t); break; }
- case 0x28: if (r.vi[is] == r.vi[it]) branch_to(target); break;
- case 0x29: if (r.vi[is] != r.vi[it]) branch_to(target); break;
- case 0x2C: if (static_cast<std::int16_t>(r.vi[is]) < 0) branch_to(target); break;
- case 0x2D: if (static_cast<std::int16_t>(r.vi[is]) > 0) branch_to(target); break;
- case 0x2E: if (static_cast<std::int16_t>(r.vi[is]) <= 0) branch_to(target); break;
- case 0x2F: if (static_cast<std::int16_t>(r.vi[is]) >= 0) branch_to(target); break;
+ case 0x24: branch_to(static_cast<std::uint32_t>(bvi(is)) * 8u); break;
+ case 0x25: { const std::uint32_t t = static_cast<std::uint32_t>(bvi(is)) * 8u; store_vi(r, it, (pc + 16u) / 8u); branch_to(t); break; }
+ case 0x28: if (bvi(is) == bvi(it)) branch_to(target); break;
+ case 0x29: if (bvi(is) != bvi(it)) branch_to(target); break;
+ case 0x2C: if (static_cast<std::int16_t>(bvi(is)) < 0) branch_to(target); break;
+ case 0x2D: if (static_cast<std::int16_t>(bvi(is)) > 0) branch_to(target); break;
+ case 0x2E: if (static_cast<std::int16_t>(bvi(is)) <= 0) branch_to(target); break;
+ case 0x2F: if (static_cast<std::int16_t>(bvi(is)) >= 0) branch_to(target); break;
default:
if (g_reported++ < 32) std::fprintf(stderr, "[vu] lower 0x%08X at 0x%04X\n", w, pc);
break;
@@ -833,22 +859,18 @@ void interpret(int unit, std::uint32_t pc) {
}
void run_entry(int unit, std::uint32_t pc) {
- // The compile of VU1 programs mistranslates at least three of them (PS2_VU_CHECK
-// names them and diverges on vf/vi/q and micro memory), and the interpreter
-// serves the games right everywhere it was compared, so until the compiler
-// fault itself is fixed the safe default is to interpret. PS2_VU_JIT=1 opts a
-// port back into the compiled programs to find the faults faster.
- static const bool interpret_only = !std::getenv("PS2_VU_JIT");
+ // Compiled programs are the default; retain an interpreter override for
+ // differential checks and diagnosing newly recorded programs.
+ static const bool interpret_only = [] {
+ const char *env = std::getenv("PS2_VU_JIT");
+ return env && std::strcmp(env, "0") == 0;
+ }();
static const bool count = std::getenv("PS2_VU_COUNT") != nullptr;
static std::uint64_t compiled = 0, interpreted = 0;
static std::unordered_map<std::uint32_t, std::uint64_t> misses;
- // Programs whose compiled form PS2_VU_CHECK showed diverging from the
- // interpreter, with state the interpreter serves right; their compiled
- // functions stay unused until the compiler fault they expose is fixed.
- static const std::unordered_set<std::uint64_t> kSuspects{0x4A2C985BE015965Cull, 0x93C6540607E7215Dull};
if (unit == 1 && !interpret_only) {
const ProgramFn fn = lookup(pc);
- if (fn && !kSuspects.count(g_entries[(pc & 16383u) >> 3].key)) {
+ if (fn) {
++compiled;
const ProgramFn jit = g_entries[(pc & 16383u) >> 3].jit;
static std::uint64_t sampled = 0;
@@ -871,8 +893,12 @@ void run_entry(int unit, std::uint32_t pc) {
std::memcpy(run_mem, g_vu1_mem, sizeof run_mem);
g_vu1 = before;
std::memcpy(g_vu1_mem, before_mem, sizeof g_vu1_mem);
+ // The reference is the interpreter loop itself: interpret()
+ // would only queue the entry while a chain is running.
checking = true;
- interpret(1, pc);
+ g_reference_dry = true;
+ run_fast(1, pc);
+ g_reference_dry = false;
checking = false;
if (escape < 0 && (std::memcmp(&after, &g_vu1, sizeof after) != 0 || std::memcmp(run_mem, g_vu1_mem, sizeof run_mem) != 0)) {
if (++mismatches <= 20) {
@@ -891,8 +917,11 @@ void run_entry(int unit, std::uint32_t pc) {
}
}
++checked;
+ if (checked == 1 || checked % 100 == 0)
+ std::fprintf(stderr, "[vu-check-summary] sampled %llu calls, %llu mismatches\n", static_cast<unsigned long long>(checked), static_cast<unsigned long long>(mismatches));
g_vu1 = after;
std::memcpy(g_vu1_mem, run_mem, sizeof g_vu1_mem);
+ if (escape >= 0) interpret(1, static_cast<std::uint32_t>(escape));
return;
}
if (jit && jit != fn && ++sampled % 32 == 0) check_jit(fn, jit);
@@ -974,6 +1003,7 @@ void run_fast(int n, std::uint32_t address) {
static const bool count = std::getenv("PS2_VU_COUNT") != nullptr;
static const bool record_jumps = std::getenv("PS2_VU_RECORD") != nullptr || static_cast<bool>(g_options.on_vu_program);
if (count && ++calls % 20000 == 0) std::fprintf(stderr, "[vu1] %llu calls, %llu instructions\n", (unsigned long long)calls, (unsigned long long)total);
+ BranchView view;
for (std::uint32_t steps = 0; steps < 1'000'000; ++steps, ++total) {
std::uint32_t lo, hi;
std::memcpy(&lo, u.code + pc, 4);
@@ -989,6 +1019,9 @@ void run_fast(int n, std::uint32_t address) {
++pipe.t;
read_q(u, pipe, r, current, hi);
fast_upper(r, d, out);
+ std::uint16_t was[16];
+ view.snapshot(r, was);
+ view.arm(u);
if (hi & 0x80000000u) {
r.i = lo;
} else {
@@ -998,6 +1031,8 @@ void run_fast(int n, std::uint32_t address) {
if (branch) npc = target;
if (branch && record_jumps && n == 1 && ((lo >> 25) == 0x24u || (lo >> 25) == 0x25u)) lookup(target);
}
+ u.branch_vi = nullptr;
+ view.commit(was, lo, !(hi & 0x80000000u));
if (out.target > 0) {
Reg128 &dst = out.target == kAcc ? r.acc : r.vf[out.target];
for (int i = 0; i < 4; ++i)
@@ -1038,6 +1073,7 @@ void run(int n, std::uint32_t address) {
u.pipe = &pipe;
std::uint32_t pc = address & u.code_mask, npc = (pc + 8u) & u.code_mask;
bool ending = false;
+ BranchView view;
for (std::uint32_t steps = 0; steps < 1'000'000; ++steps) {
std::uint32_t lo, hi;
std::memcpy(&lo, u.code + pc, 4);
@@ -1049,6 +1085,9 @@ void run(int n, std::uint32_t address) {
read_q(u, pipe, r, current, hi);
UpperOut out = upper(r, hi);
bool branch = false;
+ std::uint16_t was[16];
+ view.snapshot(r, was);
+ view.arm(u);
if (hi & 0x80000000u) {
r.i = lo;
} else {
@@ -1056,6 +1095,8 @@ void run(int n, std::uint32_t address) {
lower(u, lo, current, target, branch);
if (branch) npc = target;
}
+ u.branch_vi = nullptr;
+ view.commit(was, lo, !(hi & 0x80000000u));
commit(r, out);
if (out.target >= 0 && out.flags) pipe.set_mac(r.mac, r.status);
if (out.has_clip) {
diff --git a/scripts/test_vu_codegen.py b/scripts/test_vu_codegen.py
new file mode 100644
index 0000000..b877705
--- /dev/null
+++ b/scripts/test_vu_codegen.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python3
+"""Exercise native and Wasm VU code generation without a game disc.
+
+Requires a C++20 compiler with std::format and Node with Wasm SIMD/tail calls.
+Run from any directory: python3 scripts/test_vu_codegen.py [c++ compiler]
+"""
+import pathlib
+import subprocess
+import sys
+import tempfile
+
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+CXX = sys.argv[1] if len(sys.argv) > 1 else 'clang++'
+
+GENERATOR = r'''
+#define main vurecomp_main
+#include "recomp/vurecomp.cpp"
+#undef main
+#include "runtime/src/vu_jit.hpp"
+#include <cstddef>
+
+int main(int argc, char **argv) {
+ const fs::path out = argv[1];
+ std::ofstream native(out / "native.cpp");
+ native << "#include <stdexcept>\n#include <cstdio>\n#include \"ps2/vu_ops.hpp\"\n"
+ "namespace ps2::vu { void interpret(int, std::uint32_t) { throw std::runtime_error(\"unexpected fallback\"); } }\n"
+ "using namespace ps2; using namespace ps2::vuops;\n";
+ constexpr std::uint32_t nop = 0x8000033C, unop = 0x000002FF, end = 0x40000000;
+ const auto addi = [](unsigned it, unsigned is, unsigned imm) { return (8u << 25) | (it << 16) | (is << 11) | imm; };
+ const auto branch = [](unsigned op, unsigned is, unsigned it, unsigned from, unsigned to) {
+ return (op << 25) | (is << 11) | (it << 16) | (((to - from - 8u) / 8u) & 0x7FFu);
+ };
+ for (int test = 0; test < 8; ++test) {
+ Program p{static_cast<std::uint64_t>(test), 0, std::vector<std::uint8_t>(16384)};
+ const auto put = [&](unsigned pc, std::uint32_t lo, std::uint32_t hi = unop) {
+ std::memcpy(p.code.data() + pc, &lo, 4);
+ std::memcpy(p.code.data() + pc + 4, &hi, 4);
+ };
+ for (unsigned pc = 0; pc < 128; pc += 8) put(pc, nop);
+ if (test < 3 || test == 5) {
+ // A preceding VI write delays a comparison, but FCAND does not.
+ put(0, test == 2 ? (0x12u << 25) | 1u : addi(1, 0, 1));
+ put(8, branch(test == 5 ? 0x2C : test == 2 ? 0x29 : 0x28, test == 1 ? 0 : 1, test == 0 ? 3 : 0, 8, 40));
+ put(24, addi(2, 0, 1), unop | end);
+ put(40, addi(2, 0, 2), unop | end);
+ } else if (test == 3) {
+ // The instruction executed before PC 40 is a taken branch's
+ // delay slot at PC 8, rather than the instruction at PC 32.
+ put(0, branch(0x20, 0, 0, 0, 40));
+ put(8, addi(1, 0, 1));
+ put(32, addi(1, 0, 3));
+ put(40, branch(0x28, 1, 3, 40, 72));
+ put(56, addi(2, 0, 1), unop | end);
+ put(72, addi(2, 0, 2), unop | end);
+ } else if (test >= 6) {
+ // JR/JALR use the saved operand; JALR may also overwrite it.
+ put(0, addi(1, 0, 1));
+ put(8, ((test == 6 ? 0x24u : 0x25u) << 25) | (1u << 11) | (1u << 16), unop | end);
+ } else {
+ // Flags remain observable after exit even with no local reader.
+ put(0, nop, (0xFu << 21) | (2u << 16) | (1u << 11) | (3u << 6) | 0x28u | end);
+ }
+ std::string name;
+ native << generate(p, name);
+ std::vector<std::uint8_t> wasm;
+ if (!ps2::vu::jit::translate(p.code.data(), 0, {0x1000, 0x2000}, wasm)) return 1;
+ std::ofstream(out / std::format("{}.wasm", test), std::ios::binary).write(reinterpret_cast<const char *>(wasm.data()), wasm.size());
+ }
+ native << "int main() {\n";
+ for (int test = 0; test < 8; ++test) {
+ native << "{ Vu0Regs r{}; std::uint8_t mem[16384]{}; r.vi[1]=2; r.vi[3]=2; r.clip=1;"
+ "for (int i=0;i<4;++i) r.vf[1].w[i]=0xBF800000; r.vf[0].w[3]=0x3F800000;\n";
+ if (test == 5) native << "r.vi[1]=0xFFFF;\n";
+ native << std::format("vu1_{:016X}(r, mem);\n", test);
+ native << (test >= 6 ? "if (r.tpc != 16) return 1;\n" : test == 4 ? "if (r.mac != 0xF0 || r.status != 0x82) return 1;\n" : "if (r.vi[2] != 2) return 1;\n");
+ native << "}\n";
+ }
+ native << "puts(\"8 native VU regressions passed\"); }\n";
+ std::ofstream offsets(out / "offsets.json");
+ offsets << std::format("{{\"vi\":{},\"vf\":{},\"clip\":{},\"mac\":{},\"status\":{},\"tpc\":{}}}", offsetof(ps2::Vu0Regs, vi), offsetof(ps2::Vu0Regs, vf), offsetof(ps2::Vu0Regs, clip), offsetof(ps2::Vu0Regs, mac), offsetof(ps2::Vu0Regs, status), offsetof(ps2::Vu0Regs, tpc));
+}
+'''
+
+WASM_TEST = r'''
+const fs = require('node:fs');
+const path = require('node:path');
+const dir = process.argv[2];
+const off = JSON.parse(fs.readFileSync(path.join(dir, 'offsets.json')));
+for (let test = 0; test < 8; ++test) {
+ const memory = new WebAssembly.Memory({initial: 1, maximum: 65536, shared: true});
+ const view = new DataView(memory.buffer);
+ const r = 0x3000;
+ view.setUint16(r + off.vi + 2, test === 5 ? 0xFFFF : 2, true);
+ view.setUint16(r + off.vi + 6, 2, true);
+ view.setUint32(r + off.clip, 1, true);
+ view.setUint32(r + off.vf + 12, 0x3F800000, true);
+ for (let i = 0; i < 4; ++i) view.setUint32(r + off.vf + 16 + 4*i, 0xBF800000, true);
+ const mod = new WebAssembly.Module(fs.readFileSync(path.join(dir, `${test}.wasm`)));
+ const env = {memory};
+ for (const imp of WebAssembly.Module.imports(mod)) {
+ if (imp.kind !== 'function') continue;
+ env[imp.name] = () => { throw Error(`Unexpected import: ${imp.name}`); };
+ }
+ // These fixtures need only start, clip reads and flushing an idle Q pipe.
+ env.start = () => {};
+ env.clip = () => 1;
+ env.flush_q = () => {};
+ new WebAssembly.Instance(mod, {env}).exports.run(r, 0x4000);
+ if (test >= 6) {
+ if (view.getUint32(r + off.tpc, true) !== 16) throw Error(`Register jump regression ${test}`);
+ } else if (test === 4) {
+ if (view.getUint32(r + off.mac, true) !== 0xF0 || view.getUint32(r + off.status, true) !== 0x82)
+ throw Error('Exit flags were dropped');
+ } else if (view.getUint16(r + off.vi + 4, true) !== 2) {
+ throw Error(`Branch VI regression ${test}`);
+ }
+}
+console.log('8 Wasm VU regressions passed');
+'''
+
+
+def run(*args):
+ subprocess.run(args, check=True, cwd=ROOT)
+
+
+with tempfile.TemporaryDirectory(prefix='vu-codegen-') as tmp:
+ tmp = pathlib.Path(tmp)
+ (tmp / 'generator.cpp').write_text(GENERATOR)
+ run(CXX, '-std=c++20', '-O2', '-I.', '-Iruntime/include',
+ str(tmp / 'generator.cpp'), 'runtime/src/vu_jit.cpp', '-o', str(tmp / 'generator'))
+ run(str(tmp / 'generator'), str(tmp))
+ run(CXX, '-std=c++20', '-O2', '-Iruntime/include', str(tmp / 'native.cpp'), '-o', str(tmp / 'native'))
+ run(str(tmp / 'native'))
+ (tmp / 'wasm.cjs').write_text(WASM_TEST)
+ run('node', str(tmp / 'wasm.cjs'), str(tmp))