aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


client/runtime/recomp_types.h (55176B)


      1 /*
      2  * X-Wing Alliance Static Recompilation - Core Type Definitions
      3  *
      4  * Global register model, memory access macros, stack operations,
      5  * condition macros, and indirect call dispatch.
      6  *
      7  * All recompiled functions include this header.
      8  */
      9 
     10 #ifndef RECOMP_TYPES_H
     11 #define RECOMP_TYPES_H
     12 
     13 #include <stdint.h>
     14 #include <stddef.h>   /* ptrdiff_t (g_mem_base); MSVC pulls it in transitively, gcc/clang do not */
     15 #include <stdlib.h>
     16 #include <string.h>
     17 #include <stdio.h>
     18 #include <math.h>
     19 
     20 #ifdef _MSC_VER
     21 #include <intrin.h>
     22 #elif defined(__i386__) || defined(__x86_64__)
     23 #include <x86intrin.h>   /* __rdtsc, as <intrin.h> gives MSVC */
     24 #endif
     25 
     26 /* ============================================================
     27  * Global Register Model
     28  *
     29  * x86 registers are global variables. ebp is local per-function
     30  * since most VC6 code uses FPO (Frame Pointer Omission).
     31  * ============================================================ */
     32 
     33 /* Each portable host thread executes an independent guest CPU. */
     34 #ifdef RECOMP_PORTABLE
     35 #define RECOMP_THREAD_LOCAL _Thread_local
     36 #else
     37 #define RECOMP_THREAD_LOCAL
     38 #endif
     39 
     40 /* Volatile (caller-saved) registers */
     41 extern RECOMP_THREAD_LOCAL uint32_t g_eax, g_ecx, g_edx, g_esp;
     42 
     43 /* Callee-saved registers (also global for implicit parameter passing).
     44  * ebp is global too, not a per-function local: MSVC's __EH_prolog sets its
     45  * CALLER's frame pointer (lea ebp, [esp+0xC]) and returns, so a local ebp
     46  * would discard it and every C++ EH function would then address off zero.
     47  * Real x86 has one ebp; FPO functions that never touch it simply pass the
     48  * caller's through, which is exactly the behaviour we want. */
     49 extern RECOMP_THREAD_LOCAL uint32_t g_ebx, g_esi, g_edi, g_ebp;
     50 
     51 /* The x87 FPU stack is GLOBAL (8 shared registers), not per-function: helpers
     52  * like __ftol receive their argument on the FPU stack from the caller, and the
     53  * control word persists across calls. A per-function local stack would make every
     54  * cross-call FPU value read as 0. */
     55 extern RECOMP_THREAD_LOCAL double   g_st[8];
     56 extern RECOMP_THREAD_LOCAL int      g_fp_top;
     57 extern RECOMP_THREAD_LOCAL uint16_t g_fpu_cw;
     58 
     59 /* The arithmetic flags a function RETURNS with. The lazy flag state is local
     60  * to each lifted function, but assembly and the CRT return results in flags:
     61  * MSVC's sin/cos call a helper that returns ZF = "argument is Inf/NaN", and
     62  * the caller's `je` read its own stale flags instead -- every sin took the
     63  * NaN path (Gunman's view vectors, and with them the whole frame, went
     64  * black). So every `ret` publishes the state and every call picks it back up;
     65  * where the caller overwrites the flags first, the compiler drops the loads.
     66  * Defined here, weakly, so no project's runtime has to. */
     67 #if defined(_MSC_VER)
     68 #define RECOMP_WEAK __declspec(selectany)
     69 #else
     70 #define RECOMP_WEAK __attribute__((weak))
     71 #endif
     72 RECOMP_WEAK RECOMP_THREAD_LOCAL uint32_t g_flag_k, g_flag_a, g_flag_b, g_flag_cf;
     73 #define RECOMP_FLAGS_OUT() (g_flag_k = _flag_k, g_flag_a = _flag_a, g_flag_b = _flag_b, g_flag_cf = _cf)
     74 #define RECOMP_FLAGS_IN()  (_flag_k = g_flag_k, _flag_a = g_flag_a, _flag_b = g_flag_b, _cf = g_flag_cf)
     75 
     76 /* Segment registers (flat mode Win32 - effectively unused) */
     77 extern RECOMP_THREAD_LOCAL uint16_t g_seg_cs, g_seg_ds, g_seg_es, g_seg_fs, g_seg_gs, g_seg_ss;
     78 
     79 /* Function pointer type for recompiled functions */
     80 typedef void (*recomp_func_t)(void);
     81 
     82 /* Dispatch table entry */
     83 typedef struct {
     84     uint32_t address;
     85     recomp_func_t func;
     86 } recomp_dispatch_entry_t;
     87 
     88 /* Dispatch table (generated) */
     89 extern const recomp_dispatch_entry_t recomp_dispatch_table[];
     90 extern const uint32_t recomp_dispatch_count;
     91 
     92 /* ============================================================
     93  * Register Name Aliases (used in generated code)
     94  * ============================================================ */
     95 
     96 #if defined(RECOMP_GENERATED_CODE) && defined(RECOMP_LOCAL_REGS)
     97 /* RECOMP_LOCAL_REGS: each lifted function works on local copies of the eight
     98  * registers, loaded on entry and written back before every call, tail call
     99  * and return (and reloaded after calls, which may run native code, callbacks
    100  * or other lifted functions). Globals can alias any guest memory store, so
    101  * the optimiser had to reload them after every MEM32 write; locals whose
    102  * address is never taken stay in host registers. Opt-in: every exit from a
    103  * body must pass RECOMP_REGS_OUT, which generate.py arranges. */
    104 #define eax l_eax
    105 #define ecx l_ecx
    106 #define edx l_edx
    107 #define ebx l_ebx
    108 #define esp l_esp
    109 #define esi l_esi
    110 #define edi l_edi
    111 #define ebp l_ebp
    112 #define RECOMP_REGS_LOCALS uint32_t l_eax = g_eax, l_ecx = g_ecx, l_edx = g_edx, l_ebx = g_ebx, l_esp = g_esp, l_esi = g_esi, l_edi = g_edi, l_ebp = g_ebp;
    113 #define RECOMP_REGS_OUT() (g_eax = l_eax, g_ecx = l_ecx, g_edx = l_edx, g_ebx = l_ebx, g_esp = l_esp, g_esi = l_esi, g_edi = l_edi, g_ebp = l_ebp)
    114 #define RECOMP_REGS_IN() (l_eax = g_eax, l_ecx = g_ecx, l_edx = g_edx, l_ebx = g_ebx, l_esp = g_esp, l_esi = g_esi, l_edi = g_edi, l_ebp = g_ebp)
    115 #else
    116 #define RECOMP_REGS_LOCALS
    117 #define RECOMP_REGS_OUT() ((void)0)
    118 #define RECOMP_REGS_IN() ((void)0)
    119 #endif
    120 
    121 #if defined(RECOMP_GENERATED_CODE) && !defined(RECOMP_LOCAL_REGS)
    122 #define eax g_eax
    123 #define ecx g_ecx
    124 #define edx g_edx
    125 #define ebx g_ebx
    126 #define esp g_esp
    127 #define esi g_esi
    128 #define edi g_edi
    129 #define ebp g_ebp
    130 #endif
    131 #ifdef RECOMP_GENERATED_CODE
    132 /* x87 FPU stack is global; _fpu_cmp stays per-function (set+used within one fn) */
    133 #define _st g_st
    134 #define _fp_top g_fp_top
    135 #define _fpu_cw g_fpu_cw
    136 /* MMX file is global too. The lifter emits _mm[n] (see lift32.MMX_REGS), so the
    137  * alias has to exist alongside the others or every MMX body fails to compile. */
    138 #define _mm g_mm
    139 /* And the SSE file (lift32_sse.py emits _xmm[n]). */
    140 #define _xmm g_xmm
    141 #define _seg_cs g_seg_cs
    142 #define _seg_ds g_seg_ds
    143 #define _seg_es g_seg_es
    144 #define _seg_fs g_seg_fs
    145 #define _seg_gs g_seg_gs
    146 #define _seg_ss g_seg_ss
    147 #endif
    148 
    149 /* ============================================================
    150  * Sub-register Access
    151  * ============================================================ */
    152 
    153 #define LO8(r)       ((uint8_t)((r) & 0xFF))
    154 #define HI8(r)       ((uint8_t)(((r) >> 8) & 0xFF))
    155 #define LO16(r)      ((uint16_t)((r) & 0xFFFF))
    156 
    157 #define SET_LO8(r, v)   ((r) = ((r) & 0xFFFFFF00u) | ((uint32_t)(uint8_t)(v)))
    158 #define SET_HI8(r, v)   ((r) = ((r) & 0xFFFF00FFu) | (((uint32_t)(uint8_t)(v)) << 8))
    159 #define SET_LO16(r, v)  ((r) = ((r) & 0xFFFF0000u) | ((uint32_t)(uint16_t)(v)))
    160 
    161 /* ============================================================
    162  * Memory Access
    163  *
    164  * The original XWA binary uses a fixed image base of 0x00400000.
    165  * We map the original data sections at their original VAs using
    166  * VirtualAlloc/CreateFileMapping so that address-dependent code
    167  * works correctly.
    168  *
    169  * g_mem_base is the offset from original VA to actual mapped address.
    170  * For fixed-base mapping, this is 0.
    171  * ============================================================ */
    172 
    173 extern ptrdiff_t g_mem_base;
    174 
    175 #ifdef RECOMP_PORTABLE
    176 #include "guest_memory.h"
    177 #define ADDR(va)     guest_address((uint32_t)(va))
    178 #elif defined(RECOMP_FLAT_MEMORY)
    179 /* Guest VAs ARE host addresses (a 32-bit host mapping each module at its own
    180  * base): nothing to add, and no global to reload on every access. */
    181 #define ADDR(va)     ((uintptr_t)(uint32_t)(va))
    182 #else
    183 #define ADDR(va)     ((uintptr_t)(uint32_t)(va) + g_mem_base)
    184 #endif
    185 
    186 /* Thread-relative segment bases. In Win32, fs: points at the TIB/TEB; gs is
    187  * unused on x86. The lifter emits fs:/gs: accesses as FS_BASE/GS_BASE + addr,
    188  * so the runtime points g_fs_base at a simulated TIB (VA). cs/ds/es/ss are flat. */
    189 extern RECOMP_THREAD_LOCAL uint32_t g_fs_base;
    190 extern RECOMP_THREAD_LOCAL uint32_t g_gs_base;
    191 #define FS_BASE  g_fs_base
    192 #define GS_BASE  g_gs_base
    193 
    194 /* DOS-extender hooks: what Lifter(dos=True) emits for int, port I/O, cli/sti,
    195  * hlt and segment loads (tools/lift/lift32.py _lift_dos). A DOS host such as
    196  * runtime/dos32 defines them; nothing else references them. Under DOS/4GW es
    197  * is a real selector (the PSP, the environment), so es: overrides get a base. */
    198 extern RECOMP_THREAD_LOCAL uint32_t g_es_base;
    199 #define ES_BASE  g_es_base
    200 void     recomp_int(int n);
    201 uint8_t  recomp_in8(uint32_t port);
    202 uint16_t recomp_in16(uint32_t port);
    203 uint32_t recomp_in32(uint32_t port);
    204 void     recomp_out8(uint32_t port, uint8_t v);
    205 void     recomp_out16(uint32_t port, uint16_t v);
    206 void     recomp_out32(uint32_t port, uint32_t v);
    207 void     recomp_ins(uint32_t port, uint32_t va, int size, uint32_t count, int dir);
    208 void     recomp_outs(uint32_t port, uint32_t va, int size, uint32_t count, int dir);
    209 void     recomp_cli(void);
    210 void     recomp_sti(void);
    211 void     recomp_hlt(void);
    212 void     recomp_set_seg(int sreg, uint32_t selector);
    213 
    214 #define MEM8(addr)   (*(volatile uint8_t  *)ADDR(addr))
    215 #define MEM16(addr)  (*(volatile uint16_t *)ADDR(addr))
    216 #define MEM32(addr)  (*(volatile uint32_t *)ADDR(addr))
    217 #define MEM64(addr)  (*(volatile uint64_t *)ADDR(addr))
    218 #define MEMF(addr)   (*(volatile float    *)ADDR(addr))
    219 #define MEMD(addr)   (*(volatile double   *)ADDR(addr))
    220 
    221 /* Set 32-bit values in memory (for rep stosd) */
    222 static inline void MEMSET32(void* dst, uint32_t val, uint32_t count) {
    223     uint32_t* p = (uint32_t*)dst;
    224     for (uint32_t i = 0; i < count; i++) p[i] = val;
    225 }
    226 
    227 /* And 16-bit, for `rep stosw` -- which is how a run-length codec writes a run
    228  * of one colour, and so how most of a 1990s background image gets drawn. */
    229 static inline void MEMSET16(void* dst, uint16_t val, uint32_t count) {
    230     uint16_t* p = (uint16_t*)dst;
    231     for (uint32_t i = 0; i < count; i++) p[i] = val;
    232 }
    233 
    234 /* ============================================================
    235  * Stack Operations
    236  * ============================================================ */
    237 
    238 /* Evaluate the operand BEFORE moving esp. x86 reads the source of
    239  * push dword ptr [esp+N] at the OLD esp; decrementing first makes every
    240  * esp-relative push read one slot too low -- which lands on the return
    241  * address the caller pushed, so the callee sees RECOMP_RETADDR as an
    242  * argument. */
    243 #define PUSH32(sp, val) do { \
    244     uint32_t _pv = (uint32_t)(val); \
    245     (sp) -= 4; \
    246     MEM32(sp) = _pv; \
    247 } while(0)
    248 
    249 #define POP32_VAL(sp) ({ \
    250     uint32_t _v = MEM32(sp); \
    251     (sp) += 4; \
    252     _v; \
    253 })
    254 
    255 /* MSVC doesn't support statement expressions, so use a function */
    256 #ifdef _MSC_VER
    257 static inline uint32_t _pop32(uint32_t* sp) {
    258     uint32_t v = MEM32(*sp);
    259     *sp += 4;
    260     return v;
    261 }
    262 #undef POP32_VAL
    263 #define POP32_VAL(sp) _pop32(&(sp))
    264 #endif
    265 
    266 /* Two-arg pop: store the popped value into an lvalue destination (register or
    267  * MEM32(...)). The lifter emits this form for `pop r/m32`. Defined via POP32_VAL
    268  * so it picks up the GCC statement-expr / MSVC inline-function variant above. */
    269 #define POP32(sp, dest) do { (dest) = POP32_VAL(sp); } while(0)
    270 
    271 /*
    272  * The 16-bit forms. `push bp` / `pop bp` (66 55 / 66 5D) move esp by TWO, and
    273  * the pop writes only BP -- the top half of EBP is untouched.
    274  *
    275  * Lifting them as their 32-bit cousins looks harmless while a push and a pop
    276  * are paired, because the stack still balances. The register does not: a
    277  * 32-bit pop into ebp replaces the whole of it with the zero-extended word, so
    278  * `push bp ... pop bp ... leave` came back with ebp = 0x0000FD48 instead of
    279  * 0x022AFD48, handed that to esp, and the next stack read was at 64 KB. This
    280  * game's sprite code is full of 16-bit register traffic; that is where it bit.
    281  */
    282 #define PUSH16(sp, val) do { \
    283     uint16_t _pv = (uint16_t)(val); \
    284     (sp) -= 2; \
    285     MEM16(sp) = _pv; \
    286 } while(0)
    287 
    288 static inline uint16_t _pop16(uint32_t *sp) {
    289     uint16_t v = MEM16(*sp);
    290     *sp += 2;
    291     return v;
    292 }
    293 #define POP16_VAL(sp) _pop16(&(sp))
    294 
    295 #define PUSHAD() do { \
    296     uint32_t _tmp_esp = esp; \
    297     PUSH32(esp, eax); PUSH32(esp, ecx); PUSH32(esp, edx); PUSH32(esp, ebx); \
    298     PUSH32(esp, _tmp_esp); PUSH32(esp, ebp); PUSH32(esp, esi); PUSH32(esp, edi); \
    299 } while(0)
    300 
    301 #define POPAD() do { \
    302     edi = POP32_VAL(esp); esi = POP32_VAL(esp); ebp = POP32_VAL(esp); \
    303     esp += 4; /* skip saved ESP */ \
    304     ebx = POP32_VAL(esp); edx = POP32_VAL(esp); ecx = POP32_VAL(esp); eax = POP32_VAL(esp); \
    305 } while(0)
    306 
    307 /* ============================================================
    308  * Condition Macros
    309  *
    310  * Pattern-matched from flag-setter (cmp/test/sub/etc.) to
    311  * flag-consumer (jcc/setcc/cmovcc).
    312  * ============================================================ */
    313 
    314 /* Compare-based conditions (from cmp a, b) */
    315 #define CMP_EQ(a, b)   ((uint32_t)(a) == (uint32_t)(b))
    316 #define CMP_NE(a, b)   ((uint32_t)(a) != (uint32_t)(b))
    317 #define CMP_B(a, b)    ((uint32_t)(a) < (uint32_t)(b))      /* unsigned < */
    318 #define CMP_BE(a, b)   ((uint32_t)(a) <= (uint32_t)(b))     /* unsigned <= */
    319 #define CMP_A(a, b)    ((uint32_t)(a) > (uint32_t)(b))      /* unsigned > */
    320 #define CMP_AE(a, b)   ((uint32_t)(a) >= (uint32_t)(b))     /* unsigned >= */
    321 #define CMP_L(a, b)    ((int32_t)(a) < (int32_t)(b))        /* signed < */
    322 #define CMP_LE(a, b)   ((int32_t)(a) <= (int32_t)(b))       /* signed <= */
    323 #define CMP_G(a, b)    ((int32_t)(a) > (int32_t)(b))        /* signed > */
    324 #define CMP_GE(a, b)   ((int32_t)(a) >= (int32_t)(b))       /* signed >= */
    325 #define CMP_S(a, b)    ((int32_t)((uint32_t)(a) - (uint32_t)(b)) < 0)  /* sign flag */
    326 #define CMP_NS(a, b)   ((int32_t)((uint32_t)(a) - (uint32_t)(b)) >= 0)
    327 #define CMP_O(a, b)    0  /* TODO: overflow detection */
    328 #define CMP_NO(a, b)   1
    329 #define CMP_P(a, b)    0  /* TODO: parity */
    330 #define CMP_NP(a, b)   1
    331 
    332 /* Test-based conditions (from test a, b) */
    333 #define TEST_Z(a, b)   (((uint32_t)(a) & (uint32_t)(b)) == 0)
    334 #define TEST_NZ(a, b)  (((uint32_t)(a) & (uint32_t)(b)) != 0)
    335 #define TEST_S(a, b)   ((int32_t)((uint32_t)(a) & (uint32_t)(b)) < 0)
    336 #define TEST_NS(a, b)  ((int32_t)((uint32_t)(a) & (uint32_t)(b)) >= 0)
    337 #define TEST_G(a, b)   ((int32_t)((uint32_t)(a) & (uint32_t)(b)) > 0)
    338 #define TEST_LE(a, b)  ((int32_t)((uint32_t)(a) & (uint32_t)(b)) <= 0)
    339 
    340 /* Bit test (from bt) */
    341 #define BT_CF(base, bit) (((uint32_t)(base) >> ((uint32_t)(bit) & 31)) & 1)
    342 
    343 /*
    344  * Runtime flag kind.
    345  *
    346  * A jcc is normally paired with its flag-setter at lift time, but the setter
    347  * is not always statically known: MSVC routinely branches into a block whose
    348  * predecessors set the flags with different instructions (the signed-modulo
    349  * idiom `and/jns/dec/or/inc/je` is one join, 64-bit compares another). The
    350  * lifter used to fall back to a stale _cf at those sites, which made the
    351  * branch read whatever carry happened to be lying around.
    352  *
    353  * _flag_a/_flag_b already survive across blocks -- they are plain function
    354  * locals -- so recording which *kind* of instruction wrote them is enough to
    355  * evaluate any condition exactly, wherever the branch turns up.
    356  */
    357 enum {
    358     FK_NONE = 0,
    359     FK_CMP,     /* cmp, sub       -- a - b            */
    360     FK_ADD,     /* add            -- a + b            */
    361     FK_TEST,    /* and/or/xor/test/shift -- a & b     */
    362     FK_BT,      /* bt             -- CF = bit b of a  */
    363     FK_FCOM,    /* fcom           -- a is -1/0/1, 2 = unordered */
    364     /* INC and DEC are ADD and SUB that do NOT write CF. No condition can tell
    365      * them apart (a jcc reading CF after an inc is reading a flag the
    366      * instruction never wrote), but PUSHFD can: it has to report the carry
    367      * that was already there rather than the one the addition would have
    368      * produced. */
    369     FK_INC,     /* inc            -- a + b, CF preserved */
    370     FK_DEC,     /* dec            -- a - b, CF preserved */
    371     /* The flags as a literal word, from POPFD. Nothing is derived: every flag
    372      * is read from its own bit. The lazy triple cannot express an arbitrary
    373      * combination of flags, and a program that restores a saved EFLAGS is
    374      * asking for exactly that. */
    375     FK_EFLAGS
    376 };
    377 
    378 /* A NARROW setter's kind carries its left-align shift (24 for 8-bit, 16 for
    379  * 16-bit) in bits 8 and up. CF, ZF, SF and OF come out of the left-aligned
    380  * operands at 32 bits unchanged (lift32's _flag_capture); PF and AF are read
    381  * off the result's LOW byte, and only the shift says where that byte is. The
    382  * lifter knows the width statically, but a jcc at a join point reads the kind
    383  * at runtime, and there `fnstsw ax; test ah, 5; jp` -- MSVC's `x < 0.0` --
    384  * needs the parity of AH. Every reader masks the kind with FK_KIND. */
    385 #define FK_NARROW(k, shift) ((uint32_t)(k) | ((uint32_t)(shift) << 8))
    386 #define FK_KIND(k)          ((k) & 0xFFu)
    387 #define FK_SHIFT(k)         ((k) >> 8)
    388 
    389 enum {
    390     CC_E = 0, CC_NE, CC_S, CC_NS, CC_G, CC_GE, CC_L, CC_LE,
    391     CC_A, CC_AE, CC_B, CC_BE, CC_O, CC_NO, CC_P, CC_NP
    392 };
    393 
    394 static inline uint32_t recomp_parity8(uint8_t v);
    395 
    396 static inline int recomp_cond(uint32_t kind, uint32_t a, uint32_t b, int cc) {
    397     uint32_t r, sh = FK_SHIFT(kind);
    398     int zf, sf, cf, of, pf;
    399 
    400     kind = FK_KIND(kind);
    401     if (kind == FK_EFLAGS) {
    402         cf = (int)(a & 1u);
    403         pf = (int)((a >> 2) & 1u);
    404         zf = (int)((a >> 6) & 1u);
    405         sf = (int)((a >> 7) & 1u);
    406         of = (int)((a >> 11) & 1u);
    407         goto decide;
    408     }
    409 
    410     if (kind == FK_FCOM) {
    411         int32_t v = (int32_t)a;          /* -1 less, 0 equal, 1 greater, 2 unordered */
    412         if (v == 2) {                    /* NaN: ZF = PF = CF = 1, as fcomi/sahf leave them */
    413             switch (cc) {
    414             case CC_E: case CC_B: case CC_BE: case CC_P: return 1;
    415             default:                                     return 0;
    416             }
    417         }
    418         switch (cc) {
    419         case CC_NP:               return 1;
    420         case CC_E:                return v == 0;
    421         case CC_NE:               return v != 0;
    422         case CC_B:  case CC_L:    return v <  0;
    423         case CC_BE: case CC_LE:   return v <= 0;
    424         case CC_A:  case CC_G:    return v >  0;
    425         case CC_AE: case CC_GE:   return v >= 0;
    426         default:                  return 0;
    427         }
    428     }
    429 
    430     switch (kind) {
    431     case FK_ADD:
    432     case FK_INC:                          /* CF here is the ADD's; after INC the
    433                                              real CF is the preserved one --
    434                                              see recomp_cond_cf */
    435         r  = a + b;
    436         cf = (r < a);
    437         of = (int)((~(a ^ b) & (a ^ r)) >> 31);
    438         break;
    439     case FK_TEST:
    440         r  = a & b;
    441         cf = 0;
    442         of = 0;
    443         break;
    444     case FK_BT:
    445         r  = 0;
    446         cf = (int)((a >> (b & 31)) & 1u);
    447         of = 0;
    448         break;
    449     default:                              /* FK_CMP, FK_DEC and FK_NONE */
    450         r  = a - b;
    451         cf = (a < b);
    452         of = (int)(((a ^ b) & (a ^ r)) >> 31);
    453         break;
    454     }
    455     zf = (r == 0);
    456     sf = (int)(r >> 31);
    457     pf = (int)recomp_parity8((uint8_t)(r >> sh));
    458 
    459 decide:
    460     switch (cc) {
    461     case CC_E:   return zf;
    462     case CC_NE:  return !zf;
    463     case CC_S:   return sf;
    464     case CC_NS:  return !sf;
    465     case CC_G:   return !zf && (sf == of);
    466     case CC_GE:  return sf == of;
    467     case CC_L:   return sf != of;
    468     case CC_LE:  return zf || (sf != of);
    469     case CC_A:   return !cf && !zf;
    470     case CC_AE:  return !cf;
    471     case CC_B:   return cf;
    472     case CC_BE:  return cf || zf;
    473     case CC_O:   return of;
    474     case CC_NO:  return !of;
    475     case CC_P:   return pf;
    476     case CC_NP:  return !pf;
    477     }
    478     return 0;
    479 }
    480 
    481 /* recomp_cond, with the carry that inc/dec PRESERVE. `cmp; inc; jae` reads
    482  * the cmp's CF, which the lifted code still has in _cf; deriving it from the
    483  * inc's operands is wrong (it corrupted MSVC 6's small-block heap). */
    484 /* x87 compare outcome: -1 less, 0 equal, 1 greater, 2 unordered (a NaN). */
    485 #define FPU_CMP(x, y) ((x) < (y) ? -1 : (x) > (y) ? 1 : (x) == (y) ? 0 : 2)
    486 
    487 static inline int recomp_cond_cf(uint32_t kind, uint32_t a, uint32_t b, int cc,
    488                                  uint32_t cf) {
    489     if ((FK_KIND(kind) == FK_INC || FK_KIND(kind) == FK_DEC) &&
    490         (cc == CC_B || cc == CC_AE || cc == CC_A || cc == CC_BE)) {
    491         int zf = recomp_cond(kind, a, b, CC_E);
    492         switch (cc) {
    493         case CC_B:  return cf != 0;
    494         case CC_AE: return cf == 0;
    495         case CC_A:  return cf == 0 && !zf;
    496         default:    return cf != 0 || zf;
    497         }
    498     }
    499     return recomp_cond(kind, a, b, cc);
    500 }
    501 
    502 /* CF as adc/sbb read it: derived from an add/sub/cmp's operands (which do
    503  * not write `_cf`), otherwise the `_cf` the instruction kept (adc, sbb, shifts,
    504  * logic ops, inc/dec, popfd/sahf). The lifter's precise_carry option. */
    505 static inline uint32_t recomp_carry(uint32_t kind, uint32_t a, uint32_t b, uint32_t cf) {
    506     switch (FK_KIND(kind)) {
    507     case FK_ADD: return a + b < a;
    508     case FK_CMP: return a < b;
    509     default:     return cf;
    510     }
    511 }
    512 
    513 /* Bit 1 reads as 1 on every x86, and IF is set in any process this runtime
    514  * will ever host. A PUSHFD that omitted them differs from hardware in a way
    515  * guest CPU-detection code notices. */
    516 #define RECOMP_EFLAGS_FIXED 0x00000202u
    517 
    518 static inline uint32_t recomp_parity8(uint8_t v) {
    519     v ^= (uint8_t)(v >> 4);
    520     v ^= (uint8_t)(v >> 2);
    521     v ^= (uint8_t)(v >> 1);
    522     return (uint32_t)((~v) & 1u);
    523 }
    524 
    525 /* PF of a lazily captured result: parity of its low byte. `shift` undoes the
    526  * left-alignment _flag_capture gives narrow operands (24 for 8-bit). */
    527 #define RECOMP_PF(r, shift) ((int)recomp_parity8((uint8_t)((uint32_t)(r) >> (shift))))
    528 
    529 /* The six arithmetic flags as a word, given a result and the three that do
    530  * not come from it. */
    531 static inline uint32_t recomp_flags_pack(uint32_t r, uint32_t cf, uint32_t af,
    532                                          uint32_t of) {
    533     uint32_t e = RECOMP_EFLAGS_FIXED | (cf & 1u) | ((af & 1u) << 4) | ((of & 1u) << 11);
    534     if (r == 0) e |= 0x40u;               /* ZF */
    535     e |= (r >> 31) << 7;                  /* SF */
    536     e |= recomp_parity8((uint8_t)r) << 2; /* PF */
    537     return e;
    538 }
    539 
    540 /*
    541  * The flags as one word: PUSHFD, and the flag oracle the differential harness
    542  * compares against.
    543  *
    544  * The lazy tuple already holds everything the six arithmetic flags derive
    545  * from, so this is that derivation done all at once instead of one flag at a
    546  * time. CF is the exception: the tuple carries it for ADD/SUB/CMP, while
    547  * shifts, rotates, NEG, STC/CLC/CMC and ADC/SBB maintain the running `_cf` --
    548  * so every other kind takes the carry it is handed.
    549  *
    550  * AF exists here and nowhere else in the 32-bit model. It costs nothing --
    551  * (a ^ b ^ r) bit 4 comes out of operands the tuple already stored -- and
    552  * PUSHFD round-trips it, so code that saves and restores flags around a call
    553  * does not silently drop a flag it never mentions. Hardware leaves AF
    554  * undefined after a logic op; this reports 0 there, deterministically.
    555  */
    556 static inline uint32_t recomp_eflags(uint32_t kind, uint32_t a, uint32_t b,
    557                                      uint32_t cf_in, int df) {
    558     uint32_t r, e, sh = FK_SHIFT(kind);
    559     uint32_t cf = cf_in & 1u, of = 0, af = 0;
    560 
    561     kind = FK_KIND(kind);
    562 
    563     if (kind == FK_EFLAGS) {
    564         /* Already a word. DF still comes from `_df`: a CLD after the POPFD
    565            moved it and the saved word did not follow.
    566 
    567            AC (18) and ID (21) ride along because a POPFD/PUSHFD pair is how
    568            every 1990s binary asks the CPU a yes/no question about itself: write
    569            the bit, read it back, see whether it stuck. ID is the CPUID probe --
    570            drop it here and the readback matches the original word, the program
    571            concludes there is no CPUID, and a game that needs MMX puts up "This
    572            CPU does not have an MMX unit" and quits. They are the only two bits
    573            user mode can actually toggle, so carrying them costs one mask. */
    574         e = (a & (1u | 4u | 0x10u | 0x40u | 0x80u | 0x800u
    575                   | 0x40000u | 0x200000u)) | RECOMP_EFLAGS_FIXED;
    576         return (df < 0) ? (e | 0x400u) : e;
    577     }
    578 
    579     switch (kind) {
    580     case FK_ADD: case FK_INC:
    581         r  = a + b;
    582         if (kind == FK_ADD) cf = (r < a);
    583         of = (~(a ^ b) & (a ^ r)) >> 31;
    584         af = ((a ^ b ^ r) >> (sh + 4)) & 1u;
    585         break;
    586     case FK_TEST:
    587         /* and/or/xor/test clear CF (the lifter stores that); a shift leaves
    588            the bit it shifted out in `_cf`. Either way the carry is `cf_in`. */
    589         r  = a & b;
    590         break;
    591     case FK_BT:
    592         r  = 0;
    593         cf = (a >> (b & 31)) & 1u;
    594         break;
    595     case FK_NONE: case FK_FCOM:
    596         /* Nothing has written the arithmetic flags (or fcom wrote a comparison
    597            this word cannot express). Report the carry we hold and leave the
    598            rest clear: deriving ZF and PF from an invented zero result would
    599            report two flags as set that no instruction ever set. */
    600         e = RECOMP_EFLAGS_FIXED | cf;
    601         return (df < 0) ? (e | 0x400u) : e;
    602     default:                              /* FK_CMP, FK_DEC */
    603         r  = a - b;
    604         if (kind == FK_CMP) cf = (a < b);
    605         of = ((a ^ b) & (a ^ r)) >> 31;
    606         af = ((a ^ b ^ r) >> (sh + 4)) & 1u;
    607         break;
    608     }
    609 
    610     e = recomp_flags_pack(r, cf, af, of);
    611     if (sh)                               /* narrow: PF of the low byte, at bit sh */
    612         e = (e & ~4u) | (recomp_parity8((uint8_t)(r >> sh)) << 2);
    613     if (df < 0) e |= 0x400u;              /* DF */
    614     return e;
    615 }
    616 
    617 /*
    618  * ADC and SBB take the carry as a THIRD input, and the lazy triple cannot hold
    619  * one: folding it into the source (`a + (b + c)`) loses it whenever b is all
    620  * ones, and modelling `a - b - c` as a SUB of `b + c` gets the borrow wrong
    621  * whenever a != b. So they compute their flags at the instruction and hand
    622  * back the finished word, which the caller stores as FK_EFLAGS -- the same
    623  * escape hatch POPFD uses.
    624  */
    625 static inline uint32_t recomp_flags_adc(uint32_t a, uint32_t b, uint32_t c) {
    626     uint32_t r = a + b + c;
    627     return recomp_flags_pack(r,
    628                              c ? (r <= a) : (r < a),
    629                              ((a ^ b ^ r) >> 4) & 1u,
    630                              (~(a ^ b) & (a ^ r)) >> 31);
    631 }
    632 
    633 static inline uint32_t recomp_flags_sbb(uint32_t a, uint32_t b, uint32_t c) {
    634     uint32_t r = a - b - c;
    635     return recomp_flags_pack(r,
    636                              c ? (a <= b) : (a < b),
    637                              ((a ^ b ^ r) >> 4) & 1u,
    638                              ((a ^ b) & (a ^ r)) >> 31);
    639 }
    640 
    641 /*
    642  * A rotate writes CF and leaves ZF, SF and OF alone.
    643  *
    644  * The lazy flag triple cannot say that: it holds one instruction's operands, so
    645  * publishing the rotate's carry through it would have to throw away the compare
    646  * that set ZF, and NOT publishing it leaves a following `jae`/`jb` reading the
    647  * carry of whatever came before. The RLE sprite decoder in Gizmos & Gadgets
    648  * does exactly this -- `sub bx,cx; rcr cl,1; rep movsw; jae` -- where the jae
    649  * is asking whether the count was odd, and answering it with the sub's borrow
    650  * ran the decoder off the end of both the sprite and the framebuffer.
    651  *
    652  * So a rotate freezes the flags into a word, the same escape hatch ADC and
    653  * POPFD use, and overwrites just the carry.
    654  *
    655  * OF is carried over rather than recomputed: x86 only defines it for a rotate
    656  * of exactly 1, and no compiler emits a branch on it.
    657  */
    658 static inline uint32_t recomp_eflags_setcf(uint32_t kind, uint32_t a, uint32_t b,
    659                                            uint32_t cf, int df) {
    660     return (recomp_eflags(kind, a, b, cf, df) & ~1u) | (cf & 1u);
    661 }
    662 
    663 /* ============================================================
    664  * Bit Manipulation
    665  * ============================================================ */
    666 
    667 #define ROL32(val, n) (((uint32_t)(val) << ((n) & 31)) | ((uint32_t)(val) >> (32 - ((n) & 31))))
    668 #define ROR32(val, n) (((uint32_t)(val) >> ((n) & 31)) | ((uint32_t)(val) << (32 - ((n) & 31))))
    669 #define BSWAP32(val)  ( (((val) & 0xFF) << 24) | (((val) & 0xFF00) << 8) | \
    670                         (((val) >> 8) & 0xFF00) | (((val) >> 24) & 0xFF) )
    671 
    672 /* ============================================================
    673  * MMX
    674  *
    675  * Eight 64-bit registers holding packed bytes/words/dwords. On real hardware
    676  * they alias the x87 stack, which is why MMX code must `emms` before touching
    677  * the FPU again; we keep the two apart, so `emms` is a no-op here and code that
    678  * deliberately interleaved them would behave differently. POD does not: it is
    679  * the MMX build, and its rasterizer is a well-formed MMX block per span.
    680  *
    681  * Global, like the rest of the register file here; a multi-threaded target
    682  * wants them thread-local instead.
    683  * ============================================================ */
    684 
    685 extern RECOMP_THREAD_LOCAL uint64_t g_mm[8];
    686 
    687 #define MM_W(v, i)  ((int16_t)((uint64_t)(v) >> ((i) * 16)))
    688 #define MM_D(v, i)  ((int32_t)((uint64_t)(v) >> ((i) * 32)))
    689 #define MM_PUT_W(i, x) ((uint64_t)(uint16_t)(x) << ((i) * 16))
    690 #define MM_PUT_D(i, x) ((uint64_t)(uint32_t)(x) << ((i) * 32))
    691 
    692 static inline int16_t mmx_sat16(int32_t v) {
    693     return (int16_t)(v > 32767 ? 32767 : v < -32768 ? -32768 : v);
    694 }
    695 
    696 static inline uint64_t mmx_paddw(uint64_t a, uint64_t b) {
    697     uint64_t r = 0;
    698     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, MM_W(a, i) + MM_W(b, i));
    699     return r;
    700 }
    701 static inline uint64_t mmx_psubw(uint64_t a, uint64_t b) {
    702     uint64_t r = 0;
    703     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, MM_W(a, i) - MM_W(b, i));
    704     return r;
    705 }
    706 static inline uint64_t mmx_paddd(uint64_t a, uint64_t b) {
    707     return MM_PUT_D(0, MM_D(a, 0) + MM_D(b, 0)) | MM_PUT_D(1, MM_D(a, 1) + MM_D(b, 1));
    708 }
    709 static inline uint64_t mmx_psubd(uint64_t a, uint64_t b) {
    710     return MM_PUT_D(0, MM_D(a, 0) - MM_D(b, 0)) | MM_PUT_D(1, MM_D(a, 1) - MM_D(b, 1));
    711 }
    712 static inline uint64_t mmx_paddsw(uint64_t a, uint64_t b) {
    713     uint64_t r = 0;
    714     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, mmx_sat16(MM_W(a, i) + MM_W(b, i)));
    715     return r;
    716 }
    717 static inline uint64_t mmx_psubsw(uint64_t a, uint64_t b) {
    718     uint64_t r = 0;
    719     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, mmx_sat16(MM_W(a, i) - MM_W(b, i)));
    720     return r;
    721 }
    722 /* High half of each signed 16x16 product -- the fixed-point multiply an MMX
    723  * rasterizer scales colour and texture coordinates with. */
    724 static inline uint64_t mmx_pmulhw(uint64_t a, uint64_t b) {
    725     uint64_t r = 0;
    726     for (int i = 0; i < 4; i++)
    727         r |= MM_PUT_W(i, (int16_t)(((int32_t)MM_W(a, i) * MM_W(b, i)) >> 16));
    728     return r;
    729 }
    730 static inline uint64_t mmx_pmullw(uint64_t a, uint64_t b) {
    731     uint64_t r = 0;
    732     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, (int16_t)((int32_t)MM_W(a, i) * MM_W(b, i)));
    733     return r;
    734 }
    735 /* Two dwords, each the sum of a neighbouring pair of 16x16 products. */
    736 static inline uint64_t mmx_pmaddwd(uint64_t a, uint64_t b) {
    737     uint64_t r = 0;
    738     for (int i = 0; i < 2; i++)
    739         r |= MM_PUT_D(i, (int32_t)MM_W(a, i*2) * MM_W(b, i*2)
    740                        + (int32_t)MM_W(a, i*2+1) * MM_W(b, i*2+1));
    741     return r;
    742 }
    743 /* Interleave: the low (or high) halves of a and b, a's element first. */
    744 static inline uint64_t mmx_punpcklwd(uint64_t a, uint64_t b) {
    745     return MM_PUT_W(0, MM_W(a,0)) | MM_PUT_W(1, MM_W(b,0))
    746          | MM_PUT_W(2, MM_W(a,1)) | MM_PUT_W(3, MM_W(b,1));
    747 }
    748 static inline uint64_t mmx_punpckhwd(uint64_t a, uint64_t b) {
    749     return MM_PUT_W(0, MM_W(a,2)) | MM_PUT_W(1, MM_W(b,2))
    750          | MM_PUT_W(2, MM_W(a,3)) | MM_PUT_W(3, MM_W(b,3));
    751 }
    752 static inline uint64_t mmx_punpcklbw(uint64_t a, uint64_t b) {
    753     uint64_t r = 0;
    754     for (int i = 0; i < 4; i++) {
    755         r |= (uint64_t)(uint8_t)(a >> (i*8)) << (i*16);
    756         r |= (uint64_t)(uint8_t)(b >> (i*8)) << (i*16 + 8);
    757     }
    758     return r;
    759 }
    760 static inline uint64_t mmx_punpckhbw(uint64_t a, uint64_t b) {
    761     uint64_t r = 0;
    762     for (int i = 0; i < 4; i++) {
    763         r |= (uint64_t)(uint8_t)(a >> (32 + i*8)) << (i*16);
    764         r |= (uint64_t)(uint8_t)(b >> (32 + i*8)) << (i*16 + 8);
    765     }
    766     return r;
    767 }
    768 static inline uint64_t mmx_punpckldq(uint64_t a, uint64_t b) {
    769     return (uint64_t)(uint32_t)a | ((uint64_t)(uint32_t)b << 32);
    770 }
    771 static inline uint64_t mmx_punpckhdq(uint64_t a, uint64_t b) {
    772     return (uint64_t)(uint32_t)(a >> 32) | ((uint64_t)(uint32_t)(b >> 32) << 32);
    773 }
    774 /* Shifts. A count wider than the element is not a wrapped shift on x86: the
    775  * logical forms produce zero and the arithmetic ones produce the sign. */
    776 static inline uint64_t mmx_psllq(uint64_t a, uint32_t c) { return c > 63 ? 0 : a << c; }
    777 static inline uint64_t mmx_psrlq(uint64_t a, uint32_t c) { return c > 63 ? 0 : a >> c; }
    778 static inline uint64_t mmx_psllw(uint64_t a, uint32_t c) {
    779     uint64_t r = 0;
    780     if (c > 15) return 0;
    781     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, (uint16_t)MM_W(a, i) << c);
    782     return r;
    783 }
    784 static inline uint64_t mmx_psrlw(uint64_t a, uint32_t c) {
    785     uint64_t r = 0;
    786     if (c > 15) return 0;
    787     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, (uint16_t)MM_W(a, i) >> c);
    788     return r;
    789 }
    790 static inline uint64_t mmx_psraw(uint64_t a, uint32_t c) {
    791     uint64_t r = 0;
    792     if (c > 15) c = 15;
    793     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, (int16_t)(MM_W(a, i) >> c));
    794     return r;
    795 }
    796 static inline uint64_t mmx_pslld(uint64_t a, uint32_t c) {
    797     if (c > 31) return 0;
    798     return MM_PUT_D(0, (uint32_t)MM_D(a,0) << c) | MM_PUT_D(1, (uint32_t)MM_D(a,1) << c);
    799 }
    800 static inline uint64_t mmx_psrld(uint64_t a, uint32_t c) {
    801     if (c > 31) return 0;
    802     return MM_PUT_D(0, (uint32_t)MM_D(a,0) >> c) | MM_PUT_D(1, (uint32_t)MM_D(a,1) >> c);
    803 }
    804 static inline uint64_t mmx_psrad(uint64_t a, uint32_t c) {
    805     if (c > 31) c = 31;
    806     return MM_PUT_D(0, MM_D(a,0) >> c) | MM_PUT_D(1, MM_D(a,1) >> c);
    807 }
    808 /* Pack with saturation, a's elements low. */
    809 static inline uint64_t mmx_packssdw(uint64_t a, uint64_t b) {
    810     return MM_PUT_W(0, mmx_sat16(MM_D(a,0))) | MM_PUT_W(1, mmx_sat16(MM_D(a,1)))
    811          | MM_PUT_W(2, mmx_sat16(MM_D(b,0))) | MM_PUT_W(3, mmx_sat16(MM_D(b,1)));
    812 }
    813 static inline uint64_t mmx_packuswb(uint64_t a, uint64_t b) {
    814     uint64_t r = 0;
    815     for (int i = 0; i < 4; i++) {
    816         int16_t v = MM_W(a, i); uint8_t p = (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v);
    817         r |= (uint64_t)p << (i * 8);
    818         v = MM_W(b, i);         p = (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v);
    819         r |= (uint64_t)p << (32 + i * 8);
    820     }
    821     return r;
    822 }
    823 static inline uint64_t mmx_pcmpeqw(uint64_t a, uint64_t b) {
    824     uint64_t r = 0;
    825     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, MM_W(a,i) == MM_W(b,i) ? 0xFFFF : 0);
    826     return r;
    827 }
    828 static inline uint64_t mmx_pcmpgtw(uint64_t a, uint64_t b) {
    829     uint64_t r = 0;
    830     for (int i = 0; i < 4; i++) r |= MM_PUT_W(i, MM_W(a,i) > MM_W(b,i) ? 0xFFFF : 0);
    831     return r;
    832 }
    833 static inline uint64_t mmx_pcmpeqd(uint64_t a, uint64_t b) {
    834     return MM_PUT_D(0, MM_D(a,0) == MM_D(b,0) ? -1 : 0) | MM_PUT_D(1, MM_D(a,1) == MM_D(b,1) ? -1 : 0);
    835 }
    836 static inline uint64_t mmx_pcmpgtd(uint64_t a, uint64_t b) {
    837     return MM_PUT_D(0, MM_D(a,0) > MM_D(b,0) ? -1 : 0) | MM_PUT_D(1, MM_D(a,1) > MM_D(b,1) ? -1 : 0);
    838 }
    839 
    840 /* Bytes, and the unsigned-saturating forms. A software renderer's translucency
    841  * is one paddusb per pixel: the texel's colour added to the screen's, each
    842  * channel stopping at 255. */
    843 #define MM_B(v, i)     ((int8_t)((uint64_t)(v) >> ((i) * 8)))
    844 #define MM_UB(v, i)    ((uint8_t)((uint64_t)(v) >> ((i) * 8)))
    845 #define MM_UW(v, i)    ((uint16_t)((uint64_t)(v) >> ((i) * 16)))
    846 #define MM_PUT_B(i, x) ((uint64_t)(uint8_t)(x) << ((i) * 8))
    847 #define MMX_LANES(n, put, expr) do { for (int i = 0; i < (n); i++) r |= put(i, (expr)); } while (0)
    848 static inline int mmx_clamp(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; }
    849 
    850 static inline uint64_t mmx_paddb(uint64_t a, uint64_t b)   { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, MM_UB(a,i) + MM_UB(b,i)); return r; }
    851 static inline uint64_t mmx_psubb(uint64_t a, uint64_t b)   { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, MM_UB(a,i) - MM_UB(b,i)); return r; }
    852 static inline uint64_t mmx_paddsb(uint64_t a, uint64_t b)  { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, mmx_clamp(MM_B(a,i) + MM_B(b,i), -128, 127)); return r; }
    853 static inline uint64_t mmx_psubsb(uint64_t a, uint64_t b)  { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, mmx_clamp(MM_B(a,i) - MM_B(b,i), -128, 127)); return r; }
    854 static inline uint64_t mmx_paddusb(uint64_t a, uint64_t b) { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, mmx_clamp(MM_UB(a,i) + MM_UB(b,i), 0, 255)); return r; }
    855 static inline uint64_t mmx_psubusb(uint64_t a, uint64_t b) { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, mmx_clamp(MM_UB(a,i) - MM_UB(b,i), 0, 255)); return r; }
    856 static inline uint64_t mmx_paddusw(uint64_t a, uint64_t b) { uint64_t r = 0; MMX_LANES(4, MM_PUT_W, mmx_clamp(MM_UW(a,i) + MM_UW(b,i), 0, 65535)); return r; }
    857 static inline uint64_t mmx_psubusw(uint64_t a, uint64_t b) { uint64_t r = 0; MMX_LANES(4, MM_PUT_W, mmx_clamp(MM_UW(a,i) - MM_UW(b,i), 0, 65535)); return r; }
    858 static inline uint64_t mmx_pcmpeqb(uint64_t a, uint64_t b) { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, MM_UB(a,i) == MM_UB(b,i) ? 0xFF : 0); return r; }
    859 static inline uint64_t mmx_pcmpgtb(uint64_t a, uint64_t b) { uint64_t r = 0; MMX_LANES(8, MM_PUT_B, MM_B(a,i) > MM_B(b,i) ? 0xFF : 0); return r; }
    860 /* Signed words to signed bytes with saturation, a's elements low. */
    861 static inline uint64_t mmx_packsswb(uint64_t a, uint64_t b) {
    862     uint64_t r = 0;
    863     MMX_LANES(4, MM_PUT_B, mmx_clamp(MM_W(a,i), -128, 127));
    864     for (int i = 0; i < 4; i++) r |= MM_PUT_B(4 + i, mmx_clamp(MM_W(b,i), -128, 127));
    865     return r;
    866 }
    867 
    868 /* ============================================================
    869  * SSE / SSE2
    870  *
    871  * Eight 128-bit registers, global like the rest of the register file; the
    872  * lifter emits _xmm[n] (tools/lift/lift32_sse.py has the instruction side).
    873  * Lanes are read through the union, so a register holds whatever bits were
    874  * put in it and a float lane never passes through the x87.
    875  *
    876  * MXCSR is kept for ldmxcsr/stmxcsr and its rounding field drives cvtss2si,
    877  * cvtsd2si and cvtps2pi. Exceptions stay masked, FTZ/DAZ are not modelled.
    878  * ============================================================ */
    879 
    880 typedef union {
    881     float    f32[4];
    882     double   f64[2];
    883     uint64_t u64[2];
    884     uint32_t u32[4];
    885     int32_t  i32[4];
    886     uint16_t u16[8];
    887     int16_t  i16[8];
    888     uint8_t  u8[16];
    889 } xmm_t;
    890 
    891 extern RECOMP_THREAD_LOCAL xmm_t    g_xmm[8];
    892 extern RECOMP_THREAD_LOCAL uint32_t g_mxcsr;
    893 
    894 static inline xmm_t xmm_ld(uint32_t a) { xmm_t v; memcpy(&v, (const void*)ADDR(a), 16); return v; }
    895 static inline void  xmm_st(uint32_t a, xmm_t v) { memcpy((void*)ADDR(a), &v, 16); }
    896 static inline float    sse_f32(uint32_t u) { float f; memcpy(&f, &u, 4); return f; }
    897 static inline uint32_t sse_u32(float f) { uint32_t u; memcpy(&u, &f, 4); return u; }
    898 static inline double   sse_f64(uint64_t u) { double d; memcpy(&d, &u, 8); return d; }
    899 static inline uint64_t sse_u64(double d) { uint64_t u; memcpy(&u, &d, 8); return u; }
    900 
    901 /* float/double -> int32 as cvt(t)ss2si does: NaN or out of range gives the
    902  * "integer indefinite" 0x80000000. Rounding is MXCSR's (bits 13-14), or
    903  * toward zero for the cvtt forms. */
    904 static inline int32_t sse_cvt_i32(double v, int chop) {
    905     if (!chop)
    906         switch ((g_mxcsr >> 13) & 3) {
    907         case 0: v = nearbyint(v); break;            /* the host's default: nearest-even */
    908         case 1: v = floor(v); break;
    909         case 2: v = ceil(v); break;
    910         default: v = trunc(v); break;
    911         }
    912     if (!(v > -2147483649.0 && v < 2147483648.0)) return (int32_t)0x80000000u;
    913     return (int32_t)v;
    914 }
    915 
    916 /* minss/maxss: the SECOND operand whenever the compare is false, NaN or
    917  * equal (+0 vs -0) included. A C fminf/fmaxf would not. */
    918 static inline float  sse_minf(float a, float b) { return a < b ? a : b; }
    919 static inline float  sse_maxf(float a, float b) { return a > b ? a : b; }
    920 static inline double sse_mind(double a, double b) { return a < b ? a : b; }
    921 static inline double sse_maxd(double a, double b) { return a > b ? a : b; }
    922 
    923 /* comiss/ucomiss/comisd/ucomisd and fcomi: the EFLAGS word, ZF PF CF, with
    924  * OF SF AF clear. Unordered sets all three. */
    925 #define SSE_COMI(a, b) ((a) < (b) ? 0x01u : (a) > (b) ? 0x00u : (a) == (b) ? 0x40u : 0x45u)
    926 
    927 /* cmpXXps/ss predicates 0-7: eq lt le unord neq nlt nle ord. */
    928 static inline uint32_t sse_cmp_pred(double a, double b, int p) {
    929     int r;
    930     switch (p & 7) {
    931     case 0: r = a == b; break;
    932     case 1: r = a < b; break;
    933     case 2: r = a <= b; break;
    934     case 3: r = a != a || b != b; break;
    935     case 4: r = !(a == b); break;
    936     case 5: r = !(a < b); break;
    937     case 6: r = !(a <= b); break;
    938     default: r = a == a && b == b; break;
    939     }
    940     return r ? 0xFFFFFFFFu : 0;
    941 }
    942 
    943 /* ============================================================
    944  * FPU Stack Helpers
    945  * ============================================================ */
    946 
    947 /* The x87 register is 80 bits with a 64-bit mantissa; ours is a double with 53.
    948  * That is invisible for arithmetic but not for `fild qword / fistp qword`, the
    949  * era's idiom for moving 8 bytes (a packed x,y pair, a 64-bit counter): through
    950  * a double, a large high dword rounds away the low bits. Nocturne's clipper
    951  * copies vertices that way and got x = -20/65536 where the original had 0, then
    952  * filled a 65535-pixel span. So each slot shadows the exact int64 `fild qword`
    953  * loaded, and `fistp qword` stores the shadow while the slot's double still
    954  * equals it (nothing has computed on it since).
    955  *
    956  * selectany/weak: one shared instance, defined by the header itself, so no
    957  * project runtime has to grow a definition for it. */
    958 #if defined(_MSC_VER)
    959 #define RECOMP_SHARED_DATA __declspec(selectany)
    960 #else
    961 #define RECOMP_SHARED_DATA __attribute__((weak))
    962 #endif
    963 RECOMP_SHARED_DATA RECOMP_THREAD_LOCAL int64_t g_st_i64[8] = {0};
    964 
    965 static inline void fp_push_impl(double* st, int* top, double val) {
    966     /* Shift stack down, push new value */
    967     /* Keep GCC from lowering these short shifts to out-of-line memmove. */
    968 #if defined(__GNUC__) && !defined(__clang__)
    969 #pragma GCC unroll 7
    970 #endif
    971     for (int i = 7; i > 0; i--) { st[i] = st[i-1]; g_st_i64[i] = g_st_i64[i-1]; }
    972     st[0] = val;
    973     g_st_i64[0] = 0;
    974     (*top)++;
    975 }
    976 
    977 static inline double fp_pop_impl(double* st, int* top) {
    978     double val = st[0];
    979     /* Keep GCC from lowering these short shifts to out-of-line memmove. */
    980 #if defined(__GNUC__) && !defined(__clang__)
    981 #pragma GCC unroll 7
    982 #endif
    983     for (int i = 0; i < 7; i++) { st[i] = st[i+1]; g_st_i64[i] = g_st_i64[i+1]; }
    984     st[7] = 0.0;
    985     g_st_i64[7] = 0;
    986     (*top)--;
    987     return val;
    988 }
    989 
    990 #define fp_push(val) fp_push_impl(_st, &_fp_top, (val))
    991 #define fp_pop()     fp_pop_impl(_st, &_fp_top)
    992 
    993 /* fild qword: push with the exact value shadowed. */
    994 #define fp_push_i64(v) do { int64_t _pv = (int64_t)(v); \
    995     fp_push((double)_pv); g_st_i64[0] = _pv; } while (0)
    996 /* fxch st(i), keeping each slot's shadow with its value. */
    997 #define fp_xch(i) do { double _t = _st[0]; _st[0] = _st[i]; _st[i] = _t; \
    998     int64_t _ti = g_st_i64[0]; g_st_i64[0] = g_st_i64[i]; g_st_i64[i] = _ti; } while (0)
    999 
   1000 /* fist/fistp round by the control word's RC field (bits 10-11), not by C's
   1001  * truncating cast. MSVC's __ftol sets chop before its fistp, so a plain cast
   1002  * looked right for years; Quake-lineage rasterisers deliberately run fistp in
   1003  * nearest (the default), floor or ceil mode, and a cast shifts every span and
   1004  * texture coordinate by up to one. */
   1005 static inline double fp_round_cw(double v, uint16_t cw) {
   1006     switch ((cw >> 10) & 3) {
   1007     case 0:  return nearbyint(v);   /* nearest-even: the host default mode */
   1008     case 1:  return floor(v);
   1009     case 2:  return ceil(v);
   1010     default: return trunc(v);
   1011     }
   1012 }
   1013 #define fp_to_int(v) fp_round_cw((v), _fpu_cw)
   1014 
   1015 /* fistp qword: the exact shadow while st0 is still the value fild loaded. */
   1016 static inline int64_t fp_st0_to_i64(double v0, int64_t shadow, uint16_t cw) {
   1017     return (v0 == (double)shadow) ? shadow : (int64_t)fp_round_cw(v0, cw);
   1018 }
   1019 
   1020 /* The 80-bit extended format, for `fld/fstp xword`. The model's stack is
   1021  * double, so a load rounds to double and a store widens. The CRT keeps 2*pi
   1022  * and friends as xword constants; a load that pushed 0.0 made sin/cos reduce
   1023  * by fmod(x, 0) = NaN, and Gunman's AngleVectors drew nothing. */
   1024 static inline double fp_ld80(const uint8_t* p) {
   1025     uint64_t m; uint16_t se;
   1026     memcpy(&m, p, 8); memcpy(&se, p + 8, 2);
   1027     int e = se & 0x7FFF;
   1028     double v;
   1029     if (e == 0x7FFF)
   1030         v = (m << 1) ? NAN : INFINITY;
   1031     else
   1032         v = ldexp((double)m, (e ? e : 1) - 16383 - 63);
   1033     return (se & 0x8000) ? -v : v;
   1034 }
   1035 static inline void fp_st80(uint8_t* p, double v) {
   1036     uint64_t m = 0; uint16_t se = signbit(v) ? 0x8000 : 0;
   1037     if (isnan(v)) { se |= 0x7FFF; m = 0xC000000000000000ull; }
   1038     else if (isinf(v)) { se |= 0x7FFF; m = 0x8000000000000000ull; }
   1039     else if (v != 0.0) {
   1040         int e; double f = frexp(fabs(v), &e);      /* f in [0.5, 1) */
   1041         m = (uint64_t)ldexp(f, 64);                /* exact: 53 bits */
   1042         se |= (uint16_t)(e - 1 + 16383);
   1043     }
   1044     memcpy(p, &m, 8); memcpy(p + 8, &se, 2);
   1045 }
   1046 
   1047 /* ============================================================
   1048  * CPUID stub
   1049  * ============================================================ */
   1050 
   1051 /* Feature bits the guest may see, ANDed into leaf 1 (edx/ecx) and leaf
   1052  * 0x80000001 (edx: 3DNow!). All ones by default. Libraries that dispatch on
   1053  * CPUID -- D3DX above all -- pick SSE/3DNow! paths on a modern host, and the
   1054  * global-register lifter does not implement most of those instructions; a
   1055  * host that clears the bits gets the x87 paths instead (The Movies: 16,977
   1056  * unimplemented SIMD sites against a handful of x87 ones). */
   1057 RECOMP_WEAK uint32_t g_cpuid_edx1 = 0xFFFFFFFFu, g_cpuid_ecx1 = 0xFFFFFFFFu;
   1058 RECOMP_WEAK uint32_t g_cpuid_edx_ext = 0xFFFFFFFFu;
   1059 
   1060 static inline void CPUID_impl(uint32_t eax_val, uint32_t ebx_val, uint32_t ecx_val, uint32_t edx_val) {
   1061 #ifdef _MSC_VER
   1062     int info[4];
   1063     __cpuidex(info, eax_val, ecx_val);
   1064     g_eax = info[0]; g_ebx = info[1]; g_ecx = info[2]; g_edx = info[3];
   1065     if (eax_val == 1) { g_edx &= g_cpuid_edx1; g_ecx &= g_cpuid_ecx1; }
   1066     if (eax_val == 0x80000001u) g_edx &= g_cpuid_edx_ext;
   1067     (void)ebx_val; (void)edx_val;
   1068 #else
   1069     (void)eax_val; (void)ebx_val; (void)ecx_val; (void)edx_val;
   1070 #endif
   1071 }
   1072 
   1073 /* CPUID_impl writes the global registers */
   1074 #define CPUID(a, b, c, d) do { RECOMP_REGS_OUT(); CPUID_impl(a, b, c, d); RECOMP_REGS_IN(); } while (0)
   1075 
   1076 /* ============================================================
   1077  * Indirect Call Dispatch
   1078  * ============================================================ */
   1079 
   1080 /* The VA of the function currently executing (see RECOMP_ENTER below); an
   1081  * unresolved dispatch is far more useful with its caller named. */
   1082 extern RECOMP_THREAD_LOCAL uint32_t g_cur_func;
   1083 
   1084 /* ICALL trace ring buffer for crash diagnostics.
   1085  *
   1086  * Both halves matter. A target on its own says which vtable slot ran; the
   1087  * CALLER is what you actually need, because an indirect call is how a null
   1088  * `this` or a null argument gets handed across a module boundary, and the
   1089  * function that built the argument is the one to read. Recovering it by hand
   1090  * means a --calltrace and guessing which nearby entry was still on the stack,
   1091  * and the entry ring is no help when the answer is 33 entries back. */
   1092 /* 32 was too small the first time it mattered: a method that makes a few
   1093  * indirect calls of its own scrolls its own entry out of the ring, so the
   1094  * report showed it as a caller and never as a target, and the function that
   1095  * handed it a null argument was already gone. 128 costs a kilobyte. */
   1096 #define ICALL_TRACE_SIZE 128
   1097 extern RECOMP_THREAD_LOCAL uint32_t g_icall_trace[ICALL_TRACE_SIZE];
   1098 extern RECOMP_THREAD_LOCAL uint32_t g_icall_from[ICALL_TRACE_SIZE];
   1099 extern RECOMP_THREAD_LOCAL uint32_t g_icall_trace_idx;
   1100 extern RECOMP_THREAD_LOCAL uint32_t g_icall_count;
   1101 
   1102 /* Keep recent-call history for Windows diagnostics and trace builds. */
   1103 #if !defined(RECOMP_PORTABLE) || defined(RECOMP_TRACE)
   1104 #define RECOMP_RECORD_ICALL(va) do { \
   1105     g_icall_trace[g_icall_trace_idx & (ICALL_TRACE_SIZE-1)] = (va); \
   1106     g_icall_from[g_icall_trace_idx & (ICALL_TRACE_SIZE-1)] = g_cur_func; \
   1107     g_icall_trace_idx++; \
   1108 } while (0)
   1109 #else
   1110 #define RECOMP_RECORD_ICALL(va) ((void)0)
   1111 #endif
   1112 
   1113 /* Lookup functions */
   1114 recomp_func_t recomp_lookup(uint32_t va);          /* binary search in dispatch table */
   1115 recomp_func_t recomp_lookup_manual(uint32_t va);    /* manual overrides */
   1116 recomp_func_t recomp_lookup_import(uint32_t va);    /* import bridges */
   1117 
   1118 /* The dummy return address pushed before a recompiled call. The callee's lifted
   1119  * `ret` pops it. 0xDEAD0000 is a recognizable marker, but if a stack imbalance
   1120  * ever leaks it into a value (e.g. a size argument) the high bits are destructive.
   1121  * Projects that have hit such a leak can define RECOMP_RETADDR=0u so a leak is
   1122  * benign while it's tracked down. */
   1123 #ifndef RECOMP_RETADDR
   1124 #define RECOMP_RETADDR 0xDEAD0000u
   1125 #endif
   1126 
   1127 /* Flags cross every transfer, as on the CPU: each call and tail hands the
   1128  * caller's flags over (RECOMP_FLAGS_OUT), every function starts from them
   1129  * (RECOMP_ENTER), and `ret` hands the callee's back. Without the first two, a
   1130  * function reached by a tail jump started from FK_NONE, and one whose first
   1131  * conditional reads flags its predecessor set took an arbitrary branch: the
   1132  * MSVC CRT's `cos` runs a load helper, then falls into `_CIcos`, a separate
   1133  * function whose first `je` tests the helper's ZF (Bunghole in One's ball
   1134  * never moved). */
   1135 
   1136 /* Direct call to a known recompiled function */
   1137 #define RECOMP_CALL(func) do { \
   1138     uint32_t _caller = g_cur_func; \
   1139     PUSH32(esp, RECOMP_RETADDR); /* dummy return address */ \
   1140     RECOMP_FLAGS_OUT(); \
   1141     RECOMP_REGS_OUT(); \
   1142     func(); \
   1143     RECOMP_REGS_IN(); \
   1144     g_cur_func = _caller;  /* the callee RECOMP_ENTER clobbered it */ \
   1145 } while(0)
   1146 
   1147 /* Indirect call through dispatch */
   1148 #define RECOMP_ICALL(target_va) do { \
   1149     uint32_t _va = (uint32_t)(target_va); \
   1150     RECOMP_RECORD_ICALL(_va); \
   1151     g_icall_count++; \
   1152     recomp_func_t _fn = recomp_lookup_manual(_va); \
   1153     if (!_fn) _fn = recomp_lookup(_va); \
   1154     if (!_fn) _fn = recomp_lookup_import(_va); \
   1155     if (_fn) { \
   1156         uint32_t _caller = g_cur_func; \
   1157         PUSH32(esp, RECOMP_RETADDR); \
   1158         RECOMP_FLAGS_OUT(); \
   1159         RECOMP_REGS_OUT(); \
   1160         _fn(); \
   1161         RECOMP_REGS_IN(); \
   1162         g_cur_func = _caller;  /* the callee RECOMP_ENTER clobbered it */ \
   1163     } else { \
   1164         /* Nothing was pushed on this path, so there is nothing to pop: an \
   1165          * `esp += 4` here shifted the caller's stack by one slot per miss. \
   1166          * (Nocturne's CRT init runner lost its saved registers that way and \
   1167          * skipped ~90 static constructors after its first unlifted entry.) */ \
   1168         fprintf(stderr, "ICALL: unresolved VA 0x%08X from 0x%08X\n", _va, g_cur_func); \
   1169         eax = 0; \
   1170     } \
   1171 } while(0)
   1172 
   1173 /* Indirect tail call (jmp through dispatch) */
   1174 #define RECOMP_ITAIL(target_va) do { \
   1175     uint32_t _va = (uint32_t)(target_va); \
   1176     RECOMP_RECORD_ICALL(_va); \
   1177     g_icall_count++; \
   1178     recomp_func_t _fn = recomp_lookup_manual(_va); \
   1179     if (!_fn) _fn = recomp_lookup(_va); \
   1180     if (!_fn) _fn = recomp_lookup_import(_va); \
   1181     if (_fn) { RECOMP_FLAGS_OUT(); RECOMP_REGS_OUT(); _fn(); RECOMP_REGS_IN(); } \
   1182     else if (_va == RECOMP_RETADDR) { /* setjmp and friends return by jumping \
   1183         to the saved return address; that is a return, not a missing target. */ } \
   1184     else { fprintf(stderr, "ITAIL: unresolved VA 0x%08X from 0x%08X\n", _va, g_cur_func); } \
   1185 } while(0)
   1186 
   1187 /* `push target; ret` (Lifter dos=True): a jump to a computed address. Its own
   1188  * name, so generate.py does not take it for an intra-function indirect jump. */
   1189 #define RECOMP_RET_JUMP(target_va) RECOMP_ITAIL(target_va)
   1190 
   1191 /* ============================================================
   1192  * Optional function-entry tracer (enable with -DRECOMP_TRACE).
   1193  *
   1194  * Each lifted function records its VA into a ring buffer on entry, so a crash
   1195  * or unexpected exit can dump the last N functions that ran -- a poor-man's
   1196  * backtrace when no debugger is available. Zero cost unless RECOMP_TRACE is set.
   1197  * ============================================================ */
   1198 /* Always-on: the VA of the function currently executing. A plain global store
   1199  * (no call), so unlike the ring tracer below it doesn't force register reloads --
   1200  * useful for pinning a crash to a function without perturbing codegen. */
   1201 extern RECOMP_THREAD_LOCAL uint32_t g_cur_func;
   1202 
   1203 #ifdef RECOMP_TRACE
   1204 #define RECOMP_ENTER_SIZE 1024
   1205 extern RECOMP_THREAD_LOCAL uint32_t g_enter_trace[RECOMP_ENTER_SIZE];
   1206 extern RECOMP_THREAD_LOCAL uint32_t g_enter_idx;
   1207 void recomp_trace_enter(uint32_t va);
   1208 #define RECOMP_ENTER(va) do { g_cur_func = (va); RECOMP_FLAGS_IN(); recomp_trace_enter(va); } while (0)
   1209 #else
   1210 #define RECOMP_ENTER(va) (g_cur_func = (va), RECOMP_FLAGS_IN())
   1211 #endif
   1212 
   1213 /* Guest C++ exceptions (runtime/native32/eh32.c). A lifted function whose
   1214  * prologue installs an MSVC EH frame gets a host landing pad: on a caught
   1215  * throw the runtime longjmps here with the guest registers set for the
   1216  * catch's continuation, and the local dispatch goes to its label.
   1217  * entry_esp is esp at entry (at the return address): the frame's ebp + 4. */
   1218 #include <setjmp.h>
   1219 typedef struct recomp_ehframe {
   1220     struct recomp_ehframe* prev;
   1221     jmp_buf  jb;
   1222     uint32_t entry_esp;
   1223     uint32_t resume;
   1224 } recomp_ehframe_t;
   1225 void recomp_eh_push(recomp_ehframe_t* f);
   1226 void recomp_eh_pop(recomp_ehframe_t* f);
   1227 #define RECOMP_EH_ENTER()                                                     \
   1228     recomp_ehframe_t _ehf;                                                    \
   1229     _ehf.entry_esp = g_esp;                                                   \
   1230     recomp_eh_push(&_ehf);                                                    \
   1231     if (setjmp(_ehf.jb)) { RECOMP_REGS_IN(); _flag_k = FK_NONE;               \
   1232                            _itail_tgt = _ehf.resume; goto _ljump; }
   1233 #define RECOMP_EH_LEAVE() recomp_eh_pop(&_ehf)
   1234 /* A backward branch in lifted code: a loop. Every RECOMP_YIELD_EVERY of them,
   1235  * hand the machine to other guest threads if the host has a way to
   1236  * (native32_yield). A lifted spin-wait makes no native call, and native32
   1237  * hands its machine lock over only at native calls, so a loop waiting on
   1238  * another guest thread's flag never let that thread run: Yuri's Revenge's
   1239  * exit spins until its sound thread acknowledges a stop (0x0040A047) and hung
   1240  * there. The registers go back to the globals around the hand-over, which is
   1241  * all a native call does. Portable threads own independent loop counters;
   1242  * the Windows host serializes its shared machine state. */
   1243 RECOMP_WEAK void (*recomp_yield_hook)(void);
   1244 RECOMP_WEAK RECOMP_THREAD_LOCAL uint32_t g_backedges;
   1245 #ifndef RECOMP_YIELD_EVERY
   1246 #define RECOMP_YIELD_EVERY 0x10000u
   1247 #endif
   1248 #define RECOMP_BACKEDGE() do { \
   1249     if (++g_backedges >= RECOMP_YIELD_EVERY && recomp_yield_hook) { \
   1250         g_backedges = 0; \
   1251         RECOMP_REGS_OUT(); recomp_yield_hook(); RECOMP_REGS_IN(); \
   1252     } } while (0)
   1253 
   1254 /* Always-callable trace dump (no-op unless RECOMP_TRACE). */
   1255 void recomp_dump_trace(const char* why);
   1256 
   1257 /* Stub macro for unimplemented imports */
   1258 #define STUB(name) do { \
   1259     static int _warned = 0; \
   1260     if (!_warned) { fprintf(stderr, "STUB: %s called\n", name); _warned = 1; } \
   1261 } while(0)
   1262 
   1263 #endif /* RECOMP_TYPES_H */