"""NZCV as the lifted functions' locals (nx2/local_flags.py, A64_LOCAL_FLAGS, on by default), against the flags as bytes of the context (A64_LOCAL_FLAGS=0), on whole functions run natively (game-free). (Triforce, 11-23, the fps pass's LX-2, after NX2navi 0.11.0-rc4's recomp/flags.py.) The kit's switch makes every c->n, c->z, c->c and c->v of a function a local, read at its start and written back only where control leaves other than by a call or a return (a tail call, an indirect jump, an SVC, a trap). The kit's own reader takes any value that is set and not empty as on, so nx2/local_flags.py puts its rule in that reader's place (a64_lift.local_flags). The rule: unset, empty or any value but 0 is on, 0 is off. After install() the kit reads it so, and the environment keeps the value the player set. (11-27) So does a fresh process started after install() that runs nx2/lift.py's module level, as the lift's emit processes are spawned on Windows: install() wrote "1" or nothing into the environment, and such a process read nothing as on, so with A64_LOCAL_FLAGS=0 its C had the locals and the lift's a64_fpx.h not their helpers. And install() stops when the kit's A64_PACKED_FLAGS (one store of the four flags into the context, which the locals do not see) is on beside the locals. The run: five functions written here in AArch64 (no memory access: registers and flags alone) go through the kit's discovery and its write() with a64emit's real translator, once with the switch unset (the default) and once with A64_LOCAL_FLAGS=0. Every flag reader is there: B.cond, CSEL, CSINC/CSET, CCMP (register and immediate), ADC and SBCS (the carry in), in 64 and 32 bits, in a loop, and across a tail call (CMP then B into another function that reads the flags it came with), around a call (flags set before a BL and again after it). Both lifts are compiled into one driver that runs every function from the same random states (X0-X30, SP and NZCV) and compares X0-X30 and SP after (NZCV is not compared: it is dead at a return, as nx2/test_leaf.py says). The first lift must hold the locals (fz_) and the second none. With the switch on the context's flags are written back before the tail call, so the function it enters reads what its caller set. And reads the source: nx2/lift.py installs it after vecfp's, A64_LOCAL_FLAGS is an A64_ name (in nx2/make_game.py's lift key, as nx2/local_flags.py is), nx2/oot_patches.py's scene colour patch has the local form of its Z read, and the switch is in the switches table. (11-26, on v0.8.3) And the three edits of v0.8.3 that match a flag by its text take the local form too, each applied once to an authored function in that form and left as it is by a second run: the horse's jump step test (its FCMP as the code form, a64_fcmp32k, and its branch on fn_), the Camera centering row's anchor (fz_) and the ocarina wait's mode gate (fz_, with the other gates and hooks of the tick). Without that they are found 0 times in such a lift, and the build only warns. (11-26, on v0.8.4) Both lifts go through every pass nx2/lift.py installs, in its order (the module is imported), so the flags as locals meet the game's other passes and v0.8.4's nx2/nativefp.py, which stays last. A sixth function is float and on the hot list (A64_HOT_FUNCS): FADD, FMUL, an FCMP read by two CSETs (GT, and HI, which reads its C) and B.cond, FCVTZS, FMOV and MSR FPCR. Its FCMP is the code form (a64_fcmp32k) with the switch on and a64_fcmp32 with it off; nativefp must give it the same native names and the same FPCR sync in both lifts; and the run compares V0-V7, FPCR and FPSR too, from random float states. (11-27) The authored functions of the flag edits have the flags' declaration after their head, as the kit writes it, and the cloth's solve gate (counted in lines from the head) is made with it there: a lift of v0.8.4 with the flags as locals left that gate out, only warning, and the cloth solved at every frame above 60 fps. And both lifts are compiled with clang's profile counters (-fprofile-instr-generate, to LLVM IR), and every function's control-flow hash, by which the hot code's -fprofile-instr-use finds its entry in the shipped profile, must be the same in both: the kit's code form of the FCMP put an else where the lift without the switch has a !, and 652 of v0.8.4's 1384 hot functions were built without their profile. The FCMP is in nx2/local_flags.py's form (profile_form), and the horse's step patch takes both forms. (11-27) The horse's step test in each form (nx2/oot_patches.py HORSE_TEST, HORSE_TEST_LOCAL) is the lifted float function's own FCMP, but for the registers. Two stores through one base around that FCMP share one page mark (a64_lift.group_marks) in both lifts, and with the switch off the grouped C is the same as before the kit's MG_PLAIN named a64_fcmp32k and a64_fcmp64k. nx2/oot_patches.py's FLAG_REF is the kit's. python -I -B tests/test_local_flags.py [--cc clang] [--cxx clang++] [--random 200000] Skipped (exit 0) on a host that is not x86-64 or has no C or C++ compiler. """ import argparse import os import platform import re import sys import tempfile import time ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(ROOT, "tests")) sys.path.insert(0, os.path.join(ROOT, "nx2")) import test_fpx_sticky as fs # noqa: E402 (the build helpers the kit's other lifted-code tests use) RUN_ALL_ARGS = ["--cc", "clang", "--cxx", "{cxx}"] SEED = 20261123 SWITCH = "A64_LOCAL_FLAGS" BASE = 0x80000000 EQ, NE, CS, CC, MI, PL, VS, VC, HI, LS, GE, LT, GT, LE = range(14) XZR = 31 RET = 0xD65F03C0 # ---- an assembler for the few forms used ---------------------------------------------------------------------------- def subs_imm(d, n, imm, sf=1): return (sf << 31) | 0x71000000 | (imm << 10) | (n << 5) | d def subs_reg(d, n, m, sf=1): return (sf << 31) | 0x6B000000 | (m << 16) | (n << 5) | d def adds_reg(d, n, m, sf=1): return (sf << 31) | 0x2B000000 | (m << 16) | (n << 5) | d def adc(d, n, m): return 0x9A000000 | (m << 16) | (n << 5) | d def sbcs(d, n, m): return 0xFA000000 | (m << 16) | (n << 5) | d def csel(d, n, m, cond, sf=1): return (sf << 31) | 0x1A800000 | (m << 16) | (cond << 12) | (n << 5) | d def csinc(d, n, m, cond, sf=1): return (sf << 31) | 0x1A800400 | (m << 16) | (cond << 12) | (n << 5) | d def cset(d, cond, sf=1): return csinc(d, XZR, XZR, cond ^ 1, sf) def ccmp_reg(n, m, nzcv, cond, sf=1): return (sf << 31) | 0x7A400000 | (m << 16) | (cond << 12) | (n << 5) | nzcv def ccmp_imm(n, imm5, nzcv, cond, sf=1): return (sf << 31) | 0x7A400800 | (imm5 << 16) | (cond << 12) | (n << 5) | nzcv def movz(d, imm16): return 0xD2800000 | (imm16 << 5) | d def add_imm(d, n, imm): return 0x91000000 | (imm << 10) | (n << 5) | d def sub_imm(d, n, imm): return 0xD1000000 | (imm << 10) | (n << 5) | d def eor(d, n, m): return 0xCA000000 | (m << 16) | (n << 5) | d def tst(n, m): return 0xEA000000 | (m << 16) | (n << 5) | XZR def fadd_s(d, n, m): return 0x1E202800 | (m << 16) | (n << 5) | d def fmul_s(d, n, m): return 0x1E200800 | (m << 16) | (n << 5) | d def fcmp_s(n, m): return 0x1E202000 | (m << 16) | (n << 5) def fcvtzs_ws(d, n): return 0x1E380000 | (n << 5) | d def fmov_ws(d, n): return 0x1E260000 | (n << 5) | d def msr_fpcr(t): return 0xD51B4400 | t HOT = "f_80000400" # (the float function, on the hot list: nativefp's names go on hot text) NATIVE = (("scalar", r"\ba64_fpx_nat_\w+\(c,"), ("vector", r"\ba64_vfpx_nat_\w+\(c,"), ("conversion", r"\ba64_nat_(?:fp_to_int|fixed_to_fp)\("), ("block gate", r"A64_NAT_OPEN_BK\("), ("FPCR sync", r"hos_fpcr_sync\(c\)")) def program(): """{address: word} of six functions, and their entries. Labels are resolved in a second pass.""" funcs = { # 0: flags in a loop: every reader, in 64 and 32 bits 0x000: [movz(9, 7), ("L1", subs_imm(9, 9, 1)), adds_reg(2, 0, 1), adc(3, 3, 2), subs_reg(XZR, 0, 1), csel(4, 0, 1, LT), ccmp_reg(2, 3, 4, NE), csinc(5, 5, 4, HI), subs_reg(XZR, 6, 7, 0), cset(8, GE), sbcs(10, 10, 0), cset(11, VS), eor(0, 0, 2), ("cbnz", 9, "L1"), tst(0, 1), ("b.cond", MI, "L2"), add_imm(12, 12, 3), ("L2", subs_reg(XZR, 12, 13)), ("b.cond", GT, "L3"), sub_imm(13, 13, 5), ("L3", RET)], # 1: a compare, then a tail call that carries the flags into function 2 0x100: [subs_reg(XZR, 0, 1), add_imm(5, 5, 1), ("b", 0x140)], # 2: reads the flags it is entered with 0x140: [csel(2, 0, 1, GE), ("b.cond", EQ, "M1"), add_imm(3, 3, 1), ("M1", cset(4, HI)), RET], # 3: flags set before a call and again after it (the AAPCS64 leaves them undefined across it) 0x180: [subs_reg(XZR, 0, 1), ("bl", 0x000), adds_reg(6, 2, 4), csel(7, 6, 5, CC), cset(14, LE), RET], # 4: 32-bit and immediate compares, a CCMP chain, a TBNZ around a flag setter 0x1C0: [subs_imm(XZR, 0, 10, 0), ccmp_imm(1, 3, 2, LT, 0), csel(2, 0, 1, LE, 0), ("tbnz", 3, 5, "N1"), subs_reg(4, 4, 5, 0), ("N1", cset(6, MI, 0)), csinc(7, 7, 6, PL), RET], # 5: float, on the hot list (nativefp's names): FADD, FMUL, an FCMP read by two CSETs (GT, HI) and B.cond, FCVTZS, FMOV, # MSR FPCR 0x400: [fadd_s(2, 0, 1), fmul_s(3, 2, 0), fcmp_s(3, 1), cset(4, GT), cset(9, HI), ("b.cond", MI, "N2"), add_imm(5, 5, 1), ("N2", fcvtzs_ws(6, 3)), fmov_ws(7, 2), msr_fpcr(8), RET], } words, labels, fix = {}, {}, [] for start, items in funcs.items(): at = BASE + start for it in items: if isinstance(it, tuple) and isinstance(it[0], str) and it[0].startswith(("L", "M", "N")) and len(it) == 2: labels[it[0]] = at it = it[1] if isinstance(it, tuple): fix.append((at, it)) words[at] = 0 else: words[at] = it at += 4 for at, it in fix: kind = it[0] if kind == "b": words[at] = 0x14000000 | (((BASE + it[1] - at) >> 2) & 0x3FFFFFF) elif kind == "bl": words[at] = 0x94000000 | (((BASE + it[1] - at) >> 2) & 0x3FFFFFF) elif kind == "b.cond": words[at] = 0x54000000 | ((((labels[it[2]] - at) >> 2) & 0x7FFFF) << 5) | it[1] elif kind == "cbnz": words[at] = 0xB5000000 | ((((labels[it[2]] - at) >> 2) & 0x7FFFF) << 5) | it[1] elif kind == "tbnz": words[at] = (0x37000000 | ((it[2] >> 5) << 31) | ((it[2] & 31) << 19) | ((((labels[it[3]] - at) >> 2) & 0x3FFF) << 5) | it[1]) return words, sorted(BASE + s for s in funcs) class Image: def __init__(self): self.words, starts = program() self.entries = set(starts) self.hooks = {} self.names = {} def in_code(self, pc): return pc in self.words def word(self, pc): return self.words[pc] def read(self, addr, size): return b"\0" * size def put(name, value): if value is None: os.environ.pop(name, None) else: os.environ[name] = value # a process the lift starts for its emit, as Windows starts it (spawned): a fresh interpreter that runs nx2/lift.py's module # level again, with the lift's environment as it stands, and says how the kit reads the switch there FRESH = ("import os, sys; sys.path.insert(0, %r); import lift, a64_lift; " "print('kit=%%s env=%%r' %% (a64_lift.local_flags(), os.environ.get('A64_LOCAL_FLAGS')))") def check_rule(local_flags, a64_lift): """The rule, as the kit reads it after install() (a64_lift.local_flags), with the environment left as the player set it, in this process and in a fresh one started after it (11-27: install() wrote "1" or nothing into the environment, and a spawned emit process, which runs install() again, read nothing as on: with A64_LOCAL_FLAGS=0 its C had the locals and the a64_fcmp32k calls, the lift's a64_fpx.h not the helper). And the kit's A64_PACKED_FLAGS beside the locals stops it""" import subprocess bad = [] saved = {k: os.environ.get(k) for k in (SWITCH, "A64_PACKED_FLAGS")} try: put("A64_PACKED_FLAGS", None) for v, want in ((None, True), ("", True), ("1", True), (" 1 ", True), ("0", False), (" 0 ", False)): if local_flags.on(v) != want: bad.append("on(%r) is %s" % (v, local_flags.on(v))) put(SWITCH, v) local_flags.install() if a64_lift.local_flags() != want: bad.append("after install with %r the kit reads %s" % (v, a64_lift.local_flags())) if os.environ.get(SWITCH) != v: bad.append("install with %r leaves %r in the environment" % (v, os.environ.get(SWITCH))) if local_flags.report().startswith("flags: N, Z, C and V as each function's locals") != want: bad.append("the lift's line with %r is %r" % (v, local_flags.report())) if v in (None, "0", "1"): r = subprocess.run([sys.executable, "-I", "-B", "-c", FRESH % os.path.join(ROOT, "nx2")], capture_output=True, text=True, timeout=300) got, said = (r.stdout.strip().splitlines() or [""])[-1], "kit=%s env=%r" % (want, v) if r.returncode or got != said: bad.append("a fresh process after install with %r says %r, not %r (exit %d) %s" % (v, got, said, r.returncode, r.stderr.strip()[-300:])) for packed, local, stops in (("1", None, True), ("0", "1", True), ("1", "0", False), ("", None, False)): put("A64_PACKED_FLAGS", packed) put(SWITCH, local) try: local_flags.install() said = None except SystemExit as e: said = str(e) if stops != (said is not None) or (said and not ("A64_PACKED_FLAGS" in said and SWITCH + "=0" in said)): bad.append("install with A64_PACKED_FLAGS=%r and %s=%r: %s" % (packed, SWITCH, local, said or "no stop")) finally: for k, v in saved.items(): put(k, v) if bad: raise SystemExit("local flags: the rule: " + "; ".join(bad)) def lift(a64_lift, out_dir, value): """The kit's discovery and write() over the authored functions, with the switch at value (None: unset) and install() run""" import local_flags saved = os.environ.get(SWITCH) saved_hot = os.environ.get("A64_HOT_FUNCS") hot_list = os.path.join(os.path.dirname(out_dir), "hot_funcs.txt") with open(hot_list, "w") as f: f.write(HOT + "\n") os.environ["A64_HOT_FUNCS"] = hot_list try: if value is None: os.environ.pop(SWITCH, None) else: os.environ[SWITCH] = value local_flags.install() if a64_lift.local_flags() != local_flags.on(value): raise SystemExit("local flags: with %s=%r the kit reads %s" % (SWITCH, value, a64_lift.local_flags())) L = a64_lift.Lifter(Image()) L.discover() if sorted(L.funcs) != sorted(Image().entries): raise SystemExit("local flags: discovered %s" % sorted("%x" % e for e in L.funcs)) files = L.write(out_dir) finally: if saved is None: os.environ.pop(SWITCH, None) else: os.environ[SWITCH] = saved if saved_hot is None: os.environ.pop("A64_HOT_FUNCS", None) else: os.environ["A64_HOT_FUNCS"] = saved_hot text = "" for f in (files if isinstance(files, list) else sorted(os.listdir(out_dir))): p = f if os.path.isabs(f) else os.path.join(out_dir, f) if os.path.basename(p).startswith("code_") and p.endswith(".c"): with open(p, encoding="utf-8") as fh: text += fh.read() return text DRIVER = r""" #include "a64.h" #include #include #define F(x) void f_##x(Ctx *A64_NOESC c); void g_##x(Ctx *A64_NOESC c); F(80000000) F(80000100) F(80000140) F(80000180) F(800001c0) F(80000400) void hos_fpcr_follow(void) {} /* (the host's MXCSR following FPCR.FZ, and MSR FPCR's sync: the same for both lifts) */ void hos_fpcr_sync(Ctx *A64_NOESC c) { (void)c; } typedef void (*Fn)(Ctx *A64_NOESC); static const struct { const char *name; Fn now, old; } FN[] = { {"loop", f_80000000, g_80000000}, {"tail call", f_80000100, g_80000100}, {"entered with flags", f_80000140, g_80000140}, {"around a call", f_80000180, g_80000180}, {"32-bit and immediates", f_800001c0, g_800001c0}, {"float (hot, native)", f_80000400, g_80000400}}; static uint64_t rs = 1; static uint64_t rnd(void) { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; } static uint64_t rval(void) { /* small numbers, near the sign and wrap edges, and any */ static const uint64_t edge[] = {0, 1, 2, 3, 5, 10, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x100000000ull, 0x7FFFFFFFFFFFFFFFull, 0x8000000000000000ull, 0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFEull}; switch (rnd() % 4) { case 0: return edge[rnd() % (sizeof edge / sizeof edge[0])]; case 1: return rnd() % 16; case 2: return edge[rnd() % (sizeof edge / sizeof edge[0])] + (rnd() % 5) - 2; default: return rnd(); } } static uint64_t rfloat(void) { /* a float's bits: zeros, ones, infinities, NaNs, the normal and subnormal edges, and any */ static const uint32_t e[] = {0, 0x80000000u, 0x3f800000u, 0xbf800000u, 0x7f800000u, 0xff800000u, 0x7fc00000u, 0x7fa00000u, 0x00800000u, 0x00000001u, 0x807fffffu, 0x7f7fffffu, 0x4b000000u, 0xcf000000u}; switch (rnd() % 3) { case 0: return e[rnd() % (sizeof e / sizeof e[0])]; case 1: return 0x3f000000u + (uint32_t)(rnd() % 0x02000000u); default: return (uint32_t)rnd(); } } int main(int argc, char **argv) { const long n = atol(argv[1]); rs = strtoull(argv[2], NULL, 10) | 1; long bad = 0, checks = 0; for (long i = 0; i < n; i++) for (unsigned f = 0; f < sizeof FN / sizeof FN[0]; f++) { Ctx a, b; memset(&a, 0, sizeof a); for (int r = 0; r < 32; r++) a.x[r] = rval(); a.n = rnd() & 1, a.z = rnd() & 1, a.c = rnd() & 1, a.v = rnd() & 1; for (int r = 0; r < 8; r++) a.vreg[r][0] = rfloat() | (rnd() << 32), a.vreg[r][1] = rnd(); b = a; FN[f].now(&a); FN[f].old(&b); checks++; if (memcmp(a.x, b.x, sizeof a.x) || memcmp(a.vreg, b.vreg, sizeof a.vreg) || a.fpcr != b.fpcr || a.fpsr != b.fpsr) { if (bad++ < 10) { printf("mismatch: %s, state %ld:", FN[f].name, i); if (memcmp(a.vreg, b.vreg, sizeof a.vreg)) printf(" V registers differ"); if (a.fpcr != b.fpcr || a.fpsr != b.fpsr) printf(" FPCR/FPSR %llx/%llx (locals) %llx/%llx (context)", (unsigned long long)a.fpcr, (unsigned long long)a.fpsr, (unsigned long long)b.fpcr, (unsigned long long)b.fpsr); for (int r = 0; r < 32; r++) if (a.x[r] != b.x[r]) printf(" x%d %llx (locals) %llx (context)", r, (unsigned long long)a.x[r], (unsigned long long)b.x[r]); printf("\n"); } } } printf("total checks=%ld bad=%ld\n", checks, bad); return bad ? 1 : 0; } """ def import_lift_passes(): """Every pass nx2/lift.py installs, in its order (importing the module installs them), with v0.8.4's float options at their defaults (A64_NATIVE_FP, A64_FPX_EASY: nativefp reads them as it installs)""" saved = {k: os.environ.pop(k, None) for k in ("A64_NATIVE_FP", "A64_FPX_EASY", "A64_NATIVE_FP_COLD")} try: import importlib importlib.import_module("lift") # (nx2/lift.py: nx2 is on the path) finally: for k, v in saved.items(): if v is not None: os.environ[k] = v import nativefp if not (nativefp._installed and nativefp.native_fp()): raise SystemExit("local flags: importing nx2/lift.py did not install nativefp with A64_NATIVE_FP on") def function_text(text, name): """One lifted function's text, from its head to the next function's""" at = text.find("void %s(" % name) if at < 0: raise SystemExit("local flags: %s is not in the lift" % name) end = text.find("\nvoid f_", at + 1) return text[at:end if end > 0 else len(text)] # clang's record of a function's profile counters in LLVM IR: the hash of its name, then the hash of its control flow, by # which -fprofile-instr-use matches the function to a profile's entry (a static function's name after its file's) PROFD = re.compile(r"^@__profd_(?:\S*?\.c_)?([fg])_([0-9a-f]{8}) = [^\n]*?\} \{ i64 -?\d+, i64 (-?\d+),", re.M) def profile_hashes(cc, tmp): """Each lifted function's control-flow hash in the two lifts (code_now.c, code_old.c with g_ names), as clang computes it for -fprofile-instr-generate and -use: {address: [with the flags as locals, without]}""" got = {} for name, prefix in (("now", "f"), ("old", "g")): ll = os.path.join(tmp, "code_%s.ll" % name) fs.build([cc] + fs.target_flags(cc, tmp) + ["-march=x86-64-v3", "-O0", "-S", "-emit-llvm", "-fprofile-instr-generate", "-D_CRT_SECURE_NO_WARNINGS", "-Wno-everything", "-I" + os.path.join(fs.KIT, "rt"), "-I" + tmp, os.path.join(tmp, "code_%s.c" % name), "-o", ll], "the %s lift with profile counters" % name) with open(ll, encoding="utf-8", errors="replace") as f: ir = f.read() found = [m for m in PROFD.finditer(ir) if m.group(1) == prefix] if not found: sample = re.search(r"^@__profd_.*$", ir, re.M) raise SystemExit("local flags: no profile counters of the %s lift's functions in its LLVM IR (%s)" % (name, sample.group(0)[:200] if sample else "no __profd_ record")) for m in found: got.setdefault(m.group(2), [None, None])[name == "old"] = int(m.group(3)) return got def check_marks(a64_lift, tmp, fcmp, old_text): """(11-27) The page marks (a64_lift.group_marks, the lift's last step, nx2/chunks.py edit_c): two stores through one base with the float function's FCMP between them, as each lift wrote it, share one mark. The kit's MG_PLAIN knew a64_fcmp32 and a64_fcmp64 but not a64_fcmp32k and a64_fcmp64k, so with the flags as locals every scalar FCMP ended a group, and each store kept its own mark. With the switch off the grouped C is the same, byte for byte, as with MG_PLAIN before them""" def function(line): return ("void f_80000800(Ctx *__restrict A64_NOESC c) {\n recomp_store32(c,c->x[19] + 24,c->x[2]);\n" + line + "\n recomp_store32(c,c->x[19] + 28,c->x[3]);\n return;\n}\n") for name, (line,) in sorted(fcmp.items()): path = os.path.join(tmp, "marks_%s.c" % name) with open(path, "w", newline="\n") as f: f.write(function(line)) st = {} a64_lift.group_marks([path], st) if (st.get("groups"), st.get("grouped_stores")) != (1, 2): raise SystemExit("local flags: two stores through one base around the FCMP of the %s lift (%s) are grouped as %s: " "a64_lift.MG_PLAIN does not take its helpers" % (name, line.strip()[:60], dict(st))) now = a64_lift.MG_PLAIN before = re.compile(now.pattern.replace("fcmp32k?|fcmp64k?", "fcmp32|fcmp64")) if before.pattern == now.pattern: raise SystemExit("local flags: a64_lift.MG_PLAIN does not name a64_fcmp32k and a64_fcmp64k") text = old_text + function(fcmp["old"][0]) grouped = [] try: for plain in (now, before): a64_lift.MG_PLAIN = plain a64_lift._mg_plain.clear() grouped.append(a64_lift.mark_groups(text)) finally: a64_lift.MG_PLAIN = now a64_lift._mg_plain.clear() if grouped[0] != grouped[1] or grouped[0] == text: raise SystemExit("local flags: with %s=0 the grouped C differs from the C grouped with MG_PLAIN as it was" % SWITCH) def generate(cxx, tmp, flags): """The two lifts (code_now.c, code_old.c with g_ names), the kit's runtime C, in tmp. Returns the C files""" dll = os.path.join(tmp, "a64emit.dll" if os.name == "nt" else "liba64emit.so") fs.build([cxx, "-std=c++20", "-O0", "-shared", "-Wno-everything", "-o", dll, os.path.join(fs.KIT, "lift", "a64emit.cpp")] + flags + ([] if os.name == "nt" else ["-fPIC"]), "a64emit") import kit # noqa: F401 (a64-kit on the path) import build_emit build_emit.build = lambda force=False: dll # (not a64emit.dll beside the source) import a64_lift import a64_rtgen import a64emit import local_flags import oot_patches check_rule(local_flags, a64_lift) import_lift_passes() out = [] natives = {} fcmp = {} texts = {} try: a64_rtgen.write(tmp) for name, value in (("now", None), ("old", "0")): d = os.path.join(tmp, name) text = lift(a64_lift, d, value) hot = function_text(text, HOT) texts[name] = text natives[name] = [len(re.findall(rx, hot)) for _, rx in NATIVE] if ("a64_fcmp32k(" in hot) != (value is None) or ("a64_fcmp32(" in hot) != (value is not None): raise SystemExit("local flags: the float function's FCMP with %s=%r is not the %s form:\n%s" % (SWITCH, value, "code (a64_fcmp32k)" if value is None else "a64_fcmp32", hot)) if value is None and ("if (!_fk) " not in hot or "if (_fk) " in hot): raise SystemExit("local flags: the float function's FCMP is the kit's code form, not the hot profile's " "control flow (nx2/local_flags.py profile_form):\n%s" % hot) # (11-27) nx2/oot_patches.py's horse step test in this lift's form is the lift's own FCMP (its registers 3 and 1 in # place of the horse's 10 and 9): a PGO_FCMP written with other spaces would leave it out of the lift, and the # build only warns form = oot_patches.HORSE_TEST_LOCAL if value is None else oot_patches.HORSE_TEST want = form.split("\n", 1)[1].lstrip().replace("c->vreg[10]", "c->vreg[3]").replace("c->vreg[9]", "c->vreg[1]") if want not in hot: raise SystemExit("local flags: nx2/oot_patches.py's horse step test %r is not the lift's FCMP with %s=%r:\n%s" % (want, SWITCH, value, hot)) fcmp[name] = [ln for ln in hot.split("\n") if "a64_fcmp32" in ln] if len(fcmp[name]) != 1: raise SystemExit("local flags: the float function's FCMP is not one line:\n%s" % hot) if value is None: if "fz_" not in text or not re.search(r"c->n = fn_; c->z = fz_; c->c = fc_; c->v = fv_; TAILCALL\(", text): raise SystemExit("local flags: the default lift has no flag locals, or no write-back before its tail call") else: if re.search(r"\bf[nzcv]_\b", text): raise SystemExit("local flags: with %s=0 the lift still has flag locals" % SWITCH) text = re.sub(r"\bf_([0-9a-f]{8})\b", r"g_\1", text) path = os.path.join(tmp, "code_%s.c" % name) with open(path, "w", newline="\n") as f: f.write(text) out.append(path) if natives["now"] != natives["old"]: raise SystemExit("local flags: nativefp's names on the hot float function differ with the flags as locals: %s" % "; ".join("%s %d (locals) %d (context)" % (k, a, b) for (k, _), a, b in zip(NATIVE, natives["now"], natives["old"]) if a != b)) if not all(natives["now"][i] for i, (k, _) in enumerate(NATIVE) if k in ("scalar", "conversion", "FPCR sync")): raise SystemExit("local flags: nativefp left the hot float function without its native names (%s)" % ", ".join("%s %d" % (k, n) for (k, _), n in zip(NATIVE, natives["now"]))) check_marks(a64_lift, tmp, fcmp, texts["old"]) finally: if a64emit._lib is not None: # (unloaded, so the folder can go) import _ctypes (_ctypes.FreeLibrary if os.name == "nt" else _ctypes.dlclose)(a64emit._lib._handle) a64emit._lib = None for d in ("now", "old"): # (each lift's a64_fpx.h is the same header but for its FCMP helpers: the first one serves) if os.path.exists(os.path.join(tmp, d, "a64_fpx.h")) and not os.path.exists(os.path.join(tmp, "a64_fpx.h")): with open(os.path.join(tmp, d, "a64_fpx.h"), encoding="utf-8") as src, \ open(os.path.join(tmp, "a64_fpx.h"), "w", newline="\n") as dst: dst.write(src.read()) rt_c = [os.path.join(tmp, f) for f in sorted(os.listdir(tmp)) if f.startswith("a64_") and f.endswith(".c")] if len(rt_c) != 1: raise SystemExit("local flags: a64_rtgen wrote %s, not one C file" % rt_c) driver = os.path.join(tmp, "local_flags_test.c") with open(driver, "w", newline="\n") as f: f.write(DRIVER) return out + rt_c + [driver] def check_sources(): with open(os.path.join(ROOT, "nx2", "lift.py"), encoding="utf-8") as f: lift_py = f.read() at = [lift_py.find(p) for p in ("import local_flags", "vecfp.install()", "local_flags.install()", "def main():")] if min(at) < 0 or not at[1] < at[2] < at[3]: raise SystemExit("local flags: nx2/lift.py does not install nx2/local_flags.py at module level after vecfp's") nf = lift_py.find("\nnativefp.install()") if not at[2] < nf < at[3] or re.search(r"^\w+\.install\(\)", lift_py[nf + 1:at[3]].split("\n", 1)[1], re.M): raise SystemExit("local flags: nx2/lift.py does not install nativefp after local_flags, and last") with open(os.path.join(ROOT, "nx2", "make_game.py"), encoding="utf-8") as f: make_game = f.read() if 'if k.startswith(("A64_", "OOT_", "RX_"))' not in make_game or not SWITCH.startswith("A64_"): raise SystemExit("local flags: nx2/make_game.py's lift_key no longer takes the A64_ variables: %s is not in the key" % SWITCH) not_keyed = re.search(r"^LIFT_KEY_NOT = \((.*?)\) #", make_game, re.S | re.M) if not not_keyed or '"local_flags.py"' in not_keyed.group(1): raise SystemExit("local flags: nx2/local_flags.py must stay a file of the lift key") import oot_patches for old in (oot_patches.RGBA16F_OLD, oot_patches.RGBA16F_OLD_LOCAL): s = '#include "a64.h"\nvoid f_80672300(Ctx *c) {\n' + old + "\n}\n" got = oot_patches.patch_scene_format(s) if not got or "hos_scene_rgba16f() ? 0x2cULL : 0x1aULL" not in got or oot_patches.RGBA16F_DECL not in got: raise SystemExit("local flags: nx2/oot_patches.py's scene colour patch does not take %r" % old[-60:]) if "(!fz_)" not in oot_patches.RGBA16F_OLD_LOCAL or "c->z" in oot_patches.RGBA16F_OLD_LOCAL: raise SystemExit("local flags: the scene colour patch's local form does not read fz_") check_flag_edits(oot_patches) with open(os.path.join(ROOT, "docs", "development.md"), encoding="utf-8") as f: if "| `A64_LOCAL_FLAGS=0` |" not in f.read(): raise SystemExit("local flags: docs/development.md: A64_LOCAL_FLAGS is not in the switches table") def check_flag_edits(o): """(11-26, on v0.8.3) The edits that match a flag by its text, on authored functions as a lift with the flags as locals writes them (the flags' declaration after the head, the kit's localize_regs): each made once, and a second run changes nothing. (11-27, on v0.8.4) And the cloth's solve gate, whose place is counted in lines from the head: the declaration is no line of the job's own (counted, it left the gate out of the lift, and the cloth solved at every frame above 60 fps).""" if o.local_form("if (!c->n) { x = c->x[3]; c->vreg[2][0] = c->c; }") != "if (!fn_) { x = c->x[3]; c->vreg[2][0] = fc_; }": raise SystemExit("local flags: nx2/oot_patches.py local_form is not the kit's rule (only c->n, z, c and v)") with open(os.path.join(ROOT, "third_party", "a64-kit", "lift", "a64_lift.py"), encoding="utf-8") as f: kit = f.read() if 'fdecl = "\\n' + o.FLAG_DECL.rstrip("\n") + '"' not in kit: raise SystemExit("local flags: nx2/oot_patches.py FLAG_DECL is not the declaration the kit's localize_regs writes") if 'FLAG_REF = re.compile(r"%s")' % o.FLAG_REF.pattern not in kit: raise SystemExit("local flags: nx2/oot_patches.py FLAG_REF is not the kit's (a64_lift.FLAG_REF): local_form would " "write other text than localize_regs") d = o.FLAG_DECL # the cloth's solve job: its gate before the first store, which follows the head, the flags' declaration and a hint for name, pre, want in (("with the flags as locals", d, 1), ("with the flags in the context", "", 1), ("a store that is not the job's first line", d + " c->x[1] = 0;\n", 0)): cloth = ('#include "a64.h"\n' + o.CLOTH_SOLVE_HEAD + pre + " /* nop/hint */\n" + o.CLOTH_SOLVE_OLD + " c->x[0] = 1;\n return;\n}\n") got, n = o.patch_cloth_solve(cloth) made = n == 1 and got.count(o.CLOTH_SOLVE_NEW + o.CLOTH_SOLVE_OLD) == 1 and o.CLOTH_SOLVE_DECL in got if (want and not made) or (not want and (n or got != cloth)): raise SystemExit("local flags: the cloth's solve gate %s: %s, wanted %s" % (name, "made" if n else "left out", "made" if want else "left out")) if want and o.patch_cloth_solve(got) != (got, 1): raise SystemExit("local flags: the cloth's solve gate is not left as it is by a second run (%s)" % name) # the Movement speed tool's four places, one of which (f_80964bf0's) is the head and the line after it speed = '#include "a64.h"\n' for head in dict.fromkeys(h for h, _, _ in o.SPEED_PLACES): speed += head + d + "".join(a[len(h):] if a.startswith(h) else a for h, a, _ in o.SPEED_PLACES if h == head) speed += " return;\n}\n" got, n = o.patch_cct_speed(speed) if n != len(o.SPEED_PLACES) or got.count("hos_oot_cct_speed(c, c->x[0], ") != len(o.SPEED_PLACES): raise SystemExit("local flags: the Movement speed tool's places in a lift with the flags as locals: %d of %d" % (n, len(o.SPEED_PLACES))) if o.patch_cct_speed(got) != (got, len(o.SPEED_PLACES)): raise SystemExit("local flags: the Movement speed tool's calls are not left as they are by a second run (local form)") # the horse's jump state machine: the step test (the FCMP's code form) and its branch on fn_ if "c->n" in o.HORSE_BRANCH_LOCAL or "a64_fcmp32k(" not in o.HORSE_TEST_LOCAL or "a64_fcmp32(" in o.HORSE_TEST_LOCAL: raise SystemExit("local flags: the horse's jump test has no local form") for rest in ("fn_=(uint8_t)(_fk&1); fz_=(uint8_t)(_fk>>1&1); if (!_fk) { fn_ = 0; } }\n", # (nx2/local_flags.py's form) "if (_fk) { fn_=(uint8_t)(_fk&1); fz_=(uint8_t)(_fk>>1&1); } else { fn_ = 0; } }\n"): # (the kit's) horse = ('#include "a64.h"\n' + o.HORSE_HEAD + d + " c->x[0] = 0;\n" + o.HORSE_TEST_LOCAL + rest + o.HORSE_BRANCH_LOCAL + " c->x[0] = 1;\nL_82c5ae48:;\n}\n") got, n = o.patch_horse_jump(horse) if n != 1 or got.count(o.HORSE_SKIP + o.HORSE_BRANCH_LOCAL) != 1 or o.HORSE_DECL not in got: raise SystemExit("local flags: the horse's jump step patch does not take a lift with the flags as locals (%s)" % rest.strip()) if o.patch_horse_jump(got) != (got, 1): raise SystemExit("local flags: the horse's jump step patch is not left as it is by a second run (local form)") # the Camera centering row's anchor (fz_) cam = ('#include "a64.h"\n' + o.CAM_HEAD + d + "L_80645ad8:;\n c->x[8]=recomp_load32(c,c->x[19] + 516);\n" "if (fz_) { { A64_POLL(c); goto L_80645ad8; } }\ngoto L_806492c4;\n" + o.CAM_FOLLOW_ANCHOR_LOCAL + "c->x[30] = 0x80647218ULL; f_80649970(c);\n{ A64_POLL(c); goto L_80645ad8; }\nL_806492c4:;\n}\n") got, n = o.patch_camera_centering(cam) if n != 1 or got.count(o.CAM_FOLLOW_ANCHOR_LOCAL + o.CAM_FOLLOW_HOOK) != 1 or o.CAM_FOLLOW_DECL not in got: raise SystemExit("local flags: the Camera centering row's patch does not take a lift with the flags as locals") if o.patch_camera_centering(got) != (got, 1): raise SystemExit("local flags: the Camera centering row's patch is not left as it is by a second run (local form)") # the ocarina wait: the tick's mode gate (fz_) with its other gates and hooks if "c->z" in o.OC_TICK_GATES_LOCAL[0][0] or "(!fz_)" not in o.OC_TICK_GATES_LOCAL[0][0]: raise SystemExit("local flags: the ocarina wait's mode gate has no local form") oc = ('#include "a64.h"\n' + o.OC_ENTRY_HEAD + "\n" + o.OC_ENTRY_OLD + "\nA64_IJUMP(c, c->x[2]); return;\n}\n" + o.OC_TICK_HEAD + "\n" + d + o.OC_TICK_OLD + "\n" + o.OC_TICK_GATES_LOCAL[0][0] + "\n" + o.OC_TICK_GATES_LOCAL[1][0] + "\nL_828a92f8:; A64_POLL(c);\n" + o.OC_TICK_GATES_LOCAL[2][0] + "\nL_828a937c:; A64_POLL(c);\n" + o.OC_DONE_OLD + "\n" + o.OC_RESET_OLD + "\nL_828a92e4:; A64_POLL(c);\nreturn;\n}\n" + "void f_828a94e0(Ctx *__restrict A64_NOESC c) {\nreturn;\n}\n") got = o.patch_ocarina_wait(oc) news = [o.OC_ENTRY_NEW, o.OC_TICK_NEW, o.OC_DONE_NEW, o.OC_RESET_NEW] + [new for _, new in o.OC_TICK_GATES_LOCAL] if got is None or any(got.count(new) != 1 for new in news) or o.OC_DECL not in got: raise SystemExit("local flags: the ocarina wait's patch does not take a lift with the flags as locals") if o.patch_ocarina_wait(got) != got: raise SystemExit("local flags: the ocarina wait's patch is not left as it is by a second run (local form)") def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--cc") p.add_argument("--cxx") p.add_argument("--random", type=int, default=200000) a = p.parse_args() check_sources() if platform.machine().lower() not in ("x86_64", "amd64"): fs.skip("not an x86-64 host: %s" % platform.machine()) cc = fs.compiler(a.cc, "CC", ("clang", "gcc", "cc"), "clang") cxx = fs.compiler(a.cxx, "CXX", ("clang++", "g++", "c++"), "clang++") if not cc or not cxx: fs.skip("no C compiler" if not cc else "no C++ compiler") t0 = time.time() with tempfile.TemporaryDirectory(prefix="triforce-local-flags-") as tmp: sources = generate(cxx, tmp, fs.target_flags(cxx, tmp)) hashes = profile_hashes(cc, tmp) differ = sorted("f_%s" % a for a, pair in hashes.items() if None in pair or pair[0] != pair[1]) if len(hashes) < 6 or differ: raise SystemExit("FAIL: local flags: with the flags as locals clang hashes the control flow of %s differently " "(%d functions): the hot code built with the shipped profile would leave theirs out" % (", ".join(differ) or "none", len(hashes))) exe = os.path.join(tmp, "local_flags_test.exe") fs.build([cc] + fs.target_flags(cc, tmp) + ["-march=x86-64-v3"] + fs.FLAGS + ["-D_CRT_SECURE_NO_WARNINGS", "-Wno-everything", "-I" + os.path.join(fs.KIT, "rt"), "-I" + tmp] + sources + ["-o", exe], "the driver") r = fs.run([exe, str(a.random), str(SEED)], timeout=1200) print(r.stdout.rstrip()) total = re.search(r"total checks=(\d+) bad=(\d+)", r.stdout) if r.returncode or not total or total.group(2) != "0": raise SystemExit("FAIL: local flags: the lift with the flags as locals left other registers or float state (exit %d)" % r.returncode) print("PASS: six functions (one float, hot) lifted with %s on (the default) and off leave the same X0-X30, SP, V0-V7, FPCR and FPSR from %s states, " "and clang hashes the control flow of all %d alike (%.0f s)" % (SWITCH, total.group(1), len(hashes), time.time() - t0)) if __name__ == "__main__": main()