From b2db9da201b30a7b9d77c2a25039c7ac603f424a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 05:15:37 +0100 Subject: [PATCH 01/14] target/ppc: flush BAT ranges by block length and only when valid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a BAT register is rewritten, its old block has to be dropped from the softmmu TLB. do_invalidate_BAT() was passed the block length of the *new* value, so clearing or shrinking a BAT only flushed the first 128 KB of the old block, and stale translations of the rest survived. Use the length encoded in each BAT value instead. The flush also did more work than needed, which costs a lot with classic Mac OS: its NanoKernel rewrites IBAT0/1 and DBAT0/1 (4 MB ROM, 1 MB 68k emulator) every time it switches context, thousands of times per second even when idle, and each switch flushed ~1700 pages one by one in all 16 MMU indexes: - skip BATs with neither Vs nor Vp set: they match no access, so the TLB holds nothing from them and they hide no page table translation; - flush with tlb_flush_range_by_mmuidx() instead of a page loop; - only flush the MMU indexes with translation enabled: BATs never apply in real mode. Mac OS 9.2.2 on mac99 (G4, TCG, Apple Silicon host), idle desktop: QEMU host CPU 57% -> 33%. Default-on; no switch. Fixes a stale-TLB bug as well as saving time. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- target/ppc/mmu_helper.c | 46 ++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/target/ppc/mmu_helper.c b/target/ppc/mmu_helper.c index ad9ba8294cc61..236f4933b8f27 100644 --- a/target/ppc/mmu_helper.c +++ b/target/ppc/mmu_helper.c @@ -146,28 +146,32 @@ static void booke206_flush_tlb(CPUPPCState *env, int flags, /*****************************************************************************/ /* BATs management */ #if !defined(FLUSH_ALL_TLBS) -static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu, - target_ulong mask) +/* + * MMU indexes that use address translation (see hreg_compute_hflags_value()): + * bit 1 of the index is set in real mode, where BATs never apply. + */ +#define PPC_BAT_MMUIDX_BITS ((1 << 0) | (1 << 1) | (1 << 4) | (1 << 5)) + +/* + * Drop the TLB entries a BAT can affect: the ones it translated, and the + * page table translations it hid. Use the block length of this BAT value, + * not of the value that replaces it, or entries beyond the new length + * would survive a BAT being shrunk or cleared. + */ +static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu) { - CPUState *cs = env_cpu(env); - target_ulong base, end, page; + target_ulong base, len; - base = BATu & ~0x0001FFFF; - end = base + mask + 0x00020000; - if (((end - base) >> TARGET_PAGE_BITS) > 1024) { - /* Flushing 1024 4K pages is slower than a complete flush */ - qemu_log_mask(CPU_LOG_MMU, "Flush all BATs\n"); - tlb_flush(cs); - qemu_log_mask(CPU_LOG_MMU, "Flush done\n"); + /* Neither Vs nor Vp: the BAT matches nothing, nothing to drop */ + if (!(BATu & 0x3)) { return; } + base = BATu & ~0x0001FFFF; + len = ((BATu << 15) & 0x0FFE0000UL) + 0x00020000; qemu_log_mask(CPU_LOG_MMU, "Flush BAT from " TARGET_FMT_lx - " to " TARGET_FMT_lx " (" TARGET_FMT_lx ")\n", - base, end, mask); - for (page = base; page != end; page += TARGET_PAGE_SIZE) { - tlb_flush_page(cs, page); - } - qemu_log_mask(CPU_LOG_MMU, "Flush done\n"); + " length " TARGET_FMT_lx "\n", base, len); + tlb_flush_range_by_mmuidx(env_cpu(env), base, len, + PPC_BAT_MMUIDX_BITS, TARGET_LONG_BITS); } #endif @@ -187,7 +191,7 @@ void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong value) if (env->IBAT[0][nr] != value) { mask = (value << 15) & 0x0FFE0000UL; #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->IBAT[0][nr], mask); + do_invalidate_BAT(env, env->IBAT[0][nr]); #endif /* * When storing valid upper BAT, mask BEPI and BRPN and @@ -199,7 +203,7 @@ void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong value) env->IBAT[1][nr] = (env->IBAT[1][nr] & 0x0000007B) | (env->IBAT[1][nr] & ~0x0001FFFF & ~mask); #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->IBAT[0][nr], mask); + do_invalidate_BAT(env, env->IBAT[0][nr]); #else tlb_flush(env_cpu(env)); #endif @@ -224,7 +228,7 @@ void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong value) */ mask = (value << 15) & 0x0FFE0000UL; #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->DBAT[0][nr], mask); + do_invalidate_BAT(env, env->DBAT[0][nr]); #endif mask = (value << 15) & 0x0FFE0000UL; env->DBAT[0][nr] = (value & 0x00001FFFUL) | @@ -232,7 +236,7 @@ void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong value) env->DBAT[1][nr] = (env->DBAT[1][nr] & 0x0000007B) | (env->DBAT[1][nr] & ~0x0001FFFF & ~mask); #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->DBAT[0][nr], mask); + do_invalidate_BAT(env, env->DBAT[0][nr]); #else tlb_flush(env_cpu(env)); #endif From b14ae6cb6cdf784786da1befd445ebdc21da845d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 05:15:37 +0100 Subject: [PATCH 02/14] accel/tcg: clear the whole jump cache for ranges that cover it anyway MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tlb_flush_range_by_mmuidx_async_0() clears the jump cache page by page for ranges below TB_JMP_CACHE_SIZE pages (16 MB with 4 KB pages), 64 entries per page. A page's bucket is its page number bits [0, P) xor bits [P, 2P) (P = TB_JMP_PAGE_BITS), so any run of 2 << P pages contains an aligned run of 1 << P pages that hits every bucket: from 512 KB on, the loop already empties the whole cache, but touches up to 64 times more entries than tcg_flush_jmp_cache() does. Lower the threshold to 2 << P pages. The result is the same; only the cost changes. With classic Mac OS guests flushing 1-4 MB BAT ranges thousands of times per second, idle host CPU goes from 33% to 28%. Default-on; no switch. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- accel/tcg/cputlb.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/accel/tcg/cputlb.c b/accel/tcg/cputlb.c index 1040af2d2275e..3b18f11ec125e 100644 --- a/accel/tcg/cputlb.c +++ b/accel/tcg/cputlb.c @@ -736,7 +736,13 @@ static void tlb_flush_range_by_mmuidx_async_0(CPUState *cpu, * If the length is larger than the jump cache size, then it will take * longer to clear each entry individually than it will to clear it all. */ - if (d.len >= (TARGET_PAGE_SIZE * TB_JMP_CACHE_SIZE)) { + /* + * A page's jump cache bucket is its page number bits [0, P) xor bits + * [P, 2P), P = TB_JMP_PAGE_BITS. Any run of 2 << P pages holds an + * aligned run of 1 << P pages, which covers every bucket: clearing it + * page by page would empty the whole cache, only more slowly. + */ + if (d.len >= (TARGET_PAGE_SIZE * 2 * (TB_JMP_CACHE_SIZE / TB_JMP_PAGE_SIZE))) { tcg_flush_jmp_cache(cpu); return; } From a9485249c0bb9a428cae4eecbec3c80fdb607edf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:15:51 +0100 Subject: [PATCH 03/14] accel/tcg: bigger TB jump cache, retired by a generation counter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Mac OS X game covers 100k+ translation blocks, so with 4096 entries most indirect branches -- and every PowerPC return through blr is one -- missed the jump cache and fell back to the hash table: a quarter of the emulator's busy time went into lookups. 64K entries fix that but make emptying the cache 16x more expensive, and a 32-bit hash MMU guest empties it constantly; measured on Warcraft III, the larger cache alone traded lookups for flush stalls. Retire entries by bumping a generation counter instead, so a flush is O(1) whatever the cache size, and walk the array only on the 32-bit wrap. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Default-on; no switch. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- accel/tcg/cpu-exec.c | 3 +++ accel/tcg/tb-jmp-cache.h | 17 ++++++++++++++++- accel/tcg/translate-all.c | 13 +++++++++++-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/accel/tcg/cpu-exec.c b/accel/tcg/cpu-exec.c index 3fc76e69e7136..32be45758d7c3 100644 --- a/accel/tcg/cpu-exec.c +++ b/accel/tcg/cpu-exec.c @@ -247,6 +247,7 @@ static inline TranslationBlock *tb_lookup(CPUState *cpu, vaddr pc, tb = qatomic_read(&jc->array[hash].tb); if (likely(tb && + jc->array[hash].gen == jc->gen && jc->array[hash].pc == pc && tb->cs_base == cs_base && tb->flags == flags && @@ -260,6 +261,7 @@ static inline TranslationBlock *tb_lookup(CPUState *cpu, vaddr pc, } jc->array[hash].pc = pc; + jc->array[hash].gen = jc->gen; qatomic_set(&jc->array[hash].tb, tb); hit: @@ -995,6 +997,7 @@ cpu_exec_loop(CPUState *cpu, SyncClocks *sc) h = tb_jmp_cache_hash_func(pc); jc = cpu->tb_jmp_cache; jc->array[h].pc = pc; + jc->array[h].gen = jc->gen; qatomic_set(&jc->array[h].tb, tb); } diff --git a/accel/tcg/tb-jmp-cache.h b/accel/tcg/tb-jmp-cache.h index c3a505e394a96..b9a615dde2e80 100644 --- a/accel/tcg/tb-jmp-cache.h +++ b/accel/tcg/tb-jmp-cache.h @@ -12,7 +12,14 @@ #include "qemu/rcu.h" #include "exec/cpu-common.h" -#define TB_JMP_CACHE_BITS 12 +/* + * 4096 entries (the upstream default) thrash badly under a Mac OS X guest: + * a game's hot code covers 100k+ translation blocks, so most indirect + * branches -- and PowerPC returns through blr are indirect -- miss the + * cache and fall back to the (much slower) hash table. 64K entries cost + * 1 MB per vCPU and turn most of those misses into hits. + */ +#define TB_JMP_CACHE_BITS 16 #define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS) /* @@ -24,9 +31,17 @@ */ typedef struct CPUJumpCache { struct rcu_head rcu; + /* + * Emptying the cache means bumping this counter: an entry counts only + * while its own gen matches. Clearing 64K entries outright on every + * TLB flush would cost far more than the cache saves, and a 32-bit + * hash MMU guest flushes constantly. + */ + uint32_t gen; struct { TranslationBlock *tb; vaddr pc; + uint32_t gen; } array[TB_JMP_CACHE_SIZE]; } CPUJumpCache; diff --git a/accel/tcg/translate-all.c b/accel/tcg/translate-all.c index 7c897854eba59..bf26e00fc483a 100644 --- a/accel/tcg/translate-all.c +++ b/accel/tcg/translate-all.c @@ -673,7 +673,16 @@ void tcg_flush_jmp_cache(CPUState *cpu) return; } - for (int i = 0; i < TB_JMP_CACHE_SIZE; i++) { - qatomic_set(&jc->array[i].tb, NULL); + /* + * Retire every entry at once. Only on the (4-billionth) wrap does the + * cache have to be walked, so that generation 0 cannot match entries + * left behind by an earlier lap of the counter. + */ + if (++jc->gen == 0) { + for (int i = 0; i < TB_JMP_CACHE_SIZE; i++) { + qatomic_set(&jc->array[i].tb, NULL); + jc->array[i].gen = 0; + } + jc->gen = 1; } } From 78dadb8da4e97be7871a9314a215f44114e740ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:18:07 +0100 Subject: [PATCH 04/14] tcg: probe the jump cache inline for PowerPC branches to computed addresses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every blr, bctr and branch to another page went through helper_lookup_tb_ptr, whose jump cache probe is a few loads and compares behind a helper call, curr_cflags() and cpu_get_tb_cpu_state(). In Geekbench 2's integer tests on Tiger that helper was up to half of the vCPU thread's time. translator_lookup_and_goto_ptr() emits the probe itself: hash the pc, check the entry's pc and generation, and that the TB has this TB's cs_base, flags and cflags, then goto_ptr to it; a miss calls the helper as before. It is only for exits where the CPU state that cpu_get_tb_cpu_state() returns can't have changed since the TB began, and only for TBs with ordinary cflags (no icount, single-step, breakpoint page, plugins or exec logging). PowerPC uses it for branches to LR, CTR and TAR and for direct branches off the TB's page. Geekbench 2 on Tiger 10.4.11 (M1 Max): helper calls 2.6G -> 0.38G, integer 1173 -> 1308, overall 1249 -> 1314. QEMU_TB_INLINE=0 turns the inline probe off and always calls helper_lookup_tb_ptr, for A/B comparisons. The probe is otherwise default-on, for PowerPC guests only. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- accel/tcg/translator.c | 89 +++++++++++++++++++++++++++++++++++++ include/exec/translator.h | 12 +++++ include/tcg/tcg-op-common.h | 2 + target/ppc/translate.c | 21 ++++++++- tcg/tcg-op.c | 8 ++++ 5 files changed, 130 insertions(+), 2 deletions(-) diff --git a/accel/tcg/translator.c b/accel/tcg/translator.c index ef1538b4fcda1..21da1d67f5c36 100644 --- a/accel/tcg/translator.c +++ b/accel/tcg/translator.c @@ -20,6 +20,8 @@ #include "internal-target.h" #include "disas/disas.h" #include "tb-internal.h" +#include "tb-hash.h" +#include "tb-jmp-cache.h" static void set_can_do_io(DisasContextBase *db, bool val) { @@ -120,6 +122,93 @@ bool translator_use_goto_tb(DisasContextBase *db, vaddr dest) return translator_is_same_page(db, dest); } +/* + * helper_lookup_tb_ptr's jump cache probe, inline: hash @pc, and if the + * entry holds a live TB for it with this TB's cs_base, flags and cflags, + * jump straight to it; otherwise call the helper as before. Returns and + * other indirect branches take this path on every execution, and the + * helper call costs far more than the probe. + * + * Only for exits where cpu_get_tb_cpu_state() still returns this TB's + * cs_base and flags, and only for TBs with ordinary cflags, which is what + * curr_cflags() returns while such TBs run: anything unusual (icount, + * single-stepping, breakpoints on the page, plugins, exec logging) keeps + * the helper, which handles it. + */ +/* QEMU_TB_INLINE=0 always calls helper_lookup_tb_ptr (for A/B tests). */ +static bool tb_inline_lookup_on(void) +{ + static int on = -1; + + if (on < 0) { + const char *e = getenv("QEMU_TB_INLINE"); + on = !(e && e[0] == '0'); + } + return on; +} + +void translator_lookup_and_goto_ptr(DisasContextBase *db, TCGv_i64 pc) +{ + TranslationBlock *tb = db->tb; + uint32_t cf = tb_cflags(tb); + const size_t esz = sizeof(((CPUJumpCache *)0)->array[0]); + TCGLabel *miss; + TCGv_i64 h, t; + TCGv_ptr jc, e, next; + TCGv_i32 a, b; + + if ((cf & (CF_COUNT_MASK | CF_NO_GOTO_TB | CF_NO_GOTO_PTR | CF_SINGLE_STEP | + CF_MEMI_ONLY | CF_USE_ICOUNT | CF_NOIRQ | CF_PCREL | + CF_BP_PAGE)) || + db->plugin_enabled || qemu_loglevel_mask(CPU_LOG_TB_CPU | CPU_LOG_EXEC) || + !tb_inline_lookup_on()) { + tcg_gen_lookup_and_goto_ptr(); + return; + } + + miss = gen_new_label(); + h = tcg_temp_new_i64(); + t = tcg_temp_new_i64(); + jc = tcg_temp_new_ptr(); + e = tcg_temp_new_ptr(); + next = tcg_temp_new_ptr(); + a = tcg_temp_new_i32(); + b = tcg_temp_new_i32(); + + /* tb_jmp_cache_hash_func(pc) * esz */ + tcg_gen_shri_i64(t, pc, TARGET_PAGE_BITS - TB_JMP_PAGE_BITS); + tcg_gen_xor_i64(t, t, pc); + tcg_gen_shri_i64(h, t, TARGET_PAGE_BITS - TB_JMP_PAGE_BITS); + tcg_gen_andi_i64(h, h, TB_JMP_PAGE_MASK); + tcg_gen_andi_i64(t, t, TB_JMP_ADDR_MASK); + tcg_gen_or_i64(h, h, t); + tcg_gen_muli_i64(h, h, esz); + + tcg_gen_ld_ptr(jc, tcg_env, offsetof(ArchCPU, parent_obj.tb_jmp_cache) - + offsetof(ArchCPU, env)); + tcg_gen_trunc_i64_ptr(e, h); + tcg_gen_add_ptr(e, e, jc); + + tcg_gen_ld_ptr(next, e, offsetof(CPUJumpCache, array[0].tb)); + tcg_gen_brcondi_ptr(TCG_COND_EQ, next, 0, miss); + tcg_gen_ld_i64(t, e, offsetof(CPUJumpCache, array[0].pc)); + tcg_gen_brcond_i64(TCG_COND_NE, t, pc, miss); + tcg_gen_ld_i32(a, e, offsetof(CPUJumpCache, array[0].gen)); + tcg_gen_ld_i32(b, jc, offsetof(CPUJumpCache, gen)); + tcg_gen_brcond_i32(TCG_COND_NE, a, b, miss); + tcg_gen_ld_i64(t, next, offsetof(TranslationBlock, cs_base)); + tcg_gen_brcondi_i64(TCG_COND_NE, t, tb->cs_base, miss); + tcg_gen_ld_i32(a, next, offsetof(TranslationBlock, flags)); + tcg_gen_brcondi_i32(TCG_COND_NE, a, tb->flags, miss); + tcg_gen_ld_i32(a, next, offsetof(TranslationBlock, cflags)); + tcg_gen_brcondi_i32(TCG_COND_NE, a, cf, miss); + tcg_gen_ld_ptr(next, next, offsetof(TranslationBlock, tc.ptr)); + tcg_gen_goto_ptr(next); + + gen_set_label(miss); + tcg_gen_lookup_and_goto_ptr(); +} + void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns, vaddr pc, void *host_pc, const TranslatorOps *ops, DisasContextBase *db) diff --git a/include/exec/translator.h b/include/exec/translator.h index d70942a10ff70..2b0160b2cefb7 100644 --- a/include/exec/translator.h +++ b/include/exec/translator.h @@ -158,6 +158,18 @@ void translator_loop(CPUState *cpu, TranslationBlock *tb, int *max_insns, */ bool translator_use_goto_tb(DisasContextBase *db, vaddr dest); +/** + * translator_lookup_and_goto_ptr + * @db: Disassembly context + * @pc: the next pc, as the CPU state already holds it + * + * Like tcg_gen_lookup_and_goto_ptr(), but probes the jump cache inline + * first. Only valid where the CPU's cs_base and flags are still this + * TB's (see the definition). + */ +struct TCGv_i64_d; +void translator_lookup_and_goto_ptr(DisasContextBase *db, struct TCGv_i64_d *pc); + /** * translator_io_start * @db: Disassembly context diff --git a/include/tcg/tcg-op-common.h b/include/tcg/tcg-op-common.h index 009e2778c5ff1..c67c2844ca01a 100644 --- a/include/tcg/tcg-op-common.h +++ b/include/tcg/tcg-op-common.h @@ -73,6 +73,8 @@ void tcg_gen_goto_tb(unsigned idx); * this op is equivalent to calling tcg_gen_exit_tb() with 0 as the argument. */ void tcg_gen_lookup_and_goto_ptr(void); +/* Jump to TB code at ptr, found by the caller; the TB must allow goto_ptr. */ +void tcg_gen_goto_ptr(TCGv_ptr ptr); void tcg_gen_plugin_cb(unsigned from); void tcg_gen_plugin_mem_cb(TCGv_i64 addr, unsigned meminfo); diff --git a/target/ppc/translate.c b/target/ppc/translate.c index a52cbc869ae03..eb2709257fc6d 100644 --- a/target/ppc/translate.c +++ b/target/ppc/translate.c @@ -3656,6 +3656,23 @@ static void gen_lookup_and_goto_ptr(DisasContext *ctx) } } +/* + * A branch to cpu_nip that changes nothing else: the next TB has this + * TB's hflags and cs_base, so the jump cache can be probed inline. + */ +static void gen_branch_lookup_and_goto_ptr(DisasContext *ctx) +{ + if (unlikely(ctx->singlestep_enabled) || + (tb_cflags(ctx->base.tb) & CF_NO_GOTO_PTR)) { + gen_lookup_and_goto_ptr(ctx); + } else { + TCGv_i64 pc = tcg_temp_new_i64(); + + tcg_gen_extu_tl_i64(pc, cpu_nip); + translator_lookup_and_goto_ptr(&ctx->base, pc); + } +} + /*** Branch ***/ static void gen_goto_tb(DisasContext *ctx, int n, target_ulong dest) { @@ -3669,7 +3686,7 @@ static void gen_goto_tb(DisasContext *ctx, int n, target_ulong dest) tcg_gen_exit_tb(ctx->base.tb, n); } else { tcg_gen_movi_tl(cpu_nip, dest & ~3); - gen_lookup_and_goto_ptr(ctx); + gen_branch_lookup_and_goto_ptr(ctx); } } @@ -3818,7 +3835,7 @@ static void gen_bcond(DisasContext *ctx, int type) } else { tcg_gen_andi_tl(cpu_nip, target, ~3); } - gen_lookup_and_goto_ptr(ctx); + gen_branch_lookup_and_goto_ptr(ctx); } if ((bo & 0x14) != 0x14) { /* fallthrough case */ diff --git a/tcg/tcg-op.c b/tcg/tcg-op.c index e58b3fefd3a94..f19aab7a60cf8 100644 --- a/tcg/tcg-op.c +++ b/tcg/tcg-op.c @@ -3389,3 +3389,11 @@ void tcg_gen_lookup_and_goto_ptr(void) tcg_gen_op1i(INDEX_op_goto_ptr, TCG_TYPE_PTR, tcgv_ptr_arg(ptr)); tcg_temp_free_ptr(ptr); } + +/* Jump to the code of a TB the caller looked up itself. */ +void tcg_gen_goto_ptr(TCGv_ptr ptr) +{ + tcg_debug_assert(!(tcg_ctx->gen_tb->cflags & CF_NO_GOTO_PTR)); + plugin_gen_disable_mem_helpers(); + tcg_gen_op1i(INDEX_op_goto_ptr, TCG_TYPE_PTR, tcgv_ptr_arg(ptr)); +} From 84d7e2e5b9dd689ea91faef7d4ba8df8d2801e63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:56:16 +0100 Subject: [PATCH 05/14] accel/tcg: run TCG vCPU threads at user-interactive QoS on macOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit vCPU threads run at QOS_CLASS_USER_INTERACTIVE so macOS keeps them on performance cores instead of parking them on efficiency cores when the host is busy or the window is in the background. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Default-on, macOS hosts only. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- accel/tcg/tcg-accel-ops-mttcg.c | 9 +++++++++ accel/tcg/tcg-accel-ops-rr.c | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/accel/tcg/tcg-accel-ops-mttcg.c b/accel/tcg/tcg-accel-ops-mttcg.c index bdcc385ae971d..575692643bc4d 100644 --- a/accel/tcg/tcg-accel-ops-mttcg.c +++ b/accel/tcg/tcg-accel-ops-mttcg.c @@ -24,6 +24,9 @@ */ #include "qemu/osdep.h" +#ifdef __APPLE__ +#include +#endif #include "system/tcg.h" #include "system/replay.h" #include "system/cpu-timers.h" @@ -70,6 +73,12 @@ static void *mttcg_cpu_thread_fn(void *arg) g_assert(!icount_enabled()); rcu_register_thread(); +#ifdef __APPLE__ + /* The vCPU thread is the emulator's critical path: keep it on the + * performance cores instead of letting macOS park it on efficiency + * cores whenever the host is busy or the window is in the background. */ + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); +#endif force_rcu.notifier.notify = mttcg_force_rcu; force_rcu.cpu = cpu; rcu_add_force_rcu_notifier(&force_rcu.notifier); diff --git a/accel/tcg/tcg-accel-ops-rr.c b/accel/tcg/tcg-accel-ops-rr.c index f62cf24e1d4dd..e6ea547803a12 100644 --- a/accel/tcg/tcg-accel-ops-rr.c +++ b/accel/tcg/tcg-accel-ops-rr.c @@ -24,6 +24,9 @@ */ #include "qemu/osdep.h" +#ifdef __APPLE__ +#include +#endif #include "qemu/lockable.h" #include "system/tcg.h" #include "system/replay.h" @@ -184,6 +187,12 @@ static void *rr_cpu_thread_fn(void *arg) assert(tcg_enabled()); rcu_register_thread(); +#ifdef __APPLE__ + /* The vCPU thread is the emulator's critical path: keep it on the + * performance cores instead of letting macOS park it on efficiency + * cores whenever the host is busy or the window is in the background. */ + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0); +#endif force_rcu.notify = rr_force_rcu; rcu_add_force_rcu_notifier(&force_rcu); tcg_register_thread(); From 60dd2ede0245b0182438f39763fc60ea7b4b855e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:15:51 +0100 Subject: [PATCH 06/14] tcg: remember this thread's JIT write-protect state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Switching the JIT mapping between writable and executable costs an "isb sy", a full pipeline resynchronisation. qemu_thread_jit_execute() runs before every translated block is entered, while writes happen only when code is generated or patched, so the overwhelming majority of those switches ask for a state the thread is already in. The cache must be one variable shared by every translation unit. As a static __thread in the header each file got its own copy, so one file's idea of the state let another skip a switch it actually needed -- which did not boot at all. It is declared extern here and defined once in qemu-thread-posix.c. Part of a change measured at +5.7% on a paired A/B (52.0 -> 55.0 fps). Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Default-on, Apple JIT hosts only. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- include/tcg/tcg-apple-jit.h | 18 ++++++++++++++++-- util/qemu-thread-posix.c | 6 ++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/include/tcg/tcg-apple-jit.h b/include/tcg/tcg-apple-jit.h index 7f25dab809a34..fe2c8d55731fa 100644 --- a/include/tcg/tcg-apple-jit.h +++ b/include/tcg/tcg-apple-jit.h @@ -83,17 +83,31 @@ static __attribute__((__always_inline__)) void jit_write_protect(int enabled) #endif +/* + * Switching the JIT mapping between writable and executable costs an + * "isb sy" -- a full pipeline resynchronisation. qemu_thread_jit_execute() + * runs before every translated block is entered, while writes happen only + * when code is generated or patched, so remember which state this thread is + * already in and skip the switch (and the barrier) when nothing changes. + * The APRR state is per-thread, so the cache is too -- and it must be a + * single variable shared by every translation unit, or one file's idea of + * the state would let another skip a switch it actually needed. + */ +extern __thread int qemu_jit_wx_state; + static inline void qemu_thread_jit_execute(void) { - if (jit_write_protect_supported()) { + if (qemu_jit_wx_state != 1 && jit_write_protect_supported()) { jit_write_protect(true); + qemu_jit_wx_state = 1; } } static inline void qemu_thread_jit_write(void) { - if (jit_write_protect_supported()) { + if (qemu_jit_wx_state != 0 && jit_write_protect_supported()) { jit_write_protect(false); + qemu_jit_wx_state = 0; } } diff --git a/util/qemu-thread-posix.c b/util/qemu-thread-posix.c index b2e26e21205b6..bed513f0a419c 100644 --- a/util/qemu-thread-posix.c +++ b/util/qemu-thread-posix.c @@ -16,6 +16,12 @@ #include "qemu/notify.h" #include "qemu-thread-common.h" #include "qemu/tsan.h" + +/* + * Which way the JIT mapping is currently switched on this thread, for + * tcg-apple-jit.h. Defined once so every translation unit shares it. + */ +__thread int qemu_jit_wx_state = -1; #include "qemu/bitmap.h" #ifdef CONFIG_PTHREAD_SET_NAME_NP From 6ae34c5644307ca8c7099cf889ffb7478e8b50aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:16:36 +0100 Subject: [PATCH 07/14] target/ppc: expand lmw/stmw inline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expand lmw/stmw as word loads and stores instead of a helper that probes the whole range first. Compilers emit them in most prologues and epilogues, so the helper call was frequent. A fault part-way through restarts the instruction with some registers already loaded or some words already stored, which the architecture allows; the address lives in a temporary, so rA inside the range is harmless. Little-endian mode still raises the alignment exception before this code. Only the lmw/stmw part of the original change is taken; the host-FPU fast path and the user fault watch from the same commit are not. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Default-on; no switch. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- target/ppc/translate.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/target/ppc/translate.c b/target/ppc/translate.c index eb2709257fc6d..29b8601c90b0e 100644 --- a/target/ppc/translate.c +++ b/target/ppc/translate.c @@ -2784,7 +2784,6 @@ GEN_STX(stwbr, st32r, 0x16, 0x14, PPC_INTEGER); static void gen_lmw(DisasContext *ctx) { TCGv t0; - TCGv_i32 t1; if (ctx->le_mode) { gen_align_no_le(ctx); @@ -2792,16 +2791,27 @@ static void gen_lmw(DisasContext *ctx) } gen_set_access_type(ctx, ACCESS_INT); t0 = tcg_temp_new(); - t1 = tcg_constant_i32(rD(ctx->opcode)); gen_addr_imm_index(ctx, t0, 0); - gen_helper_lmw(tcg_env, t0, t1); + /* + * Expand inline: each word goes through the TLB fast path instead of a + * helper that probes the whole range first. Apple's and Metrowerks' + * compilers emit lmw/stmw in most prologues and epilogues. A fault + * part-way through restarts the instruction with some registers already + * loaded, which the architecture allows; the address lives in a + * temporary, so rA in the range is harmless. + */ + for (int r = rD(ctx->opcode); r < 32; r++) { + tcg_gen_qemu_ld_tl(cpu_gpr[r], t0, ctx->mem_idx, DEF_MEMOP(MO_UL)); + if (r < 31) { + gen_addr_add(ctx, t0, t0, 4); + } + } } /* stmw */ static void gen_stmw(DisasContext *ctx) { TCGv t0; - TCGv_i32 t1; if (ctx->le_mode) { gen_align_no_le(ctx); @@ -2809,9 +2819,14 @@ static void gen_stmw(DisasContext *ctx) } gen_set_access_type(ctx, ACCESS_INT); t0 = tcg_temp_new(); - t1 = tcg_constant_i32(rS(ctx->opcode)); gen_addr_imm_index(ctx, t0, 0); - gen_helper_stmw(tcg_env, t0, t1); + /* Inline, as for lmw. */ + for (int r = rS(ctx->opcode); r < 32; r++) { + tcg_gen_qemu_st_tl(cpu_gpr[r], t0, ctx->mem_idx, DEF_MEMOP(MO_UL)); + if (r < 31) { + gen_addr_add(ctx, t0, t0, 4); + } + } } /*** Integer load and store strings ***/ From 8caf096456879ddef5c60693022852edc6e9cde0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:17:07 +0100 Subject: [PATCH 08/14] target/ppc: AltiVec permutes on host NEON, float helpers on the host FPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AltiVec's byte permutes went through out-of-line helpers that loop over bytes, and QuickTime's decoders lean on them heavily. tcg: new optional vector op tbl_vec, a two-register byte table lookup (index 0-15 from a, 16-31 from b, else 0). The AArch64 backend emits it as MOVI/EOR/TBL/TBX. Other hosts don't have it and keep the helpers. target/ppc: with tbl_vec, vperm, vsldoi, vmrgh/l[bhw], vpku[hw]um, the saturating packs (VSCR[SAT] kept), vupk[hl]s[bh] are shuffles. The even/odd multiplies vmul[eo][us][bh] and the modulo multiply-sums vmsum{ubm,mbm,uhm,shm} are shifts and vector multiplies. int_helper: on AArch64 hosts vaddfp, vsubfp, vmaxfp, vminfp, vmaddfp, vnmsubfp, vrefp, vrsqrtefp, vcf[su]x and vct[su]xs compute with NEON when every input and result lane is normal or zero (where IEEE and softfloat agree bit for bit), else fall back to softfloat. tests/ppc-vmx/run.py runs a bare-metal mac99 image that checks every converted op against scalar references (188000 checks) and times them: vperm ~6x, merges/sldoi/packs ~4x and vmaddfp ~3x faster, net of loop overhead. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Default-on, AArch64 hosts only; other hosts keep the existing helpers. The lane-wise float helpers fall back to softfloat unless every input and result lane is normal or zero. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- include/tcg/tcg-op-common.h | 1 + include/tcg/tcg-opc.h | 2 + target/ppc/int_helper.c | 209 ++++++++- target/ppc/translate/vmx-impl.c.inc | 429 +++++++++++++++++-- tcg/aarch64/tcg-target-has.h | 1 + tcg/aarch64/tcg-target.c.inc | 29 ++ tcg/tcg-has.h | 3 + tcg/tcg-op-vec.c | 22 + tcg/tcg.c | 3 + tests/ppc-vmx/link.ld | 10 + tests/ppc-vmx/run.py | 128 ++++++ tests/ppc-vmx/start.S | 13 + tests/ppc-vmx/vmx_test.c | 642 ++++++++++++++++++++++++++++ 13 files changed, 1447 insertions(+), 45 deletions(-) create mode 100644 tests/ppc-vmx/link.ld create mode 100755 tests/ppc-vmx/run.py create mode 100644 tests/ppc-vmx/start.S create mode 100644 tests/ppc-vmx/vmx_test.c diff --git a/include/tcg/tcg-op-common.h b/include/tcg/tcg-op-common.h index c67c2844ca01a..85f645ad6fed5 100644 --- a/include/tcg/tcg-op-common.h +++ b/include/tcg/tcg-op-common.h @@ -460,6 +460,7 @@ void tcg_gen_cmp_vec(TCGCond cond, unsigned vece, TCGv_vec r, void tcg_gen_bitsel_vec(unsigned vece, TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec c); +void tcg_gen_tbl_vec(TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec idx); void tcg_gen_cmpsel_vec(TCGCond cond, unsigned vece, TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec c, TCGv_vec d); diff --git a/include/tcg/tcg-opc.h b/include/tcg/tcg-opc.h index 9f73771149b48..8b702fb5fff9c 100644 --- a/include/tcg/tcg-opc.h +++ b/include/tcg/tcg-opc.h @@ -272,6 +272,8 @@ DEF(cmp_vec, 1, 2, 1, TCG_OPF_VECTOR) DEF(bitsel_vec, 1, 3, 0, TCG_OPF_VECTOR) DEF(cmpsel_vec, 1, 4, 1, TCG_OPF_VECTOR) +/* r[i] = idx[i] < 16 ? a[idx[i]] : idx[i] < 32 ? b[idx[i] - 16] : 0 */ +DEF(tbl_vec, 1, 3, 0, TCG_OPF_VECTOR) DEF(last_generic, 0, 0, 0, TCG_OPF_NOT_PRESENT) diff --git a/target/ppc/int_helper.c b/target/ppc/int_helper.c index ef4b2e75d60c0..0b9c3f267b169 100644 --- a/target/ppc/int_helper.c +++ b/target/ppc/int_helper.c @@ -504,34 +504,200 @@ void helper_VPRTYBQ(ppc_avr_t *r, ppc_avr_t *b, uint32_t v) r->VsrD(0) = 0; } -#define VARITHFP(suffix, func) \ +/* + * Host-FPU fast paths for the AltiVec float ops. + * + * AltiVec float arithmetic always rounds to nearest and raises no + * exceptions the guest can see, so when every input and result lane is + * normal or zero the host's IEEE arithmetic gives the same bits as + * softfloat. NaNs, infinities and denormals (whose handling depends on + * VSCR[NJ] and on PPC's NaN rules) fall back to softfloat. This assumes + * the host FPU is in its default mode (round to nearest, no flush to + * zero, NaN propagation on), as softfloat's own hardfloat path does. + */ +#if defined(__aarch64__) +#include + +/* Every lane normal or zero: no NaN, infinity or denormal. */ +static inline bool vfp_all_zon(float32x4_t v) +{ + uint32x4_t u = vreinterpretq_u32_f32(v); + uint32x4_t e = vandq_u32(u, vdupq_n_u32(0x7f800000)); + uint32x4_t special = vceqq_u32(e, vdupq_n_u32(0x7f800000)); + uint32x4_t denormal = vandq_u32(vceqzq_u32(e), + vtstq_u32(u, vdupq_n_u32(0x007fffff))); + + return vmaxvq_u32(vorrq_u32(special, denormal)) == 0; +} + +static inline float32x4_t vfp_ld(ppc_avr_t *v) +{ + return vreinterpretq_f32_u32(vld1q_u32(v->u32)); +} + +static inline bool vfp_st_checked(ppc_avr_t *r, float32x4_t x) +{ + if (!vfp_all_zon(x)) { + return false; + } + vst1q_u32(r->u32, vreinterpretq_u32_f32(x)); + return true; +} + +enum { VFP_ADD, VFP_SUB, VFP_MIN, VFP_MAX, VFP_MADD, VFP_NMSUB, + VFP_RE, VFP_RSQRTE }; + +/* r = op(a, b[, c]); false (r untouched) when softfloat must decide. */ +static inline bool vfp_fast(int op, ppc_avr_t *r, ppc_avr_t *a, + ppc_avr_t *b, ppc_avr_t *c) +{ + float32x4_t fa = vfp_ld(a), fb, fc, x; + + if (!vfp_all_zon(fa)) { + return false; + } + switch (op) { + case VFP_RE: + return vfp_st_checked(r, vdivq_f32(vdupq_n_f32(1.0f), fa)); + case VFP_RSQRTE: + return vfp_st_checked(r, vdivq_f32(vdupq_n_f32(1.0f), vsqrtq_f32(fa))); + } + fb = vfp_ld(b); + if (!vfp_all_zon(fb)) { + return false; + } + switch (op) { + case VFP_ADD: + x = vaddq_f32(fa, fb); + break; + case VFP_SUB: + x = vsubq_f32(fa, fb); + break; + case VFP_MIN: + x = vminq_f32(fa, fb); + break; + case VFP_MAX: + x = vmaxq_f32(fa, fb); + break; + default: + fc = vfp_ld(c); + if (!vfp_all_zon(fc)) { + return false; + } + if (op == VFP_MADD) { + x = vfmaq_f32(fb, fa, fc); /* a * c + b */ + } else { + x = vnegq_f32(vfmaq_f32(vnegq_f32(fb), fa, fc)); /* -(a*c - b) */ + } + break; + } + return vfp_st_checked(r, x); +} + +/* vcfux/vcfsx: r = (float)b / 2^uim. */ +static inline bool vfp_fast_cf(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim, + bool sign) +{ + float32x4_t x = sign ? vcvtq_f32_s32(vld1q_s32(b->s32)) + : vcvtq_f32_u32(vld1q_u32(b->u32)); + float32x4_t scale = vreinterpretq_f32_u32(vdupq_n_u32((127 - uim) << 23)); + + return vfp_st_checked(r, vmulq_f32(x, scale)); +} + +/* vctuxs/vctsxs: r = saturate(trunc(b * 2^uim)), noting saturation. */ +static inline bool vfp_fast_ct(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim, + bool sign, int *sat) +{ + float32x4_t fb = vfp_ld(b); + float64x2_t scale = vreinterpretq_f64_u64( + vdupq_n_u64((uint64_t)(1023 + uim) << 52)); + int64x2_t lo, hi; + uint32x4_t res; + uint64x2_t back_lo, back_hi; + + if (!vfp_all_zon(fb)) { + return false; + } + /* Exact in double; the conversion truncates and saturates to 64 bits. */ + lo = vcvtq_s64_f64(vmulq_f64(vcvt_f64_f32(vget_low_f32(fb)), scale)); + hi = vcvtq_s64_f64(vmulq_f64(vcvt_high_f64_f32(fb), scale)); + if (sign) { + int32x4_t n = vcombine_s32(vqmovn_s64(lo), vqmovn_s64(hi)); + back_lo = vreinterpretq_u64_s64(vmovl_s32(vget_low_s32(n))); + back_hi = vreinterpretq_u64_s64(vmovl_high_s32(n)); + res = vreinterpretq_u32_s32(n); + } else { + res = vcombine_u32(vqmovun_s64(lo), vqmovun_s64(hi)); + back_lo = vmovl_u32(vget_low_u32(res)); + back_hi = vmovl_high_u32(res); + } + if (vmaxvq_u32(vreinterpretq_u32_u64( + vorrq_u64(veorq_u64(back_lo, vreinterpretq_u64_s64(lo)), + veorq_u64(back_hi, vreinterpretq_u64_s64(hi)))))) { + *sat = 1; + } + vst1q_u32(r->u32, res); + return true; +} +#else +enum { VFP_ADD, VFP_SUB, VFP_MIN, VFP_MAX, VFP_MADD, VFP_NMSUB, + VFP_RE, VFP_RSQRTE }; + +static inline bool vfp_fast(int op, ppc_avr_t *r, ppc_avr_t *a, + ppc_avr_t *b, ppc_avr_t *c) +{ + return false; +} + +static inline bool vfp_fast_cf(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim, + bool sign) +{ + return false; +} + +static inline bool vfp_fast_ct(ppc_avr_t *r, ppc_avr_t *b, uint32_t uim, + bool sign, int *sat) +{ + return false; +} +#endif + +#define VARITHFP(suffix, func, fast_op) \ void helper_v##suffix(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, \ ppc_avr_t *b) \ { \ int i; \ \ + if (vfp_fast(fast_op, r, a, b, NULL)) { \ + return; \ + } \ for (i = 0; i < ARRAY_SIZE(r->f32); i++) { \ r->f32[i] = func(a->f32[i], b->f32[i], &env->vec_status); \ } \ } -VARITHFP(addfp, float32_add) -VARITHFP(subfp, float32_sub) -VARITHFP(minfp, float32_min) -VARITHFP(maxfp, float32_max) +VARITHFP(addfp, float32_add, VFP_ADD) +VARITHFP(subfp, float32_sub, VFP_SUB) +VARITHFP(minfp, float32_min, VFP_MIN) +VARITHFP(maxfp, float32_max, VFP_MAX) #undef VARITHFP -#define VARITHFPFMA(suffix, type) \ +#define VARITHFPFMA(suffix, type, fast_op) \ void helper_v##suffix(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, \ ppc_avr_t *b, ppc_avr_t *c) \ { \ int i; \ + if (vfp_fast(fast_op, r, a, b, c)) { \ + return; \ + } \ for (i = 0; i < ARRAY_SIZE(r->f32); i++) { \ r->f32[i] = float32_muladd(a->f32[i], c->f32[i], b->f32[i], \ type, &env->vec_status); \ } \ } -VARITHFPFMA(maddfp, 0); -VARITHFPFMA(nmsubfp, float_muladd_negate_result | float_muladd_negate_c); +VARITHFPFMA(maddfp, 0, VFP_MADD); +VARITHFPFMA(nmsubfp, float_muladd_negate_result | float_muladd_negate_c, + VFP_NMSUB); #undef VARITHFPFMA #define VARITHSAT_CASE(type, op, cvt, element) \ @@ -612,19 +778,22 @@ VABSDU(VABSDUH, u16) VABSDU(VABSDUW, u32) #undef VABSDU -#define VCF(suffix, cvt, element) \ +#define VCF(suffix, cvt, element, sign) \ void helper_vcf##suffix(CPUPPCState *env, ppc_avr_t *r, \ ppc_avr_t *b, uint32_t uim) \ { \ int i; \ \ + if (vfp_fast_cf(r, b, uim, sign)) { \ + return; \ + } \ for (i = 0; i < ARRAY_SIZE(r->f32); i++) { \ float32 t = cvt(b->element[i], &env->vec_status); \ r->f32[i] = float32_scalbn(t, -uim, &env->vec_status); \ } \ } -VCF(ux, uint32_to_float32, u32) -VCF(sx, int32_to_float32, s32) +VCF(ux, uint32_to_float32, u32, false) +VCF(sx, int32_to_float32, s32, true) #undef VCF #define VCMPNEZ(NAME, ELEM) \ @@ -717,7 +886,7 @@ void helper_vcmpbfp_dot(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, vcmpbfp_internal(env, r, a, b, 1); } -#define VCT(suffix, satcvt, element) \ +#define VCT(suffix, satcvt, element, sign) \ void helper_vct##suffix(CPUPPCState *env, ppc_avr_t *r, \ ppc_avr_t *b, uint32_t uim) \ { \ @@ -725,6 +894,12 @@ void helper_vcmpbfp_dot(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, int sat = 0; \ float_status s = env->vec_status; \ \ + if (vfp_fast_ct(r, b, uim, sign, &sat)) { \ + if (sat) { \ + set_vscr_sat(env); \ + } \ + return; \ + } \ set_float_rounding_mode(float_round_to_zero, &s); \ for (i = 0; i < ARRAY_SIZE(r->f32); i++) { \ if (float32_is_any_nan(b->f32[i])) { \ @@ -742,8 +917,8 @@ void helper_vcmpbfp_dot(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *a, set_vscr_sat(env); \ } \ } -VCT(uxs, cvtsduw, u32) -VCT(sxs, cvtsdsw, s32) +VCT(uxs, cvtsduw, u32, false) +VCT(sxs, cvtsdsw, s32, true) #undef VCT typedef int64_t do_ger(uint32_t, uint32_t, uint32_t); @@ -1527,6 +1702,9 @@ void helper_vrefp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *b) { int i; + if (vfp_fast(VFP_RE, r, b, NULL, NULL)) { + return; + } for (i = 0; i < ARRAY_SIZE(r->f32); i++) { r->f32[i] = float32_div(float32_one, b->f32[i], &env->vec_status); } @@ -1554,6 +1732,9 @@ void helper_vrsqrtefp(CPUPPCState *env, ppc_avr_t *r, ppc_avr_t *b) { int i; + if (vfp_fast(VFP_RSQRTE, r, b, NULL, NULL)) { + return; + } for (i = 0; i < ARRAY_SIZE(r->f32); i++) { float32 t = float32_sqrt(b->f32[i], &env->vec_status); diff --git a/target/ppc/translate/vmx-impl.c.inc b/target/ppc/translate/vmx-impl.c.inc index 92d6e8c6032b8..810e05c48da27 100644 --- a/target/ppc/translate/vmx-impl.c.inc +++ b/target/ppc/translate/vmx-impl.c.inc @@ -34,6 +34,84 @@ static inline void set_avr_full(int regno, TCGv_i128 src) tcg_gen_st_i128(src, tcg_env, avr_full_offset(regno)); } +/* + * Byte shuffles on the host's vector unit. + * + * AltiVec's permutes (vperm, vsldoi, merges, packs, unpacks) otherwise go + * through out-of-line helpers that loop over bytes. Where the host can + * do a two-register table lookup (tbl_vec; TBL/TBX on AArch64 NEON) they + * become a few inline instructions instead. + * + * A vector register is held in host byte order: on a little-endian host, + * host byte j of the register is PPC (big-endian) byte 15 - j. A PPC + * permute picking byte s (0-15 from vA, 16-31 from vB) for result byte i + * is therefore a lookup, for host byte j, of index 31 - s into the table + * (vB, vA), where s is the pick for PPC byte 15 - j. + */ +#if !HOST_BIG_ENDIAN +static bool vmx_host_tbl(void) +{ + return tcg_can_emit_vec_op(INDEX_op_tbl_vec, TCG_TYPE_V128, MO_8) > 0; +} +#else +static bool vmx_host_tbl(void) +{ + return false; +} +#endif + +/* Turn a PPC byte pick list s0..s15 into a host-order tbl index vector. */ +#define VMX_PICK(s0, s1, s2, s3, s4, s5, s6, s7, \ + s8, s9, s10, s11, s12, s13, s14, s15) \ + { 31 - (s15), 31 - (s14), 31 - (s13), 31 - (s12), \ + 31 - (s11), 31 - (s10), 31 - (s9), 31 - (s8), \ + 31 - (s7), 31 - (s6), 31 - (s5), 31 - (s4), \ + 31 - (s3), 31 - (s2), 31 - (s1), 31 - (s0) } +#define VMX_PICK_LIST(...) VMX_PICK(__VA_ARGS__) + +static TCGv_vec vmx_ld(int reg) +{ + TCGv_vec v = tcg_temp_new_vec(TCG_TYPE_V128); + tcg_gen_ld_vec(v, tcg_env, avr_full_offset(reg)); + return v; +} + +static void vmx_st(int reg, TCGv_vec v) +{ + tcg_gen_st_vec(v, tcg_env, avr_full_offset(reg)); +} + +/* A constant 16-byte vector from host memory (tables are static). */ +static TCGv_vec vmx_ld_const(const uint8_t *table) +{ + TCGv_vec v = tcg_temp_new_vec(TCG_TYPE_V128); + tcg_gen_ld_vec(v, tcg_constant_ptr(table), 0); + return v; +} + +/* PPC permute of (a, b) by the index vector idx (see above). */ +static TCGv_vec vmx_permute(TCGv_vec a, TCGv_vec b, TCGv_vec idx) +{ + TCGv_vec r = tcg_temp_new_vec(TCG_TYPE_V128); + tcg_gen_tbl_vec(r, b, a, idx); + return r; +} + +/* vD = the fixed permute table of vA and vB. */ +static void gen_vmx_shuffle(int rd, int ra, int rb, const uint8_t *table) +{ + vmx_st(rd, vmx_permute(vmx_ld(ra), vmx_ld(rb), vmx_ld_const(table))); +} + +/* OR a nonzero-if-saturated vector into VSCR[SAT]. */ +static void vmx_accumulate_sat(TCGv_vec x) +{ + TCGv_vec sat = tcg_temp_new_vec(TCG_TYPE_V128); + tcg_gen_ld_vec(sat, tcg_env, offsetof(CPUPPCState, vscr_sat)); + tcg_gen_or_vec(MO_8, sat, sat, x); + tcg_gen_st_vec(sat, tcg_env, offsetof(CPUPPCState, vscr_sat)); +} + static bool trans_LVX(DisasContext *ctx, arg_X *a) { TCGv EA; @@ -350,12 +428,40 @@ GEN_VXFORM_V(vsububm, MO_8, tcg_gen_gvec_sub, 0, 16); GEN_VXFORM_V(vsubuhm, MO_16, tcg_gen_gvec_sub, 0, 17); GEN_VXFORM_V(vsubuwm, MO_32, tcg_gen_gvec_sub, 0, 18); GEN_VXFORM_V(vsubudm, MO_64, tcg_gen_gvec_sub, 0, 19); -GEN_VXFORM(vmrghb, 6, 0); -GEN_VXFORM(vmrghh, 6, 1); -GEN_VXFORM(vmrghw, 6, 2); -GEN_VXFORM(vmrglb, 6, 4); -GEN_VXFORM(vmrglh, 6, 5); -GEN_VXFORM(vmrglw, 6, 6); +/* A fixed byte shuffle inline when the host can, else the helper. */ +#define GEN_VXFORM_SHUFFLE(name, helper_args, ...) \ +static void glue(gen_, name)(DisasContext *ctx) \ +{ \ + static const uint8_t table[16] QEMU_ALIGNED(16) = \ + VMX_PICK(__VA_ARGS__); \ + TCGv_ptr ra, rb, rd; \ + if (unlikely(!ctx->altivec_enabled)) { \ + gen_exception(ctx, POWERPC_EXCP_VPU); \ + return; \ + } \ + if (vmx_host_tbl()) { \ + gen_vmx_shuffle(rD(ctx->opcode), rA(ctx->opcode), \ + rB(ctx->opcode), table); \ + return; \ + } \ + ra = gen_avr_ptr(rA(ctx->opcode)); \ + rb = gen_avr_ptr(rB(ctx->opcode)); \ + rd = gen_avr_ptr(rD(ctx->opcode)); \ + gen_helper_##name helper_args; \ +} + +GEN_VXFORM_SHUFFLE(vmrghb, (rd, ra, rb), + 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23); +GEN_VXFORM_SHUFFLE(vmrghh, (rd, ra, rb), + 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23); +GEN_VXFORM_SHUFFLE(vmrghw, (rd, ra, rb), + 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23); +GEN_VXFORM_SHUFFLE(vmrglb, (rd, ra, rb), + 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31); +GEN_VXFORM_SHUFFLE(vmrglh, (rd, ra, rb), + 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31); +GEN_VXFORM_SHUFFLE(vmrglw, (rd, ra, rb), + 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31); static void trans_vmrgew(DisasContext *ctx) { @@ -1057,17 +1163,81 @@ TRANS(VRLQMI, do_vector_rotl_quad, false, true) GEN_VXFORM_TRANS(vsl, 2, 7); GEN_VXFORM_TRANS(vsr, 2, 11); -GEN_VXFORM_ENV(vpkuhum, 7, 0); -GEN_VXFORM_ENV(vpkuwum, 7, 1); +#define VMX_PACK_H 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 +#define VMX_PACK_W 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 + +GEN_VXFORM_SHUFFLE(vpkuhum, (tcg_env, rd, ra, rb), VMX_PACK_H); +GEN_VXFORM_SHUFFLE(vpkuwum, (tcg_env, rd, ra, rb), VMX_PACK_W); GEN_VXFORM_ENV(vpkudum, 7, 17); -GEN_VXFORM_ENV(vpkuhus, 7, 2); -GEN_VXFORM_ENV(vpkuwus, 7, 3); + +/* + * Saturating packs: clamp each element of vA and vB to the narrower + * range (noting in VSCR[SAT] any that changed), then pack as above. + */ +static void gen_vmx_pack_sat(DisasContext *ctx, unsigned vece, bool sign_in, + int64_t lo, int64_t hi) +{ + static const uint8_t pack_h[16] QEMU_ALIGNED(16) = VMX_PICK_LIST(VMX_PACK_H); + static const uint8_t pack_w[16] QEMU_ALIGNED(16) = VMX_PICK_LIST(VMX_PACK_W); + static const TCGOpcode vecop_list[] = { + INDEX_op_smax_vec, INDEX_op_smin_vec, INDEX_op_umin_vec, 0 + }; + const TCGOpcode *hold_list = tcg_swap_vecop_list(vecop_list); + TCGv_vec in[2], sat, x; + int i; + + in[0] = vmx_ld(rA(ctx->opcode)); + in[1] = vmx_ld(rB(ctx->opcode)); + sat = tcg_temp_new_vec(TCG_TYPE_V128); + x = tcg_temp_new_vec(TCG_TYPE_V128); + tcg_gen_dupi_vec(MO_8, sat, 0); + for (i = 0; i < 2; i++) { + if (sign_in) { + tcg_gen_smax_vec(vece, x, in[i], + tcg_constant_vec(TCG_TYPE_V128, vece, lo)); + tcg_gen_smin_vec(vece, x, x, + tcg_constant_vec(TCG_TYPE_V128, vece, hi)); + } else { + tcg_gen_umin_vec(vece, x, in[i], + tcg_constant_vec(TCG_TYPE_V128, vece, hi)); + } + tcg_gen_xor_vec(vece, in[i], in[i], x); + tcg_gen_or_vec(vece, sat, sat, in[i]); + tcg_gen_mov_vec(in[i], x); + } + vmx_accumulate_sat(sat); + vmx_st(rD(ctx->opcode), + vmx_permute(in[0], in[1], + vmx_ld_const(vece == MO_16 ? pack_h : pack_w))); + tcg_swap_vecop_list(hold_list); +} + +#define GEN_VXFORM_PACK_SAT(name, vece, sign_in, lo, hi) \ +static void glue(gen_, name)(DisasContext *ctx) \ +{ \ + TCGv_ptr ra, rb, rd; \ + if (unlikely(!ctx->altivec_enabled)) { \ + gen_exception(ctx, POWERPC_EXCP_VPU); \ + return; \ + } \ + if (vmx_host_tbl()) { \ + gen_vmx_pack_sat(ctx, vece, sign_in, lo, hi); \ + return; \ + } \ + ra = gen_avr_ptr(rA(ctx->opcode)); \ + rb = gen_avr_ptr(rB(ctx->opcode)); \ + rd = gen_avr_ptr(rD(ctx->opcode)); \ + gen_helper_##name(tcg_env, rd, ra, rb); \ +} + +GEN_VXFORM_PACK_SAT(vpkuhus, MO_16, false, 0, 0xff); +GEN_VXFORM_PACK_SAT(vpkuwus, MO_32, false, 0, 0xffff); GEN_VXFORM_ENV(vpkudus, 7, 19); -GEN_VXFORM_ENV(vpkshus, 7, 4); -GEN_VXFORM_ENV(vpkswus, 7, 5); +GEN_VXFORM_PACK_SAT(vpkshus, MO_16, true, 0, 0xff); +GEN_VXFORM_PACK_SAT(vpkswus, MO_32, true, 0, 0xffff); GEN_VXFORM_ENV(vpksdus, 7, 21); -GEN_VXFORM_ENV(vpkshss, 7, 6); -GEN_VXFORM_ENV(vpkswss, 7, 7); +GEN_VXFORM_PACK_SAT(vpkshss, MO_16, true, -0x80, 0x7f); +GEN_VXFORM_PACK_SAT(vpkswss, MO_32, true, -0x8000, 0x7fff); GEN_VXFORM_ENV(vpksdss, 7, 23); GEN_VXFORM(vpkpx, 7, 12); GEN_VXFORM_ENV(vsum4ubs, 4, 24); @@ -1432,11 +1602,44 @@ static void glue(gen_, name)(DisasContext *ctx) \ rb = gen_avr_ptr(rB(ctx->opcode)); \ gen_helper_##name(cpu_gpr[rD(ctx->opcode)], rb); \ } -GEN_VXFORM_NOA(vupkhsb, 7, 8); -GEN_VXFORM_NOA(vupkhsh, 7, 9); +/* + * Signed unpacks: move each source element into the top of its wider + * result element with a shuffle, then shift it down arithmetically. + */ +#define GEN_VXFORM_UNPACK(name, vece, ...) \ +static void glue(gen_, name)(DisasContext *ctx) \ +{ \ + static const uint8_t table[16] QEMU_ALIGNED(16) = \ + VMX_PICK(__VA_ARGS__); \ + TCGv_ptr rb, rd; \ + if (unlikely(!ctx->altivec_enabled)) { \ + gen_exception(ctx, POWERPC_EXCP_VPU); \ + return; \ + } \ + if (vmx_host_tbl()) { \ + static const TCGOpcode vecop_list[] = { INDEX_op_sari_vec, 0 }; \ + const TCGOpcode *hold_list = tcg_swap_vecop_list(vecop_list); \ + TCGv_vec b = vmx_ld(rB(ctx->opcode)); \ + TCGv_vec r = vmx_permute(b, b, vmx_ld_const(table)); \ + tcg_gen_sari_vec(vece, r, r, 4 << vece); \ + vmx_st(rD(ctx->opcode), r); \ + tcg_swap_vecop_list(hold_list); \ + return; \ + } \ + rb = gen_avr_ptr(rB(ctx->opcode)); \ + rd = gen_avr_ptr(rD(ctx->opcode)); \ + gen_helper_##name(rd, rb); \ +} + +GEN_VXFORM_UNPACK(vupkhsb, MO_16, + 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); +GEN_VXFORM_UNPACK(vupkhsh, MO_32, + 0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7); GEN_VXFORM_NOA(vupkhsw, 7, 25); -GEN_VXFORM_NOA(vupklsb, 7, 10); -GEN_VXFORM_NOA(vupklsh, 7, 11); +GEN_VXFORM_UNPACK(vupklsb, MO_16, + 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15); +GEN_VXFORM_UNPACK(vupklsh, MO_32, + 8, 9, 8, 9, 10, 11, 10, 11, 12, 13, 12, 13, 14, 15, 14, 15); GEN_VXFORM_NOA(vupklsw, 7, 27); GEN_VXFORM_NOA(vupkhpx, 7, 13); GEN_VXFORM_NOA(vupklpx, 7, 15); @@ -1889,6 +2092,21 @@ static void gen_vsldoi(DisasContext *ctx) } ra = gen_avr_ptr(rA(ctx->opcode)); rb = gen_avr_ptr(rB(ctx->opcode)); + if (vmx_host_tbl()) { + /* + * PPC byte i of the result is byte i + sh of vA:vB, so host + * byte j indexes 31 - (15 - j + sh) = 16 - sh + j: a window of + * an ascending sequence. + */ + static const uint8_t seq[32] QEMU_ALIGNED(16) = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 + }; + vmx_st(rD(ctx->opcode), + vmx_permute(vmx_ld(rA(ctx->opcode)), vmx_ld(rB(ctx->opcode)), + vmx_ld_const(&seq[16 - VSH(ctx->opcode)]))); + return; + } rd = gen_avr_ptr(rD(ctx->opcode)); sh = tcg_constant_i32(VSH(ctx->opcode)); gen_helper_vsldoi(rd, ra, rb, sh); @@ -2304,7 +2522,23 @@ TRANS_FLAGS2(ALTIVEC_207, VADDEUQM, do_va_helper, gen_helper_VADDEUQM) TRANS_FLAGS2(ALTIVEC_207, VSUBEUQM, do_va_helper, gen_helper_VSUBEUQM) TRANS_FLAGS2(ALTIVEC_207, VSUBECUQ, do_va_helper, gen_helper_VSUBECUQ) -TRANS_FLAGS(ALTIVEC, VPERM, do_va_helper, gen_helper_VPERM) +static bool trans_VPERM(DisasContext *ctx, arg_VA *a) +{ + TCGv_vec idx; + + REQUIRE_INSNS_FLAGS(ctx, ALTIVEC); + if (!vmx_host_tbl()) { + return do_va_helper(ctx, a, gen_helper_VPERM); + } + REQUIRE_VECTOR(ctx); + + /* The pick for each byte is the low 5 bits of vC; index 31 - s. */ + idx = vmx_ld(a->rc); + tcg_gen_andc_vec(MO_8, idx, tcg_constant_vec(TCG_TYPE_V128, MO_8, 0x1f), + idx); + vmx_st(a->vrt, vmx_permute(vmx_ld(a->vra), vmx_ld(a->vrb), idx)); + return true; +} TRANS_FLAGS2(ISA300, VPERMR, do_va_helper, gen_helper_VPERMR) static void gen_vmladduhm_vec(unsigned vece, TCGv_vec t, TCGv_vec a, TCGv_vec b, @@ -2349,10 +2583,117 @@ static bool trans_VSEL(DisasContext *ctx, arg_VA *a) return true; } -TRANS_FLAGS(ALTIVEC, VMSUMUBM, do_va_helper, gen_helper_VMSUMUBM) -TRANS_FLAGS(ALTIVEC, VMSUMMBM, do_va_helper, gen_helper_VMSUMMBM) -TRANS_FLAGS(ALTIVEC, VMSUMSHM, do_va_helper, gen_helper_VMSUMSHM) -TRANS_FLAGS(ALTIVEC, VMSUMUHM, do_va_helper, gen_helper_VMSUMUHM) +/* + * Products of the even or odd elements of a and b, each in an element of + * twice the width (vece). A PPC even element is the more significant + * half of the wider element, in either byte order. + */ +static TCGv_vec vmx_mul_eo(unsigned vece, TCGv_vec a, TCGv_vec b, bool even, + bool sign_a, bool sign_b) +{ + unsigned half = 4 << vece; + TCGv_vec in[2] = { a, b }; + bool sign[2] = { sign_a, sign_b }; + TCGv_vec x[2]; + int i; + + for (i = 0; i < 2; i++) { + x[i] = tcg_temp_new_vec(TCG_TYPE_V128); + if (even) { + if (sign[i]) { + tcg_gen_sari_vec(vece, x[i], in[i], half); + } else { + tcg_gen_shri_vec(vece, x[i], in[i], half); + } + } else if (sign[i]) { + tcg_gen_shli_vec(vece, x[i], in[i], half); + tcg_gen_sari_vec(vece, x[i], x[i], half); + } else { + tcg_gen_and_vec(vece, x[i], in[i], + tcg_constant_vec(TCG_TYPE_V128, vece, + MAKE_64BIT_MASK(0, half))); + } + } + tcg_gen_mul_vec(vece, x[0], x[0], x[1]); + return x[0]; +} + +static const TCGOpcode vmx_mul_list[] = { + INDEX_op_shli_vec, INDEX_op_shri_vec, INDEX_op_sari_vec, + INDEX_op_add_vec, INDEX_op_mul_vec, 0 +}; + +/* Inline even/odd multiplies need 16- and 32-bit vector multiplies. */ +static bool vmx_host_mul(void) +{ + return vmx_host_tbl() + && tcg_can_emit_vecop_list(vmx_mul_list, TCG_TYPE_V128, MO_16) + && tcg_can_emit_vecop_list(vmx_mul_list, TCG_TYPE_V128, MO_32); +} + +/* Add both halves of each 32-bit element of x, as 16-bit values, to acc. */ +static void vmx_add_halves(TCGv_vec acc, TCGv_vec x, bool sign) +{ + TCGv_vec t = tcg_temp_new_vec(TCG_TYPE_V128); + + if (sign) { + tcg_gen_sari_vec(MO_32, t, x, 16); + tcg_gen_add_vec(MO_32, acc, acc, t); + tcg_gen_shli_vec(MO_32, t, x, 16); + tcg_gen_sari_vec(MO_32, t, t, 16); + } else { + tcg_gen_shri_vec(MO_32, t, x, 16); + tcg_gen_add_vec(MO_32, acc, acc, t); + tcg_gen_and_vec(MO_32, t, x, + tcg_constant_vec(TCG_TYPE_V128, MO_32, 0xffff)); + } + tcg_gen_add_vec(MO_32, acc, acc, t); +} + +/* + * Modulo multiply-sums: vD.word = vC.word + the sum of the products of the + * byte (vece MO_16 products) or halfword (MO_32) elements in that word. + */ +static bool do_vmsum_mod(DisasContext *ctx, arg_VA *a, unsigned vece, + bool sign_a, bool sign_b, + void (*helper)(TCGv_ptr, TCGv_ptr, TCGv_ptr, + TCGv_ptr)) +{ + const TCGOpcode *hold_list; + TCGv_vec va, vb, acc, pe, po; + + if (!vmx_host_mul()) { + return do_va_helper(ctx, a, helper); + } + REQUIRE_VECTOR(ctx); + + hold_list = tcg_swap_vecop_list(vmx_mul_list); + va = vmx_ld(a->vra); + vb = vmx_ld(a->vrb); + acc = vmx_ld(a->rc); + pe = vmx_mul_eo(vece, va, vb, true, sign_a, sign_b); + po = vmx_mul_eo(vece, va, vb, false, sign_a, sign_b); + if (vece == MO_32) { + tcg_gen_add_vec(MO_32, acc, acc, pe); + tcg_gen_add_vec(MO_32, acc, acc, po); + } else { + /* A byte pair's sum can overflow 16 bits, so widen each product. */ + vmx_add_halves(acc, pe, sign_a || sign_b); + vmx_add_halves(acc, po, sign_a || sign_b); + } + vmx_st(a->vrt, acc); + tcg_swap_vecop_list(hold_list); + return true; +} + +TRANS_FLAGS(ALTIVEC, VMSUMUBM, do_vmsum_mod, MO_16, false, false, + gen_helper_VMSUMUBM) +TRANS_FLAGS(ALTIVEC, VMSUMMBM, do_vmsum_mod, MO_16, true, false, + gen_helper_VMSUMMBM) +TRANS_FLAGS(ALTIVEC, VMSUMSHM, do_vmsum_mod, MO_32, true, true, + gen_helper_VMSUMSHM) +TRANS_FLAGS(ALTIVEC, VMSUMUHM, do_vmsum_mod, MO_32, false, false, + gen_helper_VMSUMUHM) static bool do_va_env_helper(DisasContext *ctx, arg_VA *a, void (*gen_helper)(TCGv_ptr, TCGv_ptr, TCGv_ptr, TCGv_ptr, TCGv_ptr)) @@ -3085,14 +3426,40 @@ static bool trans_VMULLD(DisasContext *ctx, arg_VX *a) return true; } -TRANS_FLAGS(ALTIVEC, VMULESB, do_vx_helper, gen_helper_VMULESB) -TRANS_FLAGS(ALTIVEC, VMULOSB, do_vx_helper, gen_helper_VMULOSB) -TRANS_FLAGS(ALTIVEC, VMULEUB, do_vx_helper, gen_helper_VMULEUB) -TRANS_FLAGS(ALTIVEC, VMULOUB, do_vx_helper, gen_helper_VMULOUB) -TRANS_FLAGS(ALTIVEC, VMULESH, do_vx_helper, gen_helper_VMULESH) -TRANS_FLAGS(ALTIVEC, VMULOSH, do_vx_helper, gen_helper_VMULOSH) -TRANS_FLAGS(ALTIVEC, VMULEUH, do_vx_helper, gen_helper_VMULEUH) -TRANS_FLAGS(ALTIVEC, VMULOUH, do_vx_helper, gen_helper_VMULOUH) +static bool do_vx_vmul_eo(DisasContext *ctx, arg_VX *a, unsigned vece, + bool even, bool sign, + void (*helper)(TCGv_ptr, TCGv_ptr, TCGv_ptr)) +{ + const TCGOpcode *hold_list; + + if (!vmx_host_mul()) { + return do_vx_helper(ctx, a, helper); + } + REQUIRE_VECTOR(ctx); + + hold_list = tcg_swap_vecop_list(vmx_mul_list); + vmx_st(a->vrt, vmx_mul_eo(vece, vmx_ld(a->vra), vmx_ld(a->vrb), + even, sign, sign)); + tcg_swap_vecop_list(hold_list); + return true; +} + +TRANS_FLAGS(ALTIVEC, VMULESB, do_vx_vmul_eo, MO_16, true, true, + gen_helper_VMULESB) +TRANS_FLAGS(ALTIVEC, VMULOSB, do_vx_vmul_eo, MO_16, false, true, + gen_helper_VMULOSB) +TRANS_FLAGS(ALTIVEC, VMULEUB, do_vx_vmul_eo, MO_16, true, false, + gen_helper_VMULEUB) +TRANS_FLAGS(ALTIVEC, VMULOUB, do_vx_vmul_eo, MO_16, false, false, + gen_helper_VMULOUB) +TRANS_FLAGS(ALTIVEC, VMULESH, do_vx_vmul_eo, MO_32, true, true, + gen_helper_VMULESH) +TRANS_FLAGS(ALTIVEC, VMULOSH, do_vx_vmul_eo, MO_32, false, true, + gen_helper_VMULOSH) +TRANS_FLAGS(ALTIVEC, VMULEUH, do_vx_vmul_eo, MO_32, true, false, + gen_helper_VMULEUH) +TRANS_FLAGS(ALTIVEC, VMULOUH, do_vx_vmul_eo, MO_32, false, false, + gen_helper_VMULOUH) TRANS_FLAGS2(ALTIVEC_207, VMULESW, do_vx_helper, gen_helper_VMULESW) TRANS_FLAGS2(ALTIVEC_207, VMULOSW, do_vx_helper, gen_helper_VMULOSW) TRANS_FLAGS2(ALTIVEC_207, VMULEUW, do_vx_helper, gen_helper_VMULEUW) diff --git a/tcg/aarch64/tcg-target-has.h b/tcg/aarch64/tcg-target-has.h index 39f01c14cd882..dda1fcae5db6e 100644 --- a/tcg/aarch64/tcg-target-has.h +++ b/tcg/aarch64/tcg-target-has.h @@ -109,6 +109,7 @@ #define TCG_TARGET_HAS_bitsel_vec 1 #define TCG_TARGET_HAS_cmpsel_vec 0 #define TCG_TARGET_HAS_tst_vec 1 +#define TCG_TARGET_HAS_tbl_vec 1 #define TCG_TARGET_extract_valid(type, ofs, len) 1 #define TCG_TARGET_sextract_valid(type, ofs, len) 1 diff --git a/tcg/aarch64/tcg-target.c.inc b/tcg/aarch64/tcg-target.c.inc index 4645242d85ea4..9adadf389ea2c 100644 --- a/tcg/aarch64/tcg-target.c.inc +++ b/tcg/aarch64/tcg-target.c.inc @@ -628,6 +628,10 @@ typedef enum { I3616_UQSUB = 0x2e202c00, I3616_USHL = 0x2e204400, + /* AdvSIMD table lookup, one table register (len = 0). */ + I3616_TBL = 0x0e000000, + I3616_TBX = 0x0e001000, + /* AdvSIMD two-reg misc. */ I3617_CMGT0 = 0x0e208800, I3617_CMEQ0 = 0x0e209800, @@ -2831,6 +2835,28 @@ static void tcg_out_vec_op(TCGContext *s, TCGOpcode opc, } break; + case INDEX_op_tbl_vec: + /* + * Bytes 16-31 come from b by TBL on idx ^ 16 (indexes 0-15 map + * out of range there and give 0), then TBX fills in bytes 0-15 + * from a on idx itself (16 and up leave the byte alone). Built + * in TMP0 unless the output overlaps neither a nor idx. + */ + { + TCGReg d = (a0 != a1 && a0 != args[3]) ? a0 : TCG_VEC_TMP0; + + tcg_debug_assert(is_q); + tcg_out_dupi_vec(s, TCG_TYPE_V128, MO_8, TCG_VEC_TMP0, 16); + tcg_out_insn(s, 3616, EOR, 1, 0, TCG_VEC_TMP0, + args[3], TCG_VEC_TMP0); + tcg_out_insn(s, 3616, TBL, 1, 0, d, a2, TCG_VEC_TMP0); + tcg_out_insn(s, 3616, TBX, 1, 0, d, a1, args[3]); + if (d != a0) { + tcg_out_mov(s, type, a0, d); + } + } + break; + case INDEX_op_mov_vec: /* Always emitted via tcg_out_mov. */ case INDEX_op_dup_vec: /* Always emitted via tcg_out_dup_vec. */ default: @@ -2874,6 +2900,8 @@ int tcg_can_emit_vec_op(TCGOpcode opc, TCGType type, unsigned vece) case INDEX_op_umax_vec: case INDEX_op_umin_vec: return vece < MO_64; + case INDEX_op_tbl_vec: + return type == TCG_TYPE_V128 && vece == MO_8; default: return 0; @@ -3137,6 +3165,7 @@ tcg_target_op_def(TCGOpcode op, TCGType type, unsigned flags) case INDEX_op_cmp_vec: return C_O1_I2(w, w, wZ); case INDEX_op_bitsel_vec: + case INDEX_op_tbl_vec: return C_O1_I3(w, w, w, w); case INDEX_op_aa64_sli_vec: return C_O1_I2(w, 0, w); diff --git a/tcg/tcg-has.h b/tcg/tcg-has.h index 418e4673eb011..04089dd666f6d 100644 --- a/tcg/tcg-has.h +++ b/tcg/tcg-has.h @@ -88,6 +88,9 @@ #else #define TCG_TARGET_MAYBE_vec 1 #endif +#ifndef TCG_TARGET_HAS_tbl_vec +#define TCG_TARGET_HAS_tbl_vec 0 +#endif #ifndef TCG_TARGET_HAS_v64 #define TCG_TARGET_HAS_v64 0 #endif diff --git a/tcg/tcg-op-vec.c b/tcg/tcg-op-vec.c index 893d68e7d8050..3aa4c4edd9bc6 100644 --- a/tcg/tcg-op-vec.c +++ b/tcg/tcg-op-vec.c @@ -764,6 +764,28 @@ void tcg_gen_bitsel_vec(unsigned vece, TCGv_vec r, TCGv_vec a, } } +/* + * Two-register byte table lookup: r[i] = (a:b)[idx[i]] for idx[i] < 32, + * with a supplying bytes 0-15 and b bytes 16-31, and 0 for larger + * indexes. V128 only, and only where the host has it; callers check + * tcg_can_emit_vec_op(INDEX_op_tbl_vec, TCG_TYPE_V128, MO_8). + */ +void tcg_gen_tbl_vec(TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec idx) +{ + TCGTemp *rt = tcgv_vec_temp(r); + TCGTemp *at = tcgv_vec_temp(a); + TCGTemp *bt = tcgv_vec_temp(b); + TCGTemp *it = tcgv_vec_temp(idx); + + tcg_debug_assert(rt->base_type == TCG_TYPE_V128); + tcg_debug_assert(at->base_type == TCG_TYPE_V128); + tcg_debug_assert(bt->base_type == TCG_TYPE_V128); + tcg_debug_assert(it->base_type == TCG_TYPE_V128); + tcg_debug_assert(TCG_TARGET_HAS_tbl_vec); + vec_gen_4(INDEX_op_tbl_vec, TCG_TYPE_V128, MO_8, + temp_arg(rt), temp_arg(at), temp_arg(bt), temp_arg(it)); +} + void tcg_gen_cmpsel_vec(TCGCond cond, unsigned vece, TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec c, TCGv_vec d) { diff --git a/tcg/tcg.c b/tcg/tcg.c index fc933b1a7be58..f91b4c4146783 100644 --- a/tcg/tcg.c +++ b/tcg/tcg.c @@ -2420,6 +2420,9 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) return has_type && TCG_TARGET_HAS_bitsel_vec; case INDEX_op_cmpsel_vec: return has_type && TCG_TARGET_HAS_cmpsel_vec; + case INDEX_op_tbl_vec: + return type == TCG_TYPE_V128 && TCG_TARGET_HAS_v128 + && TCG_TARGET_HAS_tbl_vec; default: tcg_debug_assert(op > INDEX_op_last_generic && op < NB_OPS); diff --git a/tests/ppc-vmx/link.ld b/tests/ppc-vmx/link.ld new file mode 100644 index 0000000000000..0b7afa7dfb594 --- /dev/null +++ b/tests/ppc-vmx/link.ld @@ -0,0 +1,10 @@ +/* Raw mac99 firmware image: loaded at 0xfff00000, entered at +0x100. */ +ENTRY(_start) +SECTIONS +{ + . = 0xfff00000; + .head : { . += 0x100; KEEP(*(.text.start)) } + .text : { *(.text .text.*) } + .rodata : { *(.rodata .rodata.* .sdata2 .sdata2.*) } + /DISCARD/ : { *(.comment) *(.eh_frame) } +} diff --git a/tests/ppc-vmx/run.py b/tests/ppc-vmx/run.py new file mode 100755 index 0000000000000..bd38c1a63ae85 --- /dev/null +++ b/tests/ppc-vmx/run.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Build vmx_test.c as a raw mac99 firmware image, run it, report results. + +usage: run.py [path/to/qemu-system-ppc] + +Needs Homebrew llvm (clang with the PowerPC target) and lld. +""" +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +QEMU = (sys.argv[1] if len(sys.argv) > 1 else + os.path.join(HERE, '..', '..', 'build', 'qemu-system-ppc')) +RESULTS = 0x10000 +OPS = """vperm vperm(d=a) vperm(d=c) vperm(a=b) vsldoi vsldoi(d=b) +vmrghb vmrghh vmrghw vmrglb vmrglh vmrglw +vpkuhum vpkuwum vpkuhus vpkuwus vpkshus vpkswus vpkshss vpkswss +vupkhsb vupkhsh vupklsb vupklsh +vmuleub vmuloub vmulesb vmulosb vmuleuh vmulouh vmulesh vmulosh +vmsumubm vmsummbm vmsumuhm vmsumshm +vaddfp vsubfp vmaxfp vminfp vmaddfp vnmsubfp vrefp vcfsx vcfux vctsxs vctuxs +""".split() +BENCH = ['vperm x4', 'vmrghb/vmrglh/vsldoi/vpkuhum', + 'vmuleub/vmsumubm/vpkshus/vupkhsb', 'vaddubm x4 (always inline)', + 'vmaddfp x4 (float)'] + + +def tool(name): + for d in ('/opt/homebrew/opt/llvm/bin', '/usr/local/opt/llvm/bin'): + p = os.path.join(d, name) + if os.path.exists(p): + return p + p = shutil.which(name) + if not p: + sys.exit(f'{name} not found (brew install llvm lld)') + return p + + +def build(out): + cc = [tool('clang'), '--target=powerpc-unknown-none-elf', '-mcpu=7450', + '-maltivec', '-O2', '-ffreestanding', '-fno-builtin', '-nostdlib', + '-fno-pic', '-c'] + objs = [] + for src in ('start.S', 'vmx_test.c'): + o = os.path.join(out, src + '.o') + subprocess.check_call(cc + [os.path.join(HERE, src), '-o', o]) + objs.append(o) + elf = os.path.join(out, 'vmx_test.elf') + subprocess.check_call([tool('ld.lld'), '-T', os.path.join(HERE, 'link.ld'), + '-o', elf] + objs) + img = os.path.join(out, 'vmx_test.bin') + subprocess.check_call([tool('llvm-objcopy'), '-O', 'binary', elf, img]) + return img + + +class Monitor: + def __init__(self, path): + self.s = socket.socket(socket.AF_UNIX) + for _ in range(100): + try: + self.s.connect(path) + break + except OSError: + time.sleep(0.1) + self.read_prompt() + + def read_prompt(self): + buf = b'' + while not buf.endswith(b'(qemu) '): + chunk = self.s.recv(65536) + if not chunk: + break + buf += chunk + return buf.decode(errors='replace') + + def cmd(self, c): + self.s.sendall(c.encode() + b'\n') + return self.read_prompt() + + def words(self, addr, n): + out = self.cmd(f'xp /{n}wx {addr:#x}') + return [int(x, 16) for x in re.findall(r'0x([0-9a-f]{8})(?!:)', out)][:n] + + +def main(): + out = tempfile.mkdtemp(prefix='ppc-vmx-') + img = build(out) + sock = os.path.join(out, 'mon.sock') + q = subprocess.Popen([QEMU, '-M', 'mac99', '-cpu', '7450', '-m', '64', + '-bios', img, '-display', 'none', '-serial', 'none', + '-monitor', f'unix:{sock},server=on,wait=off'], + stdout=subprocess.DEVNULL) + try: + mon = Monitor(sock) + for _ in range(600): + if mon.words(RESULTS, 1) == [0x564d5854]: + break + time.sleep(0.25) + else: + sys.exit('test did not finish') + head = mon.words(RESULTS, 3 + len(OPS)) + checks, fails = head[1], head[2] + for name, n in zip(OPS, head[3:]): + if n: + print(f'FAIL {name}: {n} mismatches') + for k in range(min(fails, 8)): + p = mon.words(RESULTS + 0x100 + k * 96, 24) + it, gs, es = p[1] & 0xffff, (p[1] >> 16) & 0xff, p[1] >> 24 + vec = lambda i: ' '.join(f'{w:08x}' for w in p[i:i + 4]) + print(f' {OPS[p[0]]} #{it}: a={vec(4)} b={vec(8)} c={vec(12)}') + print(f' got={vec(16)} sat={gs} expected={vec(20)} sat={es}') + tbfreq = 25_000_000 # mac99 timebase (TBFREQ) + for name, t in zip(BENCH, mon.words(RESULTS + 0x800, len(BENCH))): + print(f'bench {name:36s} {t / tbfreq * 1e3:8.1f} ms') + print(f'{checks} checks, {fails} failures') + sys.exit(1 if fails else 0) + finally: + q.kill() + + +if __name__ == '__main__': + main() diff --git a/tests/ppc-vmx/start.S b/tests/ppc-vmx/start.S new file mode 100644 index 0000000000000..246f2a032770c --- /dev/null +++ b/tests/ppc-vmx/start.S @@ -0,0 +1,13 @@ +/* Reset entry: MSR[VEC] and MSR[FP] on, stack in RAM, call main, spin. */ + .section .text.start, "ax" + .globl _start +_start: + lis %r3, 0x0200 /* MSR_VEC */ + ori %r3, %r3, 0x2000 /* MSR_FP */ + mtmsr %r3 + isync + lis %r1, 0x0080 /* stack at 8 MB, real mode */ + li %r0, 0 + stwu %r0, -64(%r1) + bl main +1: b 1b diff --git a/tests/ppc-vmx/vmx_test.c b/tests/ppc-vmx/vmx_test.c new file mode 100644 index 0000000000000..9defd3348243f --- /dev/null +++ b/tests/ppc-vmx/vmx_test.c @@ -0,0 +1,642 @@ +/* + * Bare-metal AltiVec check for the inline (host vector) translations in + * target/ppc/translate/vmx-impl.c.inc (vperm, vsldoi, merges, packs, + * unpacks, even/odd multiplies, modulo multiply-sums) and the host-FPU + * fast paths of the float helpers in target/ppc/int_helper.c. + * + * Each op runs on random and edge-case inputs and is compared with a + * scalar reference (scalar integer and FPU code go through the ordinary, + * trusted TCG and softfloat paths). Results go to guest RAM at RESULTS for run.py to read: + * +0 magic 'VMXT' once finished + * +4 checks run +8 failures + * +12 failures per op (NOPS words) + * +0x100 first MAXLOG failures: op, iteration, a, b, c, got, expected + * +0x800 benchmark: timebase ticks per op for BENCH_ITERS iterations + * + * Built by run.py with clang --target=powerpc-unknown-none -maltivec. + */ +#include + +#define RESULTS 0x10000u +#define ITERS 4000 +#define MAXLOG 8 +#define BENCH_ITERS 2000000 + +typedef vector unsigned char vuc; + +typedef union { + vuc v; + uint8_t b[16]; + int8_t sb[16]; + uint16_t h[8]; + int16_t sh[8]; + uint32_t w[4]; + int32_t sw[4]; + float f[4]; +} V; + +#define FIRST_FP_OP OP_VADDFP + +enum { + OP_VPERM, OP_VPERM_DA, OP_VPERM_DC, OP_VPERM_AA, OP_VSLDOI, OP_VSLDOI_DB, + OP_VMRGHB, OP_VMRGHH, OP_VMRGHW, OP_VMRGLB, OP_VMRGLH, OP_VMRGLW, + OP_VPKUHUM, OP_VPKUWUM, OP_VPKUHUS, OP_VPKUWUS, OP_VPKSHUS, OP_VPKSWUS, + OP_VPKSHSS, OP_VPKSWSS, + OP_VUPKHSB, OP_VUPKHSH, OP_VUPKLSB, OP_VUPKLSH, + OP_VMULEUB, OP_VMULOUB, OP_VMULESB, OP_VMULOSB, + OP_VMULEUH, OP_VMULOUH, OP_VMULESH, OP_VMULOSH, + OP_VMSUMUBM, OP_VMSUMMBM, OP_VMSUMUHM, OP_VMSUMSHM, + OP_VADDFP, OP_VSUBFP, OP_VMAXFP, OP_VMINFP, OP_VMADDFP, OP_VNMSUBFP, + OP_VREFP, OP_VCFSX, OP_VCFUX, OP_VCTSXS, OP_VCTUXS, + NOPS +}; + +static volatile uint32_t *const res = (volatile uint32_t *)RESULTS; + +void *memcpy(void *d, const void *s, unsigned long n) +{ + uint8_t *dp = d; + const uint8_t *sp = s; + while (n--) { + *dp++ = *sp++; + } + return d; +} + +void *memset(void *d, int c, unsigned long n) +{ + uint8_t *dp = d; + while (n--) { + *dp++ = c; + } + return d; +} + +static uint32_t rnd(uint32_t *s) +{ + uint32_t x = *s; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + return *s = x; +} + +/* Random bytes, with an eighth of them edge values for the saturations. */ +static V rand_vec(uint32_t *s) +{ + static const uint8_t edge[8] = { 0, 1, 0x7f, 0x80, 0xff, 0xfe, 0x81, 0 }; + V r; + int i; + + for (i = 0; i < 16; i++) { + uint32_t x = rnd(s); + r.b[i] = (x & 7) == 0 ? edge[(x >> 3) & 7] : x >> 8; + } + return r; +} + +/* + * Random floats: mostly moderate exponents (the host fast path), some + * anything at all (overflow, NaN, infinity, denormal: softfloat), some + * zeros and small integers. + */ +static V rand_fvec(uint32_t *s) +{ + V r; + int i; + + for (i = 0; i < 4; i++) { + uint32_t x = rnd(s), y = rnd(s); + switch (y & 7) { + case 0: + r.w[i] = x; + break; + case 1: + r.w[i] = x & 0x80000000; + break; + case 2: + r.w[i] = x & 0x807fffff; /* denormal */ + break; + case 3: + r.sw[i] = (int32_t)x >> (y >> 27); /* integers for vcfsx */ + break; + default: + r.w[i] = (x & 0x807fffff) | (((y >> 8) % 40 + 108) << 23); + break; + } + } + return r; +} + +static int is_nan(uint32_t w) +{ + return (w & 0x7f800000) == 0x7f800000 && (w & 0x007fffff); +} + +static float fmadds(float a, float c, float b) +{ + float r; + asm("fmadds %0,%1,%2,%3" : "=f"(r) : "f"(a), "f"(c), "f"(b)); + return r; +} + +static float fnmsubs(float a, float c, float b) +{ + float r; + asm("fnmsubs %0,%1,%2,%3" : "=f"(r) : "f"(a), "f"(c), "f"(b)); + return r; +} + +static float fmax_ref(float a, float b, int is_max) +{ + if (a != a || b != b) { + return a + b; /* some NaN; any NaN result passes */ + } + if (a == 0 && b == 0) { + /* Signed zeros: max prefers +0, min prefers -0. */ + union { float f; uint32_t w; } ua = { a }, ub = { b }; + return is_max ? ((ua.w & ub.w) >> 31 ? a : (ua.w >> 31 ? b : a)) + : ((ua.w | ub.w) >> 31 ? (ua.w >> 31 ? a : b) : a); + } + return is_max ? (a > b ? a : b) : (a < b ? a : b); +} + +static double pow2(int n) +{ + double d = 1; + while (n > 0) { + d *= 2; + n--; + } + while (n < 0) { + d /= 2; + n++; + } + return d; +} + +/* vctsxs/vctuxs reference: saturate(trunc(f * 2^uim)). */ +static uint32_t ct_ref(float f, int uim, int sign, int *sat) +{ + double d = (double)f * pow2(uim); + double lo = sign ? -2147483648.0 : 0.0; + double hi = sign ? 2147483647.0 : 4294967295.0; + + if (f != f) { + return 0; + } + if (d <= lo - 1 || d >= hi + 1) { + *sat = 1; + return d < 0 ? (sign ? 0x80000000u : 0) : (sign ? 0x7fffffffu + : 0xffffffffu); + } + if (sign) { + return (uint32_t)(int32_t)d; + } + return d < 0 ? 0 : (uint32_t)d; +} + +static uint32_t tb(void) +{ + uint32_t t; + asm volatile("mftb %0" : "=r"(t)); + return t; +} + +static void clear_sat(void) +{ + V z; + memset(&z, 0, sizeof(z)); + asm volatile("mtvscr %0" : : "v"(z.v)); +} + +static int get_sat(void) +{ + V r; + asm volatile("mfvscr %0" : "=v"(r.v)); + return r.w[3] & 1; +} + +#define ASM3(insn, r, a, b) \ + asm volatile(insn " %0,%1,%2" : "=v"(r.v) : "v"(a.v), "v"(b.v)) +#define ASM4(insn, r, a, b, c) \ + asm volatile(insn " %0,%1,%2,%3" : "=v"(r.v) : "v"(a.v), "v"(b.v), "v"(c.v)) +#define ASM2(insn, r, b) \ + asm volatile(insn " %0,%1" : "=v"(r.v) : "v"(b.v)) + +static int32_t clamp(int64_t x, int64_t lo, int64_t hi, int *sat) +{ + if (x < lo) { + *sat = 1; + return lo; + } + if (x > hi) { + *sat = 1; + return hi; + } + return x; +} + +/* Run op on a, b, c; fill in the result and the reference. */ +static void run_op(int op, V a, V b, V c, int sh, V *got, V *exp, + int *got_sat, int *exp_sat) +{ + V r, e, t; + int i, j, sat = 0; + + memset(&e, 0, sizeof(e)); + clear_sat(); + switch (op) { + case OP_VPERM: + ASM4("vperm", r, a, b, c); + goto ref_perm; + case OP_VPERM_DA: + r = a; + asm volatile("vperm %0,%0,%1,%2" : "+v"(r.v) : "v"(b.v), "v"(c.v)); + goto ref_perm; + case OP_VPERM_DC: + r = c; + asm volatile("vperm %0,%1,%2,%0" : "+v"(r.v) : "v"(a.v), "v"(b.v)); + goto ref_perm; + case OP_VPERM_AA: + b = a; + asm volatile("vperm %0,%1,%1,%2" : "=v"(r.v) : "v"(a.v), "v"(c.v)); + ref_perm: + for (i = 0; i < 16; i++) { + int s = c.b[i] & 0x1f; + e.b[i] = s < 16 ? a.b[s] : b.b[s - 16]; + } + break; + case OP_VSLDOI: + case OP_VSLDOI_DB: +#define SLD(n) \ + case n: \ + if (op == OP_VSLDOI) { \ + asm volatile("vsldoi %0,%1,%2,%3" \ + : "=v"(r.v) : "v"(a.v), "v"(b.v), "i"(n)); \ + } else { \ + r = b; \ + asm volatile("vsldoi %0,%1,%0,%2" \ + : "+v"(r.v) : "v"(a.v), "i"(n)); \ + } \ + break; + switch (sh) { + SLD(0) SLD(1) SLD(2) SLD(3) SLD(4) SLD(5) SLD(6) SLD(7) + SLD(8) SLD(9) SLD(10) SLD(11) SLD(12) SLD(13) SLD(14) SLD(15) + } + for (i = 0; i < 16; i++) { + j = i + sh; + e.b[i] = j < 16 ? a.b[j] : b.b[j - 16]; + } + break; + case OP_VMRGHB: + ASM3("vmrghb", r, a, b); + for (i = 0; i < 8; i++) { + e.b[2 * i] = a.b[i]; + e.b[2 * i + 1] = b.b[i]; + } + break; + case OP_VMRGHH: + ASM3("vmrghh", r, a, b); + for (i = 0; i < 4; i++) { + e.h[2 * i] = a.h[i]; + e.h[2 * i + 1] = b.h[i]; + } + break; + case OP_VMRGHW: + ASM3("vmrghw", r, a, b); + for (i = 0; i < 2; i++) { + e.w[2 * i] = a.w[i]; + e.w[2 * i + 1] = b.w[i]; + } + break; + case OP_VMRGLB: + ASM3("vmrglb", r, a, b); + for (i = 0; i < 8; i++) { + e.b[2 * i] = a.b[i + 8]; + e.b[2 * i + 1] = b.b[i + 8]; + } + break; + case OP_VMRGLH: + ASM3("vmrglh", r, a, b); + for (i = 0; i < 4; i++) { + e.h[2 * i] = a.h[i + 4]; + e.h[2 * i + 1] = b.h[i + 4]; + } + break; + case OP_VMRGLW: + ASM3("vmrglw", r, a, b); + for (i = 0; i < 2; i++) { + e.w[2 * i] = a.w[i + 2]; + e.w[2 * i + 1] = b.w[i + 2]; + } + break; + case OP_VPKUHUM: + ASM3("vpkuhum", r, a, b); + for (i = 0; i < 16; i++) { + e.b[i] = i < 8 ? a.h[i] : b.h[i - 8]; + } + break; + case OP_VPKUWUM: + ASM3("vpkuwum", r, a, b); + for (i = 0; i < 8; i++) { + e.h[i] = i < 4 ? a.w[i] : b.w[i - 4]; + } + break; + case OP_VPKUHUS: + ASM3("vpkuhus", r, a, b); + for (i = 0; i < 16; i++) { + e.b[i] = clamp(i < 8 ? a.h[i] : b.h[i - 8], 0, 0xff, &sat); + } + break; + case OP_VPKUWUS: + ASM3("vpkuwus", r, a, b); + for (i = 0; i < 8; i++) { + e.h[i] = clamp(i < 4 ? a.w[i] : b.w[i - 4], 0, 0xffff, &sat); + } + break; + case OP_VPKSHUS: + ASM3("vpkshus", r, a, b); + for (i = 0; i < 16; i++) { + e.b[i] = clamp(i < 8 ? a.sh[i] : b.sh[i - 8], 0, 0xff, &sat); + } + break; + case OP_VPKSWUS: + ASM3("vpkswus", r, a, b); + for (i = 0; i < 8; i++) { + e.h[i] = clamp(i < 4 ? a.sw[i] : b.sw[i - 4], 0, 0xffff, &sat); + } + break; + case OP_VPKSHSS: + ASM3("vpkshss", r, a, b); + for (i = 0; i < 16; i++) { + e.b[i] = clamp(i < 8 ? a.sh[i] : b.sh[i - 8], -0x80, 0x7f, &sat); + } + break; + case OP_VPKSWSS: + ASM3("vpkswss", r, a, b); + for (i = 0; i < 8; i++) { + e.h[i] = clamp(i < 4 ? a.sw[i] : b.sw[i - 4], + -0x8000, 0x7fff, &sat); + } + break; + case OP_VUPKHSB: + ASM2("vupkhsb", r, b); + for (i = 0; i < 8; i++) { + e.sh[i] = b.sb[i]; + } + break; + case OP_VUPKHSH: + ASM2("vupkhsh", r, b); + for (i = 0; i < 4; i++) { + e.sw[i] = b.sh[i]; + } + break; + case OP_VUPKLSB: + ASM2("vupklsb", r, b); + for (i = 0; i < 8; i++) { + e.sh[i] = b.sb[i + 8]; + } + break; + case OP_VUPKLSH: + ASM2("vupklsh", r, b); + for (i = 0; i < 4; i++) { + e.sw[i] = b.sh[i + 4]; + } + break; +#define MUL(OPC, insn, ew, rw, off) \ + case OPC: \ + ASM3(insn, r, a, b); \ + for (i = 0; i < 16 / sizeof(e.rw[0]); i++) { \ + e.rw[i] = a.ew[2 * i + off] * b.ew[2 * i + off]; \ + } \ + break; + MUL(OP_VMULEUB, "vmuleub", b, h, 0) + MUL(OP_VMULOUB, "vmuloub", b, h, 1) + MUL(OP_VMULESB, "vmulesb", sb, sh, 0) + MUL(OP_VMULOSB, "vmulosb", sb, sh, 1) + MUL(OP_VMULEUH, "vmuleuh", h, w, 0) + MUL(OP_VMULOUH, "vmulouh", h, w, 1) + MUL(OP_VMULESH, "vmulesh", sh, sw, 0) + MUL(OP_VMULOSH, "vmulosh", sh, sw, 1) + case OP_VMSUMUBM: + ASM4("vmsumubm", r, a, b, c); + for (i = 0; i < 4; i++) { + e.w[i] = c.w[i]; + for (j = 0; j < 4; j++) { + e.w[i] += (uint32_t)a.b[4 * i + j] * b.b[4 * i + j]; + } + } + break; + case OP_VMSUMMBM: + ASM4("vmsummbm", r, a, b, c); + for (i = 0; i < 4; i++) { + e.w[i] = c.w[i]; + for (j = 0; j < 4; j++) { + e.w[i] += (int32_t)a.sb[4 * i + j] * b.b[4 * i + j]; + } + } + break; + case OP_VMSUMUHM: + ASM4("vmsumuhm", r, a, b, c); + for (i = 0; i < 4; i++) { + e.w[i] = c.w[i] + (uint32_t)a.h[2 * i] * b.h[2 * i] + + (uint32_t)a.h[2 * i + 1] * b.h[2 * i + 1]; + } + break; +#define FP3(OPC, insn, expr) \ + case OPC: \ + ASM3(insn, r, a, b); \ + for (i = 0; i < 4; i++) { \ + e.f[i] = expr; \ + } \ + break; + FP3(OP_VADDFP, "vaddfp", a.f[i] + b.f[i]) + FP3(OP_VSUBFP, "vsubfp", a.f[i] - b.f[i]) + FP3(OP_VMAXFP, "vmaxfp", fmax_ref(a.f[i], b.f[i], 1)) + FP3(OP_VMINFP, "vminfp", fmax_ref(a.f[i], b.f[i], 0)) + case OP_VMADDFP: + ASM4("vmaddfp", r, a, b, c); + for (i = 0; i < 4; i++) { + e.f[i] = fmadds(a.f[i], b.f[i], c.f[i]); + } + break; + case OP_VNMSUBFP: + ASM4("vnmsubfp", r, a, b, c); + for (i = 0; i < 4; i++) { + e.f[i] = fnmsubs(a.f[i], b.f[i], c.f[i]); + } + break; + case OP_VREFP: + ASM2("vrefp", r, b); + for (i = 0; i < 4; i++) { + e.f[i] = 1.0f / b.f[i]; + } + break; +#define UIMS(X) X(0) X(1) X(7) X(16) X(31) +#define CF(n) \ + case n: \ + if (op == OP_VCFSX) { \ + asm volatile("vcfsx %0,%1,%2" : "=v"(r.v) : "v"(b.v), "i"(n)); \ + } else if (op == OP_VCFUX) { \ + asm volatile("vcfux %0,%1,%2" : "=v"(r.v) : "v"(b.v), "i"(n)); \ + } else if (op == OP_VCTSXS) { \ + asm volatile("vctsxs %0,%1,%2" : "=v"(r.v) : "v"(b.v), "i"(n)); \ + } else { \ + asm volatile("vctuxs %0,%1,%2" : "=v"(r.v) : "v"(b.v), "i"(n)); \ + } \ + uim = n; \ + break; + case OP_VCFSX: + case OP_VCFUX: + case OP_VCTSXS: + case OP_VCTUXS: { + static const int uim_of[5] = { 0, 1, 7, 16, 31 }; + int uim = 0; + switch (uim_of[sh % 5]) { + UIMS(CF) + } + for (i = 0; i < 4; i++) { + if (op == OP_VCFSX) { + e.f[i] = (float)b.sw[i] * (float)pow2(-uim); + } else if (op == OP_VCFUX) { + e.f[i] = (float)b.w[i] * (float)pow2(-uim); + } else { + e.w[i] = ct_ref(b.f[i], uim, op == OP_VCTSXS, &sat); + } + } + break; + } + case OP_VMSUMSHM: + ASM4("vmsumshm", r, a, b, c); + for (i = 0; i < 4; i++) { + e.w[i] = c.w[i] + (uint32_t)((int32_t)a.sh[2 * i] * b.sh[2 * i]) + + (uint32_t)((int32_t)a.sh[2 * i + 1] * b.sh[2 * i + 1]); + } + break; + } + t = r; + *got = t; + *exp = e; + *got_sat = get_sat(); + *exp_sat = sat; +} + +static void log_vec(volatile uint32_t *p, V v) +{ + int i; + for (i = 0; i < 4; i++) { + p[i] = v.w[i]; + } +} + +/* Dependent chains of the hot ops, for timing against the helper path. */ +static void bench(void) +{ + V a, b, c; + uint32_t t0; + int i; + + memset(&a, 0x12, sizeof(a)); + memset(&b, 0x34, sizeof(b)); + memset(&c, 0x05, sizeof(c)); + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("vperm %0,%0,%1,%2\n\tvperm %0,%0,%1,%2\n\t" + "vperm %0,%0,%1,%2\n\tvperm %0,%0,%1,%2" + : "+v"(a.v) : "v"(b.v), "v"(c.v)); + } + res[0x200] = tb() - t0; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("vmrghb %0,%0,%1\n\tvmrglh %0,%0,%1\n\t" + "vsldoi %0,%0,%1,3\n\tvpkuhum %0,%0,%1" + : "+v"(a.v) : "v"(b.v)); + } + res[0x201] = tb() - t0; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("vmuleub %0,%0,%1\n\tvmsumubm %0,%0,%1,%2\n\t" + "vpkshus %0,%0,%1\n\tvupkhsb %0,%0" + : "+v"(a.v) : "v"(b.v), "v"(c.v)); + } + res[0x202] = tb() - t0; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("vaddubm %0,%0,%1\n\tvaddubm %0,%0,%1\n\t" + "vaddubm %0,%0,%1\n\tvaddubm %0,%0,%1" + : "+v"(a.v) : "v"(b.v)); + } + res[0x203] = tb() - t0; + + /* 0.5f, 1.0f, 0.25f: stays finite and normal. */ + a.w[0] = a.w[1] = a.w[2] = a.w[3] = 0x3f000000; + b.w[0] = b.w[1] = b.w[2] = b.w[3] = 0x3f800000; + c.w[0] = c.w[1] = c.w[2] = c.w[3] = 0x3e800000; + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("vmaddfp %0,%0,%2,%1\n\tvmaddfp %0,%0,%2,%1\n\t" + "vmaddfp %0,%0,%2,%1\n\tvmaddfp %0,%0,%2,%1" + : "+v"(a.v) : "v"(b.v), "v"(c.v)); + } + res[0x204] = tb() - t0; +} + +int main(void) +{ + uint32_t seed = 0x2545f491; + uint32_t checks = 0, fails = 0, logged = 0; + int op, it, i; + + for (i = 0; i < 0x300; i++) { + res[i] = 0; + } + for (op = 0; op < NOPS; op++) { + for (it = 0; it < ITERS; it++) { + V a = rand_vec(&seed), b = rand_vec(&seed), c = rand_vec(&seed); + V got, exp; + int gs, es, bad = 0; + + if (op >= FIRST_FP_OP) { + a = rand_fvec(&seed); + b = rand_fvec(&seed); + c = rand_fvec(&seed); + } + run_op(op, a, b, c, it & 15, &got, &exp, &gs, &es); + for (i = 0; i < 4; i++) { + if (op >= FIRST_FP_OP && is_nan(exp.w[i])) { + /* NaN payloads are softfloat's either way. */ + bad |= !is_nan(got.w[i]); + } else { + bad |= got.w[i] != exp.w[i]; + } + } + bad |= gs != es; + checks++; + if (bad) { + fails++; + res[3 + op]++; + if (logged < MAXLOG) { + volatile uint32_t *p = res + 0x40 + logged * 24; + p[0] = op; + p[1] = it | gs << 16 | es << 24; + log_vec(p + 4, a); + log_vec(p + 8, b); + log_vec(p + 12, c); + log_vec(p + 16, got); + log_vec(p + 20, exp); + logged++; + } + } + } + } + res[1] = checks; + res[2] = fails; + bench(); + res[0] = 0x564d5854; /* 'VMXT' */ + return 0; +} From 4519d07586f9a5c61634e810caa8fd048515dba1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Castell=C3=B3?= Date: Tue, 10 Nov 2026 22:27:43 +0100 Subject: [PATCH 09/14] target/ppc: skip the BQL in ppc_maybe_interrupt when nothing can change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The guest rewrites MSR constantly, and every write took the BQL. With nothing pending and CPU_INTERRUPT_HARD already clear there is nothing to change; a source raising an interrupt calls ppc_maybe_interrupt() itself, under the BQL, after setting pending_interrupts. Taken from the mtmsr part of r300 commit 341dd47; the GPU and SR-slot parts of that commit are not. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Default-on; no switch. Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- target/ppc/excp_helper.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/target/ppc/excp_helper.c b/target/ppc/excp_helper.c index c941c89806e2e..234a0ce34b0d0 100644 --- a/target/ppc/excp_helper.c +++ b/target/ppc/excp_helper.c @@ -2094,6 +2094,18 @@ static int ppc_next_unmasked_interrupt(CPUPPCState *env) void ppc_maybe_interrupt(CPUPPCState *env) { CPUState *cs = env_cpu(env); + + /* + * The guest rewrites MSR constantly, and every write came here to take + * the BQL. With nothing pending and CPU_INTERRUPT_HARD already clear + * there is nothing to change; a source raising an interrupt calls this + * itself, under the BQL, after setting pending_interrupts. + */ + if (!bql_locked() && !qatomic_read(&env->pending_interrupts) && + !(qatomic_read(&cs->interrupt_request) & CPU_INTERRUPT_HARD)) { + return; + } + BQL_LOCK_GUARD(); if (ppc_next_unmasked_interrupt(env)) { From cd970d10bbe861f664391b384a0f88ca8cbc78de Mon Sep 17 00:00:00 2001 From: Spartan0285 <291227+Spartan0285@users.noreply.github.com> Date: Sat, 19 Sep 2026 00:39:57 -0400 Subject: [PATCH 10/14] target/ppc: run A-form FP arithmetic on the host FPU through one helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A-form FP arithmetic (fadd, fsub, fmul, fdiv and the fused multiply-add family, double and single) goes through one helper that computes on the host FPU when FPSCR is round-to-nearest with non-IEEE mode off and no FP exception enabled, and the operands and result are not NaNs. Anything else takes the softfloat path as before. Results and FPSCR flags are meant to be bit-identical to softfloat's in that state. FPRF is also set inline for the case that always happens: nearly every result is an ordinary normal number, which is two bit tests on the exponent. Everything else still calls helper_compute_fprf_float64(), which stays the single definition of the other classes. The inline test was compared against softfloat's classification over four million bit patterns (boundaries around zero, denormals, smallest normal, largest finite, infinity, both NaN kinds) with no mismatches. Measured +9..16% on a Warcraft III menu on an Apple Silicon host. Default-on. PPC_STRICT_FP=1 turns every FP fast path off and goes back to the original softfloat helpers. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- target/ppc/fpu_helper.c | 167 +++++++++++++++++++++++++++++ target/ppc/helper.h | 2 + target/ppc/translate/fp-impl.c.inc | 73 ++++++++++--- 3 files changed, 227 insertions(+), 15 deletions(-) diff --git a/target/ppc/fpu_helper.c b/target/ppc/fpu_helper.c index d93cfed17b413..1fe34a48f53a4 100644 --- a/target/ppc/fpu_helper.c +++ b/target/ppc/fpu_helper.c @@ -17,6 +17,7 @@ * License along with this library; if not, see . */ #include "qemu/osdep.h" +#include #include "cpu.h" #include "exec/helper-proto.h" #include "exec/exec-all.h" @@ -3658,3 +3659,169 @@ void helper_XVF64GERNN(CPUPPCState *env, ppc_vsr_t *a, ppc_vsr_t *b, vsxger(env, a, b, at, mask, true, true, true, vsxger_mul64, vsxger_muladd64, vsxger_zero64); } + + +/* + * Fast path for the A-form arithmetic ops (fadd/fsub/fmul/fdiv/f[n]m{add,sub} + * and their single-precision forms). QEMU normally emits four helper calls + * per op (reset status, softfloat op, FPRF, check status); under emulated + * Mac OS X games that was a quarter of the vCPU's time. In the state Mac OS + * X runs applications in - round to nearest, no FP exception enabled, NI off + * - the host FPU gives the IEEE result PowerPC defines, so compute there and + * only fall back to softfloat for NaNs or single-precision ops whose inputs + * are not exact singles. Sticky exception bits (XX, OX, UX, ...) are not + * accumulated on the fast path. PPC_STRICT_FP=1 disables it. + */ +enum { + FF_ADD, FF_ADDS, FF_SUB, FF_SUBS, FF_MUL, FF_MULS, FF_DIV, FF_DIVS, + FF_MADD = 16, FF_MADDS, FF_MSUB, FF_MSUBS, FF_NMADD, FF_NMADDS, + FF_NMSUB, FF_NMSUBS, +}; + +static inline bool fastfp_ok(CPUPPCState *env) +{ + static int strict = -1; + if (unlikely(strict < 0)) { + const char *e = getenv("PPC_STRICT_FP"); + strict = e && e[0] == '1'; + } + return !strict && !(env->fpscr & (FP_VE | FP_OE | FP_UE | FP_ZE | FP_XE | + FP_NI | FP_RN)); +} + +static inline double ff_d(uint64_t v) +{ + double d; + memcpy(&d, &v, 8); + return d; +} + +static inline uint64_t ff_u(double d) +{ + uint64_t v; + memcpy(&v, &d, 8); + return v; +} + +static inline bool ff_single(double d) +{ + return (double)(float)d == d; +} + +/* + * Set FPRF for a result the fast path produced. + * + * helper_compute_fprf_float64() decides between five classes with a chain of + * softfloat predicates, and it ran on every arithmetic operation -- 2.25% of + * the vCPU thread in a Warcraft III profile, on top of the call itself. + * + * Nearly every result is an ordinary normal number, and that case is two bit + * tests on the exponent: not all-zero (zero or denormal) and not all-ones + * (infinity or NaN). Anything else goes to the full helper, which stays the + * single definition of what the other classes mean. + * + * The caller has already rejected NaN, so this does not have to distinguish + * signalling from quiet -- but it does not assume that either, since the + * all-ones exponent is handled by falling through. + */ +static inline void ff_fprf(CPUPPCState *env, uint64_t r) +{ + uint32_t exp = (r >> 52) & 0x7FF; + + if (likely(exp != 0 && exp != 0x7FF)) { + target_ulong fprf = (r >> 63) ? (0x08 << FPSCR_FPRF) + : (0x04 << FPSCR_FPRF); + env->fpscr = (env->fpscr & ~FP_FPRF) | fprf; + } else { + helper_compute_fprf_float64(env, r); + } +} + +uint64_t helper_fastfp_ab(CPUPPCState *env, uint64_t a, uint64_t b, uint32_t op) +{ + uintptr_t ra = GETPC(); + if (likely(fastfp_ok(env))) { + double x = ff_d(a), y = ff_d(b), r; + bool ok = true; + switch (op) { + case FF_ADD: r = x + y; break; + case FF_SUB: r = x - y; break; + case FF_MUL: r = x * y; break; + case FF_DIV: r = x / y; break; + default: + ok = ff_single(x) && ff_single(y); + switch (op) { + case FF_ADDS: r = (float)x + (float)y; break; + case FF_SUBS: r = (float)x - (float)y; break; + case FF_MULS: r = (float)x * (float)y; break; + default: r = (float)x / (float)y; break; + } + break; + } + if (likely(ok && !isnan(r))) { + uint64_t ret = ff_u(r); + ff_fprf(env, ret); + return ret; + } + } + /* exact softfloat path, as the four separate helpers would do it */ + set_float_exception_flags(0, &env->fp_status); + float64 ret; + int flags; + switch (op) { + case FF_ADD: ret = float64_add(a, b, &env->fp_status); break; + case FF_ADDS: ret = float64r32_add(a, b, &env->fp_status); break; + case FF_SUB: ret = float64_sub(a, b, &env->fp_status); break; + case FF_SUBS: ret = float64r32_sub(a, b, &env->fp_status); break; + case FF_MUL: ret = float64_mul(a, b, &env->fp_status); break; + case FF_MULS: ret = float64r32_mul(a, b, &env->fp_status); break; + case FF_DIV: ret = float64_div(a, b, &env->fp_status); break; + default: ret = float64r32_div(a, b, &env->fp_status); break; + } + flags = get_float_exception_flags(&env->fp_status); + switch (op) { + case FF_ADD: case FF_ADDS: case FF_SUB: case FF_SUBS: + addsub_flags_handler(env, flags, ra); break; + case FF_MUL: case FF_MULS: + mul_flags_handler(env, flags, ra); break; + default: + div_flags_handler(env, flags, ra); break; + } + helper_compute_fprf_float64(env, ret); + do_float_check_status(env, true, ra); + return ret; +} + +uint64_t helper_fastfp_acb(CPUPPCState *env, uint64_t a, uint64_t c, + uint64_t b, uint32_t op) +{ + uintptr_t ra = GETPC(); + static const int mflags[4] = { MADD_FLGS, MSUB_FLGS, NMADD_FLGS, NMSUB_FLGS }; + int kind = (op - FF_MADD) >> 1; + bool single = (op - FF_MADD) & 1; + if (likely(fastfp_ok(env))) { + double x = ff_d(a), y = ff_d(c), z = ff_d(b), r; + bool ok = true; + double zz = (kind & 1) ? -z : z; /* msub / nmsub */ + if (single) { + ok = ff_single(x) && ff_single(y) && ff_single(z); + r = fmaf((float)x, (float)y, (float)zz); + } else { + r = fma(x, y, zz); + } + if (kind & 2) { + r = -r; /* nmadd / nmsub */ + } + if (likely(ok && !isnan(r))) { + uint64_t ret = ff_u(r); + ff_fprf(env, ret); + return ret; + } + } + set_float_exception_flags(0, &env->fp_status); + uint64_t ret = single ? do_fmadds(env, a, c, b, mflags[kind], ra) + : do_fmadd(env, a, c, b, mflags[kind], ra); + helper_compute_fprf_float64(env, ret); + do_float_check_status(env, true, ra); + return ret; +} diff --git a/target/ppc/helper.h b/target/ppc/helper.h index ca414f2f43d3a..eff3bb28655ec 100644 --- a/target/ppc/helper.h +++ b/target/ppc/helper.h @@ -116,6 +116,8 @@ DEF_HELPER_2(frip, i64, env, i64) DEF_HELPER_2(frim, i64, env, i64) DEF_HELPER_3(FADD, f64, env, f64, f64) +DEF_HELPER_4(fastfp_ab, i64, env, i64, i64, i32) +DEF_HELPER_5(fastfp_acb, i64, env, i64, i64, i64, i32) DEF_HELPER_3(FADDS, f64, env, f64, f64) DEF_HELPER_3(FSUB, f64, env, f64, f64) DEF_HELPER_3(FSUBS, f64, env, f64, f64) diff --git a/target/ppc/translate/fp-impl.c.inc b/target/ppc/translate/fp-impl.c.inc index a66b83398b6ca..1a64f9fa6d0db 100644 --- a/target/ppc/translate/fp-impl.c.inc +++ b/target/ppc/translate/fp-impl.c.inc @@ -30,6 +30,27 @@ static void gen_set_cr1_from_fpscr(DisasContext *ctx) #endif /*** Floating-Point arithmetic ***/ +/* Op codes for helper_fastfp_ab/acb (fpu_helper.c). */ +static int fastfp_op(void *helper) +{ + static const struct { void *h; int op; } map[] = { + { gen_helper_FADD, 0 }, { gen_helper_FADDS, 1 }, + { gen_helper_FSUB, 2 }, { gen_helper_FSUBS, 3 }, + { gen_helper_FMUL, 4 }, { gen_helper_FMULS, 5 }, + { gen_helper_FDIV, 6 }, { gen_helper_FDIVS, 7 }, + { gen_helper_FMADD, 16 }, { gen_helper_FMADDS, 17 }, + { gen_helper_FMSUB, 18 }, { gen_helper_FMSUBS, 19 }, + { gen_helper_FNMADD, 20 }, { gen_helper_FNMADDS, 21 }, + { gen_helper_FNMSUB, 22 }, { gen_helper_FNMSUBS, 23 }, + }; + for (size_t i = 0; i < ARRAY_SIZE(map); i++) { + if (map[i].h == helper) { + return map[i].op; + } + } + return -1; +} + static bool do_helper_acb(DisasContext *ctx, arg_A *a, void (*helper)(TCGv_i64, TCGv_ptr, TCGv_i64, TCGv_i64, TCGv_i64)) @@ -41,13 +62,23 @@ static bool do_helper_acb(DisasContext *ctx, arg_A *a, t1 = tcg_temp_new_i64(); t2 = tcg_temp_new_i64(); t3 = tcg_temp_new_i64(); - gen_reset_fpstatus(); - get_fpr(t0, a->fra); - get_fpr(t1, a->frc); - get_fpr(t2, a->frb); - helper(t3, tcg_env, t0, t1, t2); - set_fpr(a->frt, t3); - gen_compute_fprf_float64(t3); + int op = fastfp_op((void *)helper); + if (op >= 0) { + /* one call: fast host FP, or the full softfloat sequence */ + get_fpr(t0, a->fra); + get_fpr(t1, a->frc); + get_fpr(t2, a->frb); + gen_helper_fastfp_acb(t3, tcg_env, t0, t1, t2, tcg_constant_i32(op)); + set_fpr(a->frt, t3); + } else { + gen_reset_fpstatus(); + get_fpr(t0, a->fra); + get_fpr(t1, a->frc); + get_fpr(t2, a->frb); + helper(t3, tcg_env, t0, t1, t2); + set_fpr(a->frt, t3); + gen_compute_fprf_float64(t3); + } if (unlikely(a->rc)) { gen_set_cr1_from_fpscr(ctx); } @@ -64,12 +95,18 @@ static bool do_helper_ab(DisasContext *ctx, arg_A_tab *a, t0 = tcg_temp_new_i64(); t1 = tcg_temp_new_i64(); t2 = tcg_temp_new_i64(); - gen_reset_fpstatus(); + int op = fastfp_op((void *)helper); get_fpr(t0, a->fra); get_fpr(t1, a->frb); - helper(t2, tcg_env, t0, t1); - set_fpr(a->frt, t2); - gen_compute_fprf_float64(t2); + if (op >= 0) { + gen_helper_fastfp_ab(t2, tcg_env, t0, t1, tcg_constant_i32(op)); + set_fpr(a->frt, t2); + } else { + gen_reset_fpstatus(); + helper(t2, tcg_env, t0, t1); + set_fpr(a->frt, t2); + gen_compute_fprf_float64(t2); + } if (unlikely(a->rc)) { gen_set_cr1_from_fpscr(ctx); } @@ -86,12 +123,18 @@ static bool do_helper_ac(DisasContext *ctx, arg_A_tac *a, t0 = tcg_temp_new_i64(); t1 = tcg_temp_new_i64(); t2 = tcg_temp_new_i64(); - gen_reset_fpstatus(); + int op = fastfp_op((void *)helper); get_fpr(t0, a->fra); get_fpr(t1, a->frc); - helper(t2, tcg_env, t0, t1); - set_fpr(a->frt, t2); - gen_compute_fprf_float64(t2); + if (op >= 0) { + gen_helper_fastfp_ab(t2, tcg_env, t0, t1, tcg_constant_i32(op)); + set_fpr(a->frt, t2); + } else { + gen_reset_fpstatus(); + helper(t2, tcg_env, t0, t1); + set_fpr(a->frt, t2); + gen_compute_fprf_float64(t2); + } if (unlikely(a->rc)) { gen_set_cr1_from_fpscr(ctx); } From f61ed56c7e7aa40e104dac7196284e7ad8834fcc Mon Sep 17 00:00:00 2001 From: Teufelhunden-0311 <106038146+Teufelhunden-0311@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:15:46 -0700 Subject: [PATCH 11/14] target/ppc: run the A-form FP arithmetic inline on the host FPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fadd/fsub/fmul/fdiv, fmadd/fmsub/fnmadd/fnmsub and their single forms now run as host instructions in translated code instead of a call to helper_fastfp_ab/acb, when the FPSCR is in the state Mac OS X runs applications in (no FP exception enabled, NI off, round to nearest: the new HFLAGS_FP_FAST TB flag). Results and FPSCR are bit-identical to the helper's; where the helper would fall back to softfloat (NaN results, single ops on non-single inputs) the op branches to an out-of-line slow path that calls the helper and leaves the TB. - tcg: new vector-register ops fop_vec, ffma_vec and fcvt_vec for scalar IEEE arithmetic in a V64 (AArch64 backend only; TCG_TARGET_HAS_fp_vec). - FPRF is computed lazily: the inline op stores its result in env->fprf_res and ppc_fprf_sync() computes FPRF when something reads or partly changes it (mffs, mcrfs, fcmp, mtfsb, gdbstub, migration, dumps); full FPRF writers call ppc_fprf_clear(). Each host instruction counts here: an eager branchless FPRF cost more than it saved. - helper_fastfp_acb: fnmadd/fnmsub gave +0 instead of -0 for an exact zero sum on AArch64 hosts (clang folds -fma() into FNMADD, which negates the operands); flip the sign bit instead. - tests/ppc-vmx: run.py --fpdiff compares 211,200 scalar FP cases (with mffs, fcmpu, mtfsb1 and mcrfs after the op) between the inline path and the helper, results and FPSCR; --fpdiff-strict compares result bits with softfloat. Also link the test above macio-nvram's 0xfff04000-0xfff07fff window, which hid code past 16 KiB. PPC_NATIVE_FP=0 turns the inline path off (PPC_STRICT_FP=1 turns off all fast paths). Measured on an M1 Max, Tiger 10.4.11, Geekbench 2.2.0 (AI-assisted, Claude Code): FP score 654 -> 960, overall 1156 -> 1276 (Mandelbrot 604 -> 1727, dot product 383 -> 584, LU 396 -> 498). Both --fpdiff modes report 0 mismatches; Tiger and Leopard boot and run with it. fcmpu and frsp also run inline in this mode (PPC_NATIVE_FCMP=0 and PPC_NATIVE_FRSP=0 keep their helpers). fcmpu was three helper calls; NaN inputs branch to the old helper sequence, otherwise the operands' bits are compared as ordered integer keys. frsp converts to single and back on the host and takes the old sequence out of line for NaNs, inputs below 2^-126 and overflow. Geekbench 2 on Tiger, M1 Max, inline vs helpers: fcmpu +5% overall (Primality +46%), frsp Sharpen/Blur ~2x. The tests/ppc-vmx --fpdiff run compares the inline ops (including fcmpu and frsp) against the helpers and, with --fpdiff-strict, against softfloat: no mismatches over 224,400 cases. Default-on, AArch64 hosts only (it needs the new vector ops) and not in user-only emulation. It applies only while the TB flag HFLAGS_FP_FAST is set (no FP exception enabled, NI off, round to nearest); PPC_NATIVE_FP=0 turns the inline path off, PPC_STRICT_FP=1 turns off all fast paths. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- include/tcg/tcg-op-common.h | 5 + include/tcg/tcg-opc.h | 12 + target/ppc/arch_dump.c | 1 + target/ppc/cpu.c | 8 + target/ppc/cpu.h | 26 ++ target/ppc/cpu_init.c | 2 + target/ppc/dfp_helper.c | 2 + target/ppc/fpu_helper.c | 37 ++- target/ppc/gdbstub.c | 2 + target/ppc/helper.h | 1 + target/ppc/helper_regs.c | 9 + target/ppc/machine.c | 2 + target/ppc/translate.c | 23 +- target/ppc/translate/fp-impl.c.inc | 435 +++++++++++++++++++++++++- tcg/aarch64/tcg-target-has.h | 1 + tcg/aarch64/tcg-target.c.inc | 46 +++ tcg/tcg-has.h | 3 + tcg/tcg-op-vec.c | 45 +++ tcg/tcg.c | 5 + tests/ppc-vmx/link.ld | 6 +- tests/ppc-vmx/run.py | 66 +++- tests/ppc-vmx/vmx_test.c | 483 +++++++++++++++++++++++++++++ 22 files changed, 1212 insertions(+), 8 deletions(-) diff --git a/include/tcg/tcg-op-common.h b/include/tcg/tcg-op-common.h index 85f645ad6fed5..51549e9c1e94f 100644 --- a/include/tcg/tcg-op-common.h +++ b/include/tcg/tcg-op-common.h @@ -461,6 +461,11 @@ void tcg_gen_cmp_vec(TCGCond cond, unsigned vece, TCGv_vec r, void tcg_gen_bitsel_vec(unsigned vece, TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec c); void tcg_gen_tbl_vec(TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec idx); +void tcg_gen_fop_vec(unsigned vece, unsigned op, TCGv_vec r, + TCGv_vec a, TCGv_vec b); +void tcg_gen_ffma_vec(unsigned vece, unsigned kind, TCGv_vec r, + TCGv_vec a, TCGv_vec c, TCGv_vec b); +void tcg_gen_fcvt_vec(bool to_double, TCGv_vec r, TCGv_vec a); void tcg_gen_cmpsel_vec(TCGCond cond, unsigned vece, TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec c, TCGv_vec d); diff --git a/include/tcg/tcg-opc.h b/include/tcg/tcg-opc.h index 8b702fb5fff9c..92d7263608a82 100644 --- a/include/tcg/tcg-opc.h +++ b/include/tcg/tcg-opc.h @@ -274,6 +274,18 @@ DEF(bitsel_vec, 1, 3, 0, TCG_OPF_VECTOR) DEF(cmpsel_vec, 1, 4, 1, TCG_OPF_VECTOR) /* r[i] = idx[i] < 16 ? a[idx[i]] : idx[i] < 32 ? b[idx[i] - 16] : 0 */ DEF(tbl_vec, 1, 3, 0, TCG_OPF_VECTOR) +/* + * Scalar IEEE binary floating point in the low element of a V64: a double + * for vece MO_64, a single for MO_32. Round to nearest even, no + * exception flags; results for NaN operands are the host's. + * fop_vec r = a op b, constant op: 0 add, 1 sub, 2 mul, 3 div. + * ffma_vec r = a*c + b with one rounding, constant: 0 a*c+b, 1 a*c-b, + * 2 -(a*c+b), 3 -(a*c-b) (the negated forms negate the rounded result). + * fcvt_vec: constant 0 double -> single (rounding), 1 single -> double. + */ +DEF(fop_vec, 1, 2, 1, TCG_OPF_VECTOR) +DEF(ffma_vec, 1, 3, 1, TCG_OPF_VECTOR) +DEF(fcvt_vec, 1, 1, 1, TCG_OPF_VECTOR) DEF(last_generic, 0, 0, 0, TCG_OPF_NOT_PRESENT) diff --git a/target/ppc/arch_dump.c b/target/ppc/arch_dump.c index 80ac6c3e320c6..92978a61cc151 100644 --- a/target/ppc/arch_dump.c +++ b/target/ppc/arch_dump.c @@ -149,6 +149,7 @@ static void ppc_write_elf_fpregset(NoteFuncArg *arg, PowerPCCPU *cpu, int id) uint64_t *fpr = cpu_fpr_ptr(&cpu->env, i); fpregset->fpr[i] = cpu_to_dump64(s, *fpr); } + ppc_fprf_sync(&cpu->env); fpregset->fpscr = cpu_to_dump_reg(s, cpu->env.fpscr); } diff --git a/target/ppc/cpu.c b/target/ppc/cpu.c index bfcc695de7688..3395c28088c57 100644 --- a/target/ppc/cpu.c +++ b/target/ppc/cpu.c @@ -239,6 +239,8 @@ static inline void fpscr_set_rounding_mode(CPUPPCState *env) void ppc_store_fpscr(CPUPPCState *env, target_ulong val) { + target_ulong old = env->fpscr; + val &= FPSCR_MTFS_MASK; if (val & FPSCR_IX) { val |= FP_VX; @@ -246,10 +248,16 @@ void ppc_store_fpscr(CPUPPCState *env, target_ulong val) if ((val >> FPSCR_XX) & (val >> FPSCR_XE) & 0x1f) { val |= FP_FEX; } + ppc_fprf_clear(env); env->fpscr = val; env->fp_status.rebias_overflow = (FP_OE & env->fpscr) ? true : false; env->fp_status.rebias_underflow = (FP_UE & env->fpscr) ? true : false; if (tcg_enabled()) { fpscr_set_rounding_mode(env); + /* HFLAGS_FP_FAST follows these; see hreg_compute_hflags_value() */ + if ((old ^ val) & (FP_VE | FP_OE | FP_UE | FP_ZE | FP_XE | + FP_NI | FP_RN)) { + hreg_compute_hflags(env); + } } } diff --git a/target/ppc/cpu.h b/target/ppc/cpu.h index 3e6c143299b65..c5135c88eb036 100644 --- a/target/ppc/cpu.h +++ b/target/ppc/cpu.h @@ -811,6 +811,7 @@ enum { HFLAGS_PMC_OTHER = 18, /* PMC other than PMC5-6 is enabled */ HFLAGS_INSN_CNT = 19, /* PMU instruction count enabled */ HFLAGS_BHRB_ENABLE = 20, /* Summary flag for enabling BHRB */ + HFLAGS_FP_FAST = 21, /* FPSCR: no FP exception enabled, NI=0, RN=0 */ HFLAGS_VSX = 23, /* MSR_VSX if cpu has VSX */ HFLAGS_VR = 25, /* MSR_VR if cpu has VRE */ @@ -1232,6 +1233,12 @@ struct CPUArchState { target_ulong ca; target_ulong ov32; target_ulong ca32; + /* + * The result of the last inline FP op (fp-impl.c.inc), whose FPRF is + * not in fpscr yet, or PPC_FPRF_NONE; see ppc_fprf_sync(). Up here + * so translated code reaches it with a single store. + */ + uint64_t fprf_res; target_ulong reserve_addr; /* Reservation address */ target_ulong reserve_length; /* Reservation larx op size (bytes) */ @@ -1651,6 +1658,25 @@ void cpu_ppc_set_1lpar(PowerPCCPU *cpu); #endif void ppc_store_fpscr(CPUPPCState *env, target_ulong val); + +/* + * The inline FP ops leave FPSCR[FPRF] to be computed from their result + * when it is needed: code that reads FPRF, or changes only part of it, + * calls ppc_fprf_sync() first; code that sets all of FPRF calls + * ppc_fprf_clear(). The sentinel is a NaN, which an inline op never keeps. + */ +#define PPC_FPRF_NONE UINT64_MAX +void ppc_fprf_sync_slow(CPUPPCState *env); +static inline void ppc_fprf_sync(CPUPPCState *env) +{ + if (unlikely(env->fprf_res != PPC_FPRF_NONE)) { + ppc_fprf_sync_slow(env); + } +} +static inline void ppc_fprf_clear(CPUPPCState *env) +{ + env->fprf_res = PPC_FPRF_NONE; +} void helper_hfscr_facility_check(CPUPPCState *env, uint32_t bit, const char *caller, uint32_t cause); diff --git a/target/ppc/cpu_init.c b/target/ppc/cpu_init.c index 012957eb3969a..d75234ca98a71 100644 --- a/target/ppc/cpu_init.c +++ b/target/ppc/cpu_init.c @@ -7303,6 +7303,7 @@ static void ppc_cpu_reset_hold(Object *obj, ResetType type) /* clean any pending stop state */ env->resume_as_sreset = 0; #endif + ppc_fprf_clear(env); hreg_compute_hflags(env); env->reserve_addr = (target_ulong)-1ULL; /* Be sure no exception or interrupt is pending */ @@ -7662,6 +7663,7 @@ void ppc_cpu_dump_state(CPUState *cs, FILE *f, int flags) qemu_fprintf(f, "\n"); } } + ppc_fprf_sync(env); qemu_fprintf(f, "FPSCR " TARGET_FMT_lx "\n", env->fpscr); } diff --git a/target/ppc/dfp_helper.c b/target/ppc/dfp_helper.c index ecc3f79326729..3d433082fd833 100644 --- a/target/ppc/dfp_helper.c +++ b/target/ppc/dfp_helper.c @@ -251,6 +251,7 @@ static void dfp_set_FPRF_from_FRT_with_context(struct PPC_DFP *dfp, default: g_assert_not_reached(); } + ppc_fprf_clear(dfp->env); dfp->env->fpscr &= ~FP_FPRF; dfp->env->fpscr |= (fprf << FPSCR_FPRF); } @@ -400,6 +401,7 @@ static void dfp_set_CRBF_from_T(struct PPC_DFP *dfp) static void dfp_set_FPCC_from_CRBF(struct PPC_DFP *dfp) { + ppc_fprf_sync(dfp->env); dfp->env->fpscr &= ~FP_FPCC; dfp->env->fpscr |= (dfp->crbf << FPSCR_FPCC); } diff --git a/target/ppc/fpu_helper.c b/target/ppc/fpu_helper.c index 1fe34a48f53a4..2911bb4755ebb 100644 --- a/target/ppc/fpu_helper.c +++ b/target/ppc/fpu_helper.c @@ -162,6 +162,7 @@ void helper_compute_fprf_##tp(CPUPPCState *env, tp arg) \ fprf = 0x11 << FPSCR_FPRF; \ } \ } \ + ppc_fprf_clear(env); \ env->fpscr = (env->fpscr & ~FP_FPRF) | fprf; \ } @@ -193,6 +194,7 @@ static void finish_invalid_op_arith(CPUPPCState *env, int op, env->fpscr &= ~(FP_FR | FP_FI); if (!(env->fpscr & FP_VE)) { if (set_fpcc) { + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= (FP_C | FP_FU); } @@ -253,6 +255,7 @@ static void float_invalid_op_vxvc(CPUPPCState *env, bool set_fpcc, { env->fpscr |= FP_VXVC; if (set_fpcc) { + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= (FP_C | FP_FU); } @@ -280,6 +283,7 @@ static void float_invalid_op_vxcvi(CPUPPCState *env, bool set_fpcc, env->fpscr &= ~(FP_FR | FP_FI); if (!(env->fpscr & FP_VE)) { if (set_fpcc) { + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= (FP_C | FP_FU); } @@ -356,9 +360,20 @@ static inline void float_inexact_excp(CPUPPCState *env) } } +void ppc_fprf_sync_slow(CPUPPCState *env) +{ + helper_compute_fprf_float64(env, env->fprf_res); +} + +void helper_fprf_sync(CPUPPCState *env) +{ + ppc_fprf_sync(env); +} + void helper_fpscr_clrbit(CPUPPCState *env, uint32_t bit) { uint32_t mask = 1u << bit; + ppc_fprf_sync(env); if (env->fpscr & mask) { ppc_store_fpscr(env, env->fpscr & ~(target_ulong)mask); } @@ -367,6 +382,7 @@ void helper_fpscr_clrbit(CPUPPCState *env, uint32_t bit) void helper_fpscr_setbit(CPUPPCState *env, uint32_t bit) { uint32_t mask = 1u << bit; + ppc_fprf_sync(env); if (!(env->fpscr & mask)) { ppc_store_fpscr(env, env->fpscr | mask); } @@ -377,6 +393,7 @@ void helper_store_fpscr(CPUPPCState *env, uint64_t val, uint32_t nibbles) target_ulong mask = 0; int i; + ppc_fprf_sync(env); /* TODO: push this extension back to translation time */ for (i = 0; i < sizeof(target_ulong) * 2; i++) { if (nibbles & (1 << i)) { @@ -893,6 +910,7 @@ void helper_fcmpu(CPUPPCState *env, uint64_t arg1, uint64_t arg2, ret = 0x02UL; } + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= ret << FPSCR_FPCC; env->crf[crfD] = ret; @@ -924,6 +942,7 @@ void helper_fcmpo(CPUPPCState *env, uint64_t arg1, uint64_t arg2, ret = 0x02UL; } + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= ret << FPSCR_FPCC; env->crf[crfD] = (uint32_t) ret; @@ -2190,6 +2209,7 @@ void helper_xscmpexpdp(CPUPPCState *env, uint32_t opcode, } } + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= cc << FPSCR_FPCC; env->crf[BF(opcode)] = cc; @@ -2219,6 +2239,7 @@ void helper_xscmpexpqp(CPUPPCState *env, uint32_t opcode, } } + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= cc << FPSCR_FPCC; env->crf[BF(opcode)] = cc; @@ -2265,6 +2286,7 @@ static inline void do_scalar_cmp(CPUPPCState *env, ppc_vsr_t *xa, ppc_vsr_t *xb, g_assert_not_reached(); } + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= cc << FPSCR_FPCC; env->crf[crf_idx] = cc; @@ -2330,6 +2352,7 @@ static inline void do_scalar_cmpq(CPUPPCState *env, ppc_vsr_t *xa, g_assert_not_reached(); } + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= cc << FPSCR_FPCC; env->crf[crf_idx] = cc; @@ -3170,6 +3193,7 @@ static bool not_SP_value(float64 val) uint32_t cc, match, sign = TP##_is_neg(b->FLD); \ match = TP##_tstdc(b->FLD, dcmx); \ cc = sign << CRF_LT_BIT | match << CRF_EQ_BIT; \ + ppc_fprf_sync(env); \ env->fpscr &= ~FP_FPCC; \ env->fpscr |= cc << FPSCR_FPCC; \ env->crf[bf] = cc; \ @@ -3187,6 +3211,7 @@ void helper_XSTSTDCSP(CPUPPCState *env, uint32_t bf, int not_sp = (int)not_SP_value(b->VsrD(0)); match = float64_tstdc(b->VsrD(0), dcmx) || (exp > 0 && exp < 0x381); cc = sign << CRF_LT_BIT | match << CRF_EQ_BIT | not_sp << CRF_SO_BIT; + ppc_fprf_sync(env); env->fpscr &= ~FP_FPCC; env->fpscr |= cc << FPSCR_FPCC; env->crf[bf] = cc; @@ -3731,6 +3756,7 @@ static inline void ff_fprf(CPUPPCState *env, uint64_t r) if (likely(exp != 0 && exp != 0x7FF)) { target_ulong fprf = (r >> 63) ? (0x08 << FPSCR_FPRF) : (0x04 << FPSCR_FPRF); + ppc_fprf_clear(env); env->fpscr = (env->fpscr & ~FP_FPRF) | fprf; } else { helper_compute_fprf_float64(env, r); @@ -3809,11 +3835,16 @@ uint64_t helper_fastfp_acb(CPUPPCState *env, uint64_t a, uint64_t c, } else { r = fma(x, y, zz); } - if (kind & 2) { - r = -r; /* nmadd / nmsub */ - } if (likely(ok && !isnan(r))) { uint64_t ret = ff_u(r); + /* + * nmadd / nmsub negate the rounded result, so an exact zero + * sum gives -0. Flip the bit: the compiler would fold -fma() + * into AArch64 FNMADD, -(x*y)-z, which gives +0 there. + */ + if (kind & 2) { + ret ^= INT64_MIN; + } ff_fprf(env, ret); return ret; } diff --git a/target/ppc/gdbstub.c b/target/ppc/gdbstub.c index 3b28d4e21c73d..fd532a0a81e73 100644 --- a/target/ppc/gdbstub.c +++ b/target/ppc/gdbstub.c @@ -193,6 +193,7 @@ int ppc_cpu_gdb_read_register_apple(CPUState *cs, GByteArray *buf, int n) gdb_get_reg32(buf, cpu_read_xer(env)); break; case 70 + 32: + ppc_fprf_sync(env); gdb_get_reg64(buf, env->fpscr); break; } @@ -449,6 +450,7 @@ static int gdb_get_float_reg(CPUState *cs, GByteArray *buf, int n) return 8; } if (n == 32) { + ppc_fprf_sync(env); gdb_get_reg32(buf, env->fpscr); mem_buf = gdb_get_reg_ptr(buf, 4); ppc_maybe_bswap_register(env, mem_buf, 4); diff --git a/target/ppc/helper.h b/target/ppc/helper.h index eff3bb28655ec..435bf0064a38f 100644 --- a/target/ppc/helper.h +++ b/target/ppc/helper.h @@ -91,6 +91,7 @@ DEF_HELPER_2(compute_fprf_float64, void, env, i64) DEF_HELPER_3(store_fpscr, void, env, i64, i32) DEF_HELPER_2(fpscr_clrbit, void, env, i32) DEF_HELPER_2(fpscr_setbit, void, env, i32) +DEF_HELPER_1(fprf_sync, void, env) DEF_HELPER_FLAGS_1(todouble, TCG_CALL_NO_RWG_SE, i64, i32) DEF_HELPER_FLAGS_1(tosingle, TCG_CALL_NO_RWG_SE, i32, i64) diff --git a/target/ppc/helper_regs.c b/target/ppc/helper_regs.c index f211bc9830444..e93bbb5c4d97b 100644 --- a/target/ppc/helper_regs.c +++ b/target/ppc/helper_regs.c @@ -181,6 +181,15 @@ static uint32_t hreg_compute_hflags_value(CPUPPCState *env) if (env->spr[SPR_LPCR] & LPCR_GTSE) { hflags |= 1 << HFLAGS_GTSE; } + /* + * The FPSCR state in which the A-form FP ops run inline on the host + * FPU (see native_fp_op() in translate/fp-impl.c.inc). Only + * ppc_store_fpscr() changes these bits, and it recomputes hflags. + */ + if (!(env->fpscr & (FP_VE | FP_OE | FP_UE | FP_ZE | FP_XE | + FP_NI | FP_RN))) { + hflags |= 1 << HFLAGS_FP_FAST; + } if (env->spr[SPR_LPCR] & LPCR_HR) { hflags |= 1 << HFLAGS_HR; } diff --git a/target/ppc/machine.c b/target/ppc/machine.c index 98df5b4a3a2a0..411e52277b806 100644 --- a/target/ppc/machine.c +++ b/target/ppc/machine.c @@ -127,6 +127,7 @@ static int cpu_pre_save(void *opaque) env->spr[SPR_LR] = env->lr; env->spr[SPR_CTR] = env->ctr; env->spr[SPR_XER] = cpu_read_xer(env); + ppc_fprf_sync(env); #if defined(TARGET_PPC64) env->spr[SPR_CFAR] = env->cfar; #endif @@ -258,6 +259,7 @@ static int cpu_post_load(void *opaque, int version_id) ppc_store_sdr1(env, env->spr[SPR_SDR1]); } + ppc_fprf_clear(env); post_load_update_msr(env); if (tcg_enabled()) { diff --git a/target/ppc/translate.c b/target/ppc/translate.c index 29b8601c90b0e..c7eed092177f3 100644 --- a/target/ppc/translate.c +++ b/target/ppc/translate.c @@ -166,8 +166,18 @@ void ppc_translate_init(void) } /* internal defines */ +/* A deferred slow path of an inline FP op (fp-impl.c.inc) */ +typedef struct NativeFPSlow { + TCGLabel *slow; + target_ulong next; /* address of the following instruction */ + int op, frt, x, y, z; +} NativeFPSlow; + struct DisasContext { DisasContextBase base; + bool fp_fast; /* HFLAGS_FP_FAST */ + int n_nfp; + NativeFPSlow nfp[64]; target_ulong cia; /* current instruction address */ uint32_t opcode; /* Routine used to access memory */ @@ -6540,6 +6550,8 @@ static void ppc_tr_init_disas_context(DisasContextBase *dcbase, CPUState *cs) uint32_t hflags = ctx->base.tb->flags; ctx->spr_cb = env->spr_cb; + ctx->fp_fast = (hflags >> HFLAGS_FP_FAST) & 1; + ctx->n_nfp = 0; ctx->pr = (hflags >> HFLAGS_PR) & 1; ctx->mem_idx = (hflags >> HFLAGS_DMMU_IDX) & 7; ctx->dr = (hflags >> HFLAGS_DR) & 1; @@ -6644,7 +6656,7 @@ static void ppc_tr_translate_insn(DisasContextBase *dcbase, CPUState *cs) } } -static void ppc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs) +static void ppc_tr_tb_exit(DisasContextBase *dcbase, CPUState *cs) { DisasContext *ctx = container_of(dcbase, DisasContext, base); DisasJumpType is_jmp = ctx->base.is_jmp; @@ -6721,6 +6733,15 @@ static void ppc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs) } } +static void ppc_tr_tb_stop(DisasContextBase *dcbase, CPUState *cs) +{ + DisasContext *ctx = container_of(dcbase, DisasContext, base); + + ppc_tr_tb_exit(dcbase, cs); + /* out of line, after the TB's exit, so the fast paths never branch */ + native_fp_emit_slow_paths(ctx); +} + static const TranslatorOps ppc_tr_ops = { .init_disas_context = ppc_tr_init_disas_context, .tb_start = ppc_tr_tb_start, diff --git a/target/ppc/translate/fp-impl.c.inc b/target/ppc/translate/fp-impl.c.inc index 1a64f9fa6d0db..40caca612e11f 100644 --- a/target/ppc/translate/fp-impl.c.inc +++ b/target/ppc/translate/fp-impl.c.inc @@ -51,6 +51,386 @@ static int fastfp_op(void *helper) return -1; } +/* + * The A-form arithmetic ops on the host FPU, inline (fop_vec/ffma_vec). + * + * helper_fastfp_ab/acb already compute these with host floating point in + * the state Mac OS X runs applications in, but a guest fmadd still costs + * an out-of-line call: about 5.4 ns in a dependent chain on an M1, against + * 0.3 ns for an integer add. This emits the host instruction instead, and + * keeps its result wherever the helper's fast path would return the same + * bits and FPSCR: + * - FPSCR as fastfp_ok() wants it: no exception enabled, NI off, round to + * nearest. That is HFLAGS_FP_FAST, a TB flag, so it costs nothing at + * run time; ppc_store_fpscr() recomputes it and the mtfs* instructions + * end the TB; + * - for single precision, inputs that are singles (converting them to + * single and back gives the same bits), so the single-precision host + * operation rounds once, like the helper's (float)x ops; + * - a result that is not a NaN (the helper uses softfloat for those). + * The helper then sets FPRF only. Here FPRF is left for later: the result + * goes to env->fprf_res, and ppc_fprf_sync() computes FPRF from it when + * something reads FPRF (mffs, mcrfs, a partial update, gdb, migration). + * That keeps the inline op down to the operation, one store, a NaN test + * and the FPR store; each extra host instruction here costs Geekbench + * points, as FP-heavy loops are bound by instruction throughput. + * + * If the checks fail, the op branches to a slow path that calls + * helper_fastfp_ab/acb exactly as before and then leaves the TB for the + * next instruction. It never comes back: a label where the paths joined + * would make TCG write back and reload every global at every FP op (a + * conditional branch only writes back the dirty ones). The slow paths are + * emitted after the TB's exit (native_fp_emit_slow_paths()). Nothing + * there can raise an exception (no FP exception is enabled), so being + * outside the op's insn_start range does not matter. The target FPR is + * written only after the branch, so the slow path finds the inputs intact. + * + * Needs a host with fop_vec (AArch64); PPC_STRICT_FP=1 or PPC_NATIVE_FP=0 + * turn it off. + */ +static bool native_fp_on(void) +{ +#ifdef CONFIG_USER_ONLY + /* linux-user sets env->fpscr directly, without the hflags update */ + return false; +#else + static int on = -1; + if (on < 0) { + const char *strict = getenv("PPC_STRICT_FP"); + const char *nat = getenv("PPC_NATIVE_FP"); + on = !(strict && strict[0] == '1') && !(nat && nat[0] == '0') + && tcg_can_emit_vec_op(INDEX_op_fop_vec, TCG_TYPE_V64, MO_64) > 0; + } + return on; +#endif +} + +static bool native_fp(DisasContext *ctx) +{ + /* + * The slow path leaves the TB without the guest's trace interrupt, PMU + * instruction counting or icount; Mac OS X applications use none. + */ + return native_fp_on() && ctx->fp_fast + && ctx->n_nfp < ARRAY_SIZE(ctx->nfp) + && !ctx->singlestep_enabled && !ctx->pmu_insn_cnt + && !(tb_cflags(ctx->base.tb) & CF_USE_ICOUNT); +} + +/* Before code that reads FPSCR[FPRF] from cpu_fpscr */ +static void gen_fprf_sync(void) +{ + if (native_fp_on()) { + gen_helper_fprf_sync(tcg_env); + } +} + +/* The helpers' FF_* codes (fpu_helper.c): single-precision if odd. */ +static bool native_single(int op) +{ + return (op >= 16 ? op - 16 : op) & 1; +} + +/* + * Load FPR regno, as a single if single; then ok is cleared (from all + * ones) if it does not convert to single and back unchanged. + */ +static TCGv_vec native_load(int regno, bool single, TCGv_vec ok) +{ + TCGv_vec v = tcg_temp_new_vec(TCG_TYPE_V64); + + tcg_gen_ld_vec(v, tcg_env, fpr_offset(regno)); + if (single) { + TCGv_vec s = tcg_temp_new_vec(TCG_TYPE_V64); + TCGv_vec d = tcg_temp_new_vec(TCG_TYPE_V64); + + tcg_gen_fcvt_vec(false, s, v); + tcg_gen_fcvt_vec(true, d, s); + tcg_gen_cmp_vec(TCG_COND_EQ, MO_64, d, d, v); + tcg_gen_and_vec(MO_64, ok, ok, d); + return s; + } + return v; +} + +/* + * Emit op (an FF_* code) on inputs x, y, z in the helper's order (z < 0 + * for the two-operand ops), writing frt. Only when native_fp(ctx). + */ +static void native_fp_op(DisasContext *ctx, int op, int frt, + int x, int y, int z) +{ + NativeFPSlow *sp = &ctx->nfp[ctx->n_nfp++]; + bool fma = op >= 16; + bool single = native_single(op); + unsigned vece = single ? MO_32 : MO_64; + TCGv_vec r = tcg_temp_new_vec(TCG_TYPE_V64); + TCGv_vec ok = NULL, vx, vy, vz = NULL; + TCGv_i64 res = tcg_temp_new_i64(); + + *sp = (NativeFPSlow) { + .slow = gen_new_label(), .next = ctx->base.pc_next, + .op = op, .frt = frt, .x = x, .y = y, .z = z, + }; + + if (single) { + ok = tcg_temp_new_vec(TCG_TYPE_V64); + tcg_gen_dupi_vec(MO_64, ok, -1); + } + vx = native_load(x, single, ok); + vy = native_load(y, single, ok); + if (fma) { + vz = native_load(z, single, ok); + tcg_gen_ffma_vec(vece, (op - 16) >> 1, r, vx, vy, vz); + } else { + tcg_gen_fop_vec(vece, op >> 1, r, vx, vy); + } + if (single) { + tcg_gen_fcvt_vec(true, r, r); + /* all ones, a NaN, unless every input was a single */ + tcg_gen_orc_vec(MO_64, r, r, ok); + } + + /* + * FPRF is now due from this result. On the slow path the helper sets + * FPRF itself, which drops this. + */ + tcg_gen_st_vec(r, tcg_env, offsetof(CPUPPCState, fprf_res)); + tcg_gen_ld_i64(res, tcg_env, offsetof(CPUPPCState, fprf_res)); + tcg_gen_shli_i64(res, res, 1); + tcg_gen_brcondi_i64(TCG_COND_GTU, res, 0xffe0000000000000ull, sp->slow); + + tcg_gen_st_vec(r, tcg_env, fpr_offset(frt)); + if (ctx->insns_flags2 & PPC2_VSX) { + /* as set_fpr(); without VSX nothing else writes doubleword 1 */ + tcg_gen_st_i64(tcg_constant_i64(0), tcg_env, vsr64_offset(frt, false)); + } +} + +/* A NativeFPSlow op for fcmpu, whose frt is the CR field */ +#define NATIVE_FCMPU (-1) + +/* PPC_NATIVE_FCMP=0 keeps fcmpu on the helpers (for A/B tests). */ +static bool native_fcmp_on(void) +{ + static int on = -1; + if (on < 0) { + const char *e = getenv("PPC_NATIVE_FCMP"); + on = !(e && e[0] == '0'); + } + return on; +} + +/* + * A non-NaN double's bits as a signed integer that orders like the double: + * negative doubles count down from zero, so -0 and +0 are both 0. + */ +static void native_fcmp_key(TCGv_i64 key, TCGv_i64 x) +{ + TCGv_i64 m = tcg_temp_new_i64(); + TCGv_i64 n = tcg_temp_new_i64(); + + tcg_gen_andi_i64(m, x, INT64_MAX); + tcg_gen_neg_i64(n, m); + tcg_gen_movcond_i64(TCG_COND_LT, key, x, tcg_constant_i64(0), n, m); +} + +/* + * fcmpu with integer ops: the helpers give FPCC and CR field 8, 4 or 2 for + * ordered inputs and clear FPSCR[FI] (float_check_status with nothing + * raised). NaN inputs (unordered, maybe VXSNAN) take the slow path. + * FPCC is part of FPRF, whose C bit comes from the pending result if there + * is one (see ppc_fprf_sync): C is set for -0 and denormals, and native + * results are never NaN. + */ +static void native_fcmpu(DisasContext *ctx, int crf, int ra, int rb) +{ + NativeFPSlow *sp = &ctx->nfp[ctx->n_nfp++]; + TCGv_i64 a = tcg_temp_new_i64(), b = tcg_temp_new_i64(); + TCGv_i64 t = tcg_temp_new_i64(), u = tcg_temp_new_i64(); + TCGv_i64 ka = tcg_temp_new_i64(), kb = tcg_temp_new_i64(); + TCGv_i64 res = tcg_temp_new_i64(), c = tcg_temp_new_i64(); + TCGv_i32 r32 = tcg_temp_new_i32(); + TCGv tl = tcg_temp_new(); + + *sp = (NativeFPSlow) { + .slow = gen_new_label(), .next = ctx->base.pc_next, + .op = NATIVE_FCMPU, .frt = crf, .x = ra, .y = rb, .z = -1, + }; + + get_fpr(a, ra); + get_fpr(b, rb); + tcg_gen_shli_i64(t, a, 1); + tcg_gen_shli_i64(u, b, 1); + tcg_gen_umax_i64(t, t, u); + tcg_gen_brcondi_i64(TCG_COND_GTU, t, 0xffe0000000000000ull, sp->slow); + + /* 8 if a < b, 4 if a > b, else 2 */ + native_fcmp_key(ka, a); + native_fcmp_key(kb, b); + tcg_gen_setcond_i64(TCG_COND_LT, t, ka, kb); + tcg_gen_setcond_i64(TCG_COND_GT, u, ka, kb); + tcg_gen_shli_i64(t, t, 3); + tcg_gen_shli_i64(u, u, 2); + tcg_gen_or_i64(t, t, u); + tcg_gen_movcond_i64(TCG_COND_EQ, t, t, tcg_constant_i64(0), + tcg_constant_i64(2), t); + tcg_gen_extrl_i64_i32(cpu_crf[crf], t); + + /* C: from the pending result, else FPSCR's own */ + tcg_gen_ld_i64(res, tcg_env, offsetof(CPUPPCState, fprf_res)); + tcg_gen_shli_i64(u, res, 1); + tcg_gen_setcondi_i64(TCG_COND_LTU, u, u, 1ull << 53); + tcg_gen_setcondi_i64(TCG_COND_NE, c, res, 0); + tcg_gen_and_i64(u, u, c); + tcg_gen_extu_tl_i64(c, cpu_fpscr); + tcg_gen_shri_i64(c, c, FPSCR_C); + tcg_gen_andi_i64(c, c, 1); + tcg_gen_movcond_i64(TCG_COND_NE, c, res, tcg_constant_i64(PPC_FPRF_NONE), + u, c); + /* + * Store with the vector unit, as the native ops do: on the M1 an + * integer store here, between their vector store and integer reload + * of fprf_res, cost 25% of Geekbench's Mandelbrot routine. + */ + { + TCGv_vec none = tcg_temp_new_vec(TCG_TYPE_V64); + + tcg_gen_dupi_vec(MO_64, none, PPC_FPRF_NONE); + tcg_gen_st_vec(none, tcg_env, offsetof(CPUPPCState, fprf_res)); + } + + tcg_gen_shli_i64(c, c, FPSCR_C); + tcg_gen_shli_i64(t, t, FPSCR_FPCC); + tcg_gen_or_i64(t, t, c); + tcg_gen_trunc_i64_tl(tl, t); + tcg_gen_andi_tl(cpu_fpscr, cpu_fpscr, ~(target_ulong)(FP_FPRF | FP_FI)); + tcg_gen_or_tl(cpu_fpscr, cpu_fpscr, tl); + /* as after gen_reset_fpstatus and an ordered comparison */ + tcg_gen_movi_i32(r32, 0); + tcg_gen_st16_i32(r32, tcg_env, + offsetof(CPUPPCState, fp_status.float_exception_flags)); +} + +/* A NativeFPSlow op for frsp */ +#define NATIVE_FRSP (-2) + +/* PPC_NATIVE_FRSP=0 keeps frsp on the helpers (for A/B tests). */ +static bool native_frsp_on(void) +{ + static int on = -1; + if (on < 0) { + const char *e = getenv("PPC_NATIVE_FRSP"); + on = !(e && e[0] == '0'); + } + return on; +} + +/* + * frsp on the host: convert to single and back. The helper sequence + * (reset status, frsp, FPRF, check status) also sets FPSCR XX and FX when + * the result is inexact, and FI to whether it is; that is the result's bits + * differing from the input's, so it is done here too. Inputs that are + * tiny for a single (underflow, which softfloat detects before rounding), + * results that overflow, and NaNs take the slow path. FPRF is left + * pending in fprf_res, as for the arithmetic. + */ +static void native_frsp(DisasContext *ctx, int frt, int frb) +{ + NativeFPSlow *sp = &ctx->nfp[ctx->n_nfp++]; + TCGv_vec v = tcg_temp_new_vec(TCG_TYPE_V64); + TCGv_vec s = tcg_temp_new_vec(TCG_TYPE_V64); + TCGv_i64 x = tcg_temp_new_i64(), res = tcg_temp_new_i64(); + TCGv_i64 t = tcg_temp_new_i64(), u = tcg_temp_new_i64(); + TCGv_i32 r32 = tcg_temp_new_i32(); + TCGv tl = tcg_temp_new(); + + *sp = (NativeFPSlow) { + .slow = gen_new_label(), .next = ctx->base.pc_next, + .op = NATIVE_FRSP, .frt = frt, .x = frb, .y = frb, .z = -1, + }; + + tcg_gen_ld_vec(v, tcg_env, fpr_offset(frb)); + tcg_gen_fcvt_vec(false, s, v); + tcg_gen_fcvt_vec(true, v, s); + tcg_gen_st_vec(v, tcg_env, offsetof(CPUPPCState, fprf_res)); + tcg_gen_ld_i64(res, tcg_env, offsetof(CPUPPCState, fprf_res)); + get_fpr(x, frb); + + /* slow: result Inf or NaN from a non-Inf input, or input below 2^-126 */ + tcg_gen_shli_i64(t, res, 1); + tcg_gen_setcondi_i64(TCG_COND_GEU, t, t, 0xffe0000000000000ull); + tcg_gen_shli_i64(u, x, 1); + tcg_gen_setcondi_i64(TCG_COND_NE, u, u, 0xffe0000000000000ull); + tcg_gen_and_i64(t, t, u); + tcg_gen_brcondi_i64(TCG_COND_NE, t, 0, sp->slow); + tcg_gen_shli_i64(u, x, 1); + tcg_gen_subi_i64(u, u, 1); /* +-0 wraps to the top: not tiny */ + tcg_gen_brcondi_i64(TCG_COND_LTU, u, (0x381ull << 53) - 1, sp->slow); + + tcg_gen_st_vec(v, tcg_env, fpr_offset(frt)); + if (ctx->insns_flags2 & PPC2_VSX) { + tcg_gen_st_i64(tcg_constant_i64(0), tcg_env, vsr64_offset(frt, false)); + } + + /* inexact: XX and FX set, FI set or cleared; softfloat's flags too */ + tcg_gen_setcond_i64(TCG_COND_NE, t, res, x); + tcg_gen_extrl_i64_i32(r32, t); + tcg_gen_shli_i32(r32, r32, 4); /* float_flag_inexact */ + tcg_gen_st16_i32(r32, tcg_env, + offsetof(CPUPPCState, fp_status.float_exception_flags)); + tcg_gen_neg_i64(t, t); + tcg_gen_andi_i64(t, t, FP_XX | FP_FX | FP_FI); + tcg_gen_trunc_i64_tl(tl, t); + tcg_gen_andi_tl(cpu_fpscr, cpu_fpscr, ~(target_ulong)FP_FI); + tcg_gen_or_tl(cpu_fpscr, cpu_fpscr, tl); +} + +/* After the TB's exit: each slow path, then on to the next instruction. */ +static void native_fp_emit_slow_paths(DisasContext *ctx) +{ + for (int i = 0; i < ctx->n_nfp; i++) { + NativeFPSlow *sp = &ctx->nfp[i]; + TCGv_i64 t0 = tcg_temp_new_i64(); + TCGv_i64 t1 = tcg_temp_new_i64(); + TCGv_i64 t3 = tcg_temp_new_i64(); + TCGv_i32 op = tcg_constant_i32(sp->op); + + gen_set_label(sp->slow); + get_fpr(t0, sp->x); + get_fpr(t1, sp->y); + if (sp->op == NATIVE_FCMPU) { + gen_reset_fpstatus(); + gen_helper_fcmpu(tcg_env, t0, t1, tcg_constant_i32(sp->frt)); + gen_helper_float_check_status(tcg_env); + gen_update_nip(ctx, sp->next); + tcg_gen_lookup_and_goto_ptr(); + continue; + } + if (sp->op == NATIVE_FRSP) { + gen_reset_fpstatus(); + gen_helper_frsp(t3, tcg_env, t0); + set_fpr(sp->frt, t3); + gen_helper_compute_fprf_float64(tcg_env, t3); + gen_helper_float_check_status(tcg_env); + gen_update_nip(ctx, sp->next); + tcg_gen_lookup_and_goto_ptr(); + continue; + } + if (sp->z >= 0) { + TCGv_i64 t2 = tcg_temp_new_i64(); + get_fpr(t2, sp->z); + gen_helper_fastfp_acb(t3, tcg_env, t0, t1, t2, op); + } else { + gen_helper_fastfp_ab(t3, tcg_env, t0, t1, op); + } + set_fpr(sp->frt, t3); + gen_update_nip(ctx, sp->next); + tcg_gen_lookup_and_goto_ptr(); + } + ctx->n_nfp = 0; +} + static bool do_helper_acb(DisasContext *ctx, arg_A *a, void (*helper)(TCGv_i64, TCGv_ptr, TCGv_i64, TCGv_i64, TCGv_i64)) @@ -63,6 +443,10 @@ static bool do_helper_acb(DisasContext *ctx, arg_A *a, t2 = tcg_temp_new_i64(); t3 = tcg_temp_new_i64(); int op = fastfp_op((void *)helper); + if (op >= 0 && !a->rc && native_fp(ctx)) { + native_fp_op(ctx, op, a->frt, a->fra, a->frc, a->frb); + return true; + } if (op >= 0) { /* one call: fast host FP, or the full softfloat sequence */ get_fpr(t0, a->fra); @@ -96,6 +480,10 @@ static bool do_helper_ab(DisasContext *ctx, arg_A_tab *a, t1 = tcg_temp_new_i64(); t2 = tcg_temp_new_i64(); int op = fastfp_op((void *)helper); + if (op >= 0 && !a->rc && native_fp(ctx)) { + native_fp_op(ctx, op, a->frt, a->fra, a->frb, -1); + return true; + } get_fpr(t0, a->fra); get_fpr(t1, a->frb); if (op >= 0) { @@ -124,6 +512,10 @@ static bool do_helper_ac(DisasContext *ctx, arg_A_tac *a, t1 = tcg_temp_new_i64(); t2 = tcg_temp_new_i64(); int op = fastfp_op((void *)helper); + if (op >= 0 && !a->rc && native_fp(ctx)) { + native_fp_op(ctx, op, a->frt, a->fra, a->frc, -1); + return true; + } get_fpr(t0, a->fra); get_fpr(t1, a->frc); if (op >= 0) { @@ -265,7 +657,31 @@ GEN_FLOAT_B(ctiwz, 0x0F, 0x00, 0, PPC_FLOAT); /* fctiwuz */ GEN_FLOAT_B(ctiwuz, 0x0F, 0x04, 0, PPC2_FP_CVT_ISA206); /* frsp */ -GEN_FLOAT_B(rsp, 0x0C, 0x00, 1, PPC_FLOAT); +static void gen_frsp(DisasContext *ctx) +{ + TCGv_i64 t0, t1; + + if (unlikely(!ctx->fpu_enabled)) { + gen_exception(ctx, POWERPC_EXCP_FPU); + return; + } + if (!Rc(ctx->opcode) && native_fp(ctx) && native_frsp_on()) { + native_frsp(ctx, rD(ctx->opcode), rB(ctx->opcode)); + return; + } + /* as GEN_FLOAT_B(rsp, 0x0C, 0x00, 1, PPC_FLOAT) */ + t0 = tcg_temp_new_i64(); + t1 = tcg_temp_new_i64(); + gen_reset_fpstatus(); + get_fpr(t0, rB(ctx->opcode)); + gen_helper_frsp(t1, tcg_env, t0); + set_fpr(rD(ctx->opcode), t1); + gen_helper_compute_fprf_float64(tcg_env, t1); + gen_helper_float_check_status(tcg_env); + if (unlikely(Rc(ctx->opcode) != 0)) { + gen_set_cr1_from_fpscr(ctx); + } +} /* fcfid */ GEN_FLOAT_B(cfid, 0x0E, 0x1A, 1, PPC2_FP_CVT_S64); /* fcfids */ @@ -348,6 +764,10 @@ static void gen_fcmpu(DisasContext *ctx) gen_exception(ctx, POWERPC_EXCP_FPU); return; } + if (native_fp(ctx) && native_fcmp_on()) { + native_fcmpu(ctx, crfD(ctx->opcode), rA(ctx->opcode), rB(ctx->opcode)); + return; + } t0 = tcg_temp_new_i64(); t1 = tcg_temp_new_i64(); gen_reset_fpstatus(); @@ -515,6 +935,7 @@ static void gen_mcrfs(DisasContext *ctx) bfa = crfS(ctx->opcode); nibble = 7 - bfa; shift = 4 * nibble; + gen_fprf_sync(); tcg_gen_shri_tl(tmp, cpu_fpscr, shift); tcg_gen_trunc_tl_i32(cpu_crf[crfD(ctx->opcode)], tmp); tcg_gen_andi_i32(cpu_crf[crfD(ctx->opcode)], cpu_crf[crfD(ctx->opcode)], @@ -533,6 +954,7 @@ static TCGv_i64 place_from_fpscr(int rt, uint64_t mask) TCGv_i64 fpscr = tcg_temp_new_i64(); TCGv_i64 fpscr_masked = tcg_temp_new_i64(); + gen_fprf_sync(); tcg_gen_extu_tl_i64(fpscr, cpu_fpscr); tcg_gen_andi_i64(fpscr_masked, fpscr, mask); set_fpr(rt, fpscr_masked); @@ -588,6 +1010,7 @@ static bool trans_MFFSCE(DisasContext *ctx, arg_X_t *a) gen_reset_fpstatus(); fpscr = place_from_fpscr(a->rt, UINT64_MAX); store_fpscr_masked(fpscr, FP_ENABLES, tcg_constant_i64(0), 0x0003); + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; /* HFLAGS_FP_FAST */ return true; } @@ -604,6 +1027,7 @@ static bool trans_MFFSCRN(DisasContext *ctx, arg_X_tb *a) gen_reset_fpstatus(); fpscr = place_from_fpscr(a->rt, FP_DRN | FP_ENABLES | FP_NI | FP_RN); store_fpscr_masked(fpscr, FP_RN, t1, 0x0001); + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; /* HFLAGS_FP_FAST */ return true; } @@ -635,6 +1059,7 @@ static bool trans_MFFSCRNI(DisasContext *ctx, arg_X_imm2 *a) gen_reset_fpstatus(); fpscr = place_from_fpscr(a->rt, FP_DRN | FP_ENABLES | FP_NI | FP_RN); store_fpscr_masked(fpscr, FP_RN, t1, 0x0001); + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; /* HFLAGS_FP_FAST */ return true; } @@ -680,6 +1105,8 @@ static void gen_mtfsb0(DisasContext *ctx) tcg_gen_trunc_tl_i32(cpu_crf[1], cpu_fpscr); tcg_gen_shri_i32(cpu_crf[1], cpu_crf[1], FPSCR_OX); } + /* HFLAGS_FP_FAST may have changed: look up the next TB afresh */ + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; } /* mtfsb1 */ @@ -702,6 +1129,8 @@ static void gen_mtfsb1(DisasContext *ctx) } /* We can raise a deferred exception */ gen_helper_fpscr_check_status(tcg_env); + /* HFLAGS_FP_FAST may have changed: look up the next TB afresh */ + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; } /* mtfsf */ @@ -738,6 +1167,8 @@ static void gen_mtfsf(DisasContext *ctx) } /* We can raise a deferred exception */ gen_helper_fpscr_check_status(tcg_env); + /* HFLAGS_FP_FAST may have changed: look up the next TB afresh */ + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; } /* mtfsfi */ @@ -767,6 +1198,8 @@ static void gen_mtfsfi(DisasContext *ctx) } /* We can raise a deferred exception */ gen_helper_fpscr_check_status(tcg_env); + /* HFLAGS_FP_FAST may have changed: look up the next TB afresh */ + ctx->base.is_jmp = DISAS_CHAIN_UPDATE; } static void gen_qemu_ld32fs(DisasContext *ctx, TCGv_i64 dest, TCGv addr) diff --git a/tcg/aarch64/tcg-target-has.h b/tcg/aarch64/tcg-target-has.h index dda1fcae5db6e..dccc1464be99c 100644 --- a/tcg/aarch64/tcg-target-has.h +++ b/tcg/aarch64/tcg-target-has.h @@ -110,6 +110,7 @@ #define TCG_TARGET_HAS_cmpsel_vec 0 #define TCG_TARGET_HAS_tst_vec 1 #define TCG_TARGET_HAS_tbl_vec 1 +#define TCG_TARGET_HAS_fp_vec 1 #define TCG_TARGET_extract_valid(type, ofs, len) 1 #define TCG_TARGET_sextract_valid(type, ofs, len) 1 diff --git a/tcg/aarch64/tcg-target.c.inc b/tcg/aarch64/tcg-target.c.inc index 9adadf389ea2c..0fb9d67ce5164 100644 --- a/tcg/aarch64/tcg-target.c.inc +++ b/tcg/aarch64/tcg-target.c.inc @@ -2835,6 +2835,43 @@ static void tcg_out_vec_op(TCGContext *s, TCGOpcode opc, } break; + case INDEX_op_fop_vec: + /* Scalar FADD/FSUB/FMUL/FDIV; ftype 01 double, 00 single. */ + { + static const uint32_t fop[4] = { + 0x1e202800, 0x1e203800, 0x1e200800, 0x1e201800, + }; + tcg_out32(s, fop[args[3]] | (vece == MO_64) << 22 + | (a2 & 0x1f) << 16 | (a1 & 0x1f) << 5 | (a0 & 0x1f)); + } + break; + case INDEX_op_ffma_vec: + /* + * r = a*c + b in PowerPC's four forms. AArch64's FMADD (n*m + a) + * and FNMSUB (n*m - a) give the first two with n = a, m = c, + * a = b. PowerPC's negated forms negate the rounded result, so an + * exact zero comes out -0; AArch64's FNMADD/FMSUB negate operands + * instead (+0), so use FMADD/FNMSUB and then FNEG. + */ + { + static const uint32_t fma[2] = { 0x1f000000, 0x1f208000 }; + uint32_t ft = (vece == MO_64) << 22; + + tcg_out32(s, fma[args[4] & 1] | ft | (a2 & 0x1f) << 16 + | (args[3] & 0x1f) << 10 | (a1 & 0x1f) << 5 + | (a0 & 0x1f)); + if (args[4] & 2) { + tcg_out32(s, 0x1e214000 | ft | (a0 & 0x1f) << 5 + | (a0 & 0x1f)); + } + } + break; + case INDEX_op_fcvt_vec: + /* FCVT Sd, Dn (0x1e624000) or FCVT Dd, Sn (0x1e22c000) */ + tcg_out32(s, (a2 ? 0x1e22c000 : 0x1e624000) + | (a1 & 0x1f) << 5 | (a0 & 0x1f)); + break; + case INDEX_op_tbl_vec: /* * Bytes 16-31 come from b by TBL on idx ^ 16 (indexes 0-15 map @@ -2902,6 +2939,10 @@ int tcg_can_emit_vec_op(TCGOpcode opc, TCGType type, unsigned vece) return vece < MO_64; case INDEX_op_tbl_vec: return type == TCG_TYPE_V128 && vece == MO_8; + case INDEX_op_fop_vec: + case INDEX_op_ffma_vec: + case INDEX_op_fcvt_vec: + return type == TCG_TYPE_V64 && (vece == MO_32 || vece == MO_64); default: return 0; @@ -3164,8 +3205,13 @@ tcg_target_op_def(TCGOpcode op, TCGType type, unsigned flags) return C_O1_I2(w, w, wN); case INDEX_op_cmp_vec: return C_O1_I2(w, w, wZ); + case INDEX_op_fop_vec: + return C_O1_I2(w, w, w); + case INDEX_op_fcvt_vec: + return C_O1_I1(w, w); case INDEX_op_bitsel_vec: case INDEX_op_tbl_vec: + case INDEX_op_ffma_vec: return C_O1_I3(w, w, w, w); case INDEX_op_aa64_sli_vec: return C_O1_I2(w, 0, w); diff --git a/tcg/tcg-has.h b/tcg/tcg-has.h index 04089dd666f6d..537ff56619d64 100644 --- a/tcg/tcg-has.h +++ b/tcg/tcg-has.h @@ -88,6 +88,9 @@ #else #define TCG_TARGET_MAYBE_vec 1 #endif +#ifndef TCG_TARGET_HAS_fp_vec +#define TCG_TARGET_HAS_fp_vec 0 +#endif #ifndef TCG_TARGET_HAS_tbl_vec #define TCG_TARGET_HAS_tbl_vec 0 #endif diff --git a/tcg/tcg-op-vec.c b/tcg/tcg-op-vec.c index 3aa4c4edd9bc6..8f6dd74354d02 100644 --- a/tcg/tcg-op-vec.c +++ b/tcg/tcg-op-vec.c @@ -786,6 +786,51 @@ void tcg_gen_tbl_vec(TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec idx) temp_arg(rt), temp_arg(at), temp_arg(bt), temp_arg(it)); } +/* + * Scalar floating point on V64 temps; see fop_vec/ffma_vec/fcvt_vec in + * tcg-opc.h. Callers check + * tcg_can_emit_vec_op(INDEX_op_fop_vec, TCG_TYPE_V64, vece) (all three + * are provided together). + */ +void tcg_gen_fcvt_vec(bool to_double, TCGv_vec r, TCGv_vec a) +{ + TCGTemp *rt = tcgv_vec_temp(r); + TCGTemp *at = tcgv_vec_temp(a); + + tcg_debug_assert(rt->base_type == TCG_TYPE_V64); + vec_gen_3(INDEX_op_fcvt_vec, TCG_TYPE_V64, MO_64, + temp_arg(rt), temp_arg(at), to_double); +} + +void tcg_gen_fop_vec(unsigned vece, unsigned op, TCGv_vec r, + TCGv_vec a, TCGv_vec b) +{ + TCGTemp *rt = tcgv_vec_temp(r); + TCGTemp *at = tcgv_vec_temp(a); + TCGTemp *bt = tcgv_vec_temp(b); + + tcg_debug_assert(rt->base_type == TCG_TYPE_V64); + tcg_debug_assert(op < 4 && (vece == MO_32 || vece == MO_64)); + vec_gen_4(INDEX_op_fop_vec, TCG_TYPE_V64, vece, + temp_arg(rt), temp_arg(at), temp_arg(bt), op); +} + +void tcg_gen_ffma_vec(unsigned vece, unsigned kind, TCGv_vec r, + TCGv_vec a, TCGv_vec c, TCGv_vec b) +{ + TCGOp *op = tcg_emit_op(INDEX_op_ffma_vec, 5); + + tcg_debug_assert(tcgv_vec_temp(r)->base_type == TCG_TYPE_V64); + tcg_debug_assert(kind < 4 && (vece == MO_32 || vece == MO_64)); + TCGOP_TYPE(op) = TCG_TYPE_V64; + TCGOP_VECE(op) = vece; + op->args[0] = temp_arg(tcgv_vec_temp(r)); + op->args[1] = temp_arg(tcgv_vec_temp(a)); + op->args[2] = temp_arg(tcgv_vec_temp(c)); + op->args[3] = temp_arg(tcgv_vec_temp(b)); + op->args[4] = kind; +} + void tcg_gen_cmpsel_vec(TCGCond cond, unsigned vece, TCGv_vec r, TCGv_vec a, TCGv_vec b, TCGv_vec c, TCGv_vec d) { diff --git a/tcg/tcg.c b/tcg/tcg.c index f91b4c4146783..38db0b7e09ca0 100644 --- a/tcg/tcg.c +++ b/tcg/tcg.c @@ -2423,6 +2423,11 @@ bool tcg_op_supported(TCGOpcode op, TCGType type, unsigned flags) case INDEX_op_tbl_vec: return type == TCG_TYPE_V128 && TCG_TARGET_HAS_v128 && TCG_TARGET_HAS_tbl_vec; + case INDEX_op_fop_vec: + case INDEX_op_ffma_vec: + case INDEX_op_fcvt_vec: + return type == TCG_TYPE_V64 && TCG_TARGET_HAS_v64 + && TCG_TARGET_HAS_fp_vec; default: tcg_debug_assert(op > INDEX_op_last_generic && op < NB_OPS); diff --git a/tests/ppc-vmx/link.ld b/tests/ppc-vmx/link.ld index 0b7afa7dfb594..83bc3f4c955af 100644 --- a/tests/ppc-vmx/link.ld +++ b/tests/ppc-vmx/link.ld @@ -1,9 +1,13 @@ -/* Raw mac99 firmware image: loaded at 0xfff00000, entered at +0x100. */ +/* + * Raw mac99 firmware image: loaded at 0xfff00000, entered at +0x100. + * macio-nvram covers 0xfff04000-0xfff07fff, so the code goes above it. + */ ENTRY(_start) SECTIONS { . = 0xfff00000; .head : { . += 0x100; KEEP(*(.text.start)) } + . = 0xfff08000; .text : { *(.text .text.*) } .rodata : { *(.rodata .rodata.* .sdata2 .sdata2.*) } /DISCARD/ : { *(.comment) *(.eh_frame) } diff --git a/tests/ppc-vmx/run.py b/tests/ppc-vmx/run.py index bd38c1a63ae85..8243dbd088ae4 100755 --- a/tests/ppc-vmx/run.py +++ b/tests/ppc-vmx/run.py @@ -1,7 +1,11 @@ #!/usr/bin/env python3 """Build vmx_test.c as a raw mac99 firmware image, run it, report results. -usage: run.py [path/to/qemu-system-ppc] +usage: run.py [--fpdiff | --fpdiff-strict] [path/to/qemu-system-ppc] + +--fpdiff runs the scalar FP cases with the inline FP ops off and on and +compares results and FPSCR; --fpdiff-strict compares the inline results +with softfloat's (PPC_STRICT_FP=1), whose FPSCR also has the inexact bits. Needs Homebrew llvm (clang with the PowerPC target) and lld. """ @@ -15,7 +19,8 @@ import time HERE = os.path.dirname(os.path.abspath(__file__)) -QEMU = (sys.argv[1] if len(sys.argv) > 1 else +ARGS = [a for a in sys.argv[1:] if not a.startswith('--')] +QEMU = (ARGS[0] if ARGS else os.path.join(HERE, '..', '..', 'build', 'qemu-system-ppc')) RESULTS = 0x10000 OPS = """vperm vperm(d=a) vperm(d=c) vperm(a=b) vsldoi vsldoi(d=b) @@ -88,9 +93,66 @@ def words(self, addr, n): return [int(x, 16) for x in re.findall(r'0x([0-9a-f]{8})(?!:)', out)][:n] +FPD_BASE = 0x01000000 +FPD_REC = 6 * 8 +FPD_OPS = ['fadd', 'fadds', 'fsub', 'fsubs', 'fmul', 'fmuls', 'fdiv', 'fdivs', + 'fmadd', 'fmadds', 'fmsub', 'fmsubs', 'fnmadd', 'fnmadds', + 'fnmsub', 'fnmsubs', 'frsp'] + + +def fpdiff(img, out, strict=False): + """Run the scalar FP cases as the reference and inline; compare them.""" + import struct + ref = 'softfloat' if strict else 'helper' + dumps = [] + for native in ('0', '1'): + sock = os.path.join(out, f'mon{native}.sock') + env = dict(os.environ, PPC_NATIVE_FP=native) + if strict and native == '0': + env['PPC_STRICT_FP'] = '1' + q = subprocess.Popen([QEMU, '-M', 'mac99', '-cpu', '7450', '-m', '64', + '-bios', img, '-display', 'none', + '-serial', 'none', '-monitor', + f'unix:{sock},server=on,wait=off'], + stdout=subprocess.DEVNULL, env=env) + try: + mon = Monitor(sock) + for _ in range(1200): + if mon.words(RESULTS, 1) == [0x564d5854]: + break + time.sleep(0.25) + else: + sys.exit('test did not finish') + n = mon.words(RESULTS + 0x283 * 4, 1)[0] + path = os.path.join(out, f'fpd{native}.bin') + mon.cmd(f'pmemsave {FPD_BASE:#x} {n * FPD_REC} "{path}"') + dumps.append(open(path, 'rb').read()) + finally: + q.kill() + n = len(dumps[0]) // FPD_REC + bad = 0 + for i in range(n): + r0 = struct.unpack_from('>6Q', dumps[0], i * FPD_REC) + r1 = struct.unpack_from('>6Q', dumps[1], i * FPD_REC) + if r0[:4] != r1[:4] or (not strict and r0 != r1): + bad += 1 + if bad <= 10: + st, op, form = (r0[5] >> 16) & 15, (r0[5] >> 8) & 0xff, r0[5] & 0xff + follow = ('mffs', 'fcmpu', 'mtfsb1', 'mcrfs')[(r0[5] >> 20) & 15] + print(f'MISMATCH {FPD_OPS[op]} form {form} fpscr_in {st} then {follow} ' + f'(cr {r0[5] >> 32:08x}/{r1[5] >> 32:08x}): ' + f'a={r0[0]:016x} c={r0[1]:016x} b={r0[2]:016x}') + print(f' {ref}: {r0[3]:016x} fpscr {r0[4] & 0xffffffff:08x}' + f' native: {r1[3]:016x} fpscr {r1[4] & 0xffffffff:08x}') + print(f'{n} FP cases compared (native vs {ref}), {bad} mismatches') + return bad + + def main(): out = tempfile.mkdtemp(prefix='ppc-vmx-') img = build(out) + if '--fpdiff' in sys.argv or '--fpdiff-strict' in sys.argv: + sys.exit(1 if fpdiff(img, out, '--fpdiff-strict' in sys.argv) else 0) sock = os.path.join(out, 'mon.sock') q = subprocess.Popen([QEMU, '-M', 'mac99', '-cpu', '7450', '-m', '64', '-bios', img, '-display', 'none', '-serial', 'none', diff --git a/tests/ppc-vmx/vmx_test.c b/tests/ppc-vmx/vmx_test.c index 9defd3348243f..5eebe19acc19f 100644 --- a/tests/ppc-vmx/vmx_test.c +++ b/tests/ppc-vmx/vmx_test.c @@ -584,6 +584,487 @@ static void bench(void) : "+v"(a.v) : "v"(b.v), "v"(c.v)); } res[0x204] = tb() - t0; + + /* lfs; fmadds; stfs on an array of normal singles, x4 per iteration */ + { + float buf[64]; + float k = 1.0f; + for (i = 0; i < 64; i++) { + buf[i] = 1.0f + i * 0.125f; + } + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + float *p = &buf[(i * 4) & 63]; + asm volatile("lfs 1,0(%0)\n\tfmadds 1,1,%1,%1\n\tstfs 1,0(%0)\n\t" + "lfs 2,4(%0)\n\tfmadds 2,2,%1,%1\n\tstfs 2,4(%0)\n\t" + "lfs 3,8(%0)\n\tfmadds 3,3,%1,%1\n\tstfs 3,8(%0)\n\t" + "lfs 4,12(%0)\n\tfmadds 4,4,%1,%1\n\tstfs 4,12(%0)" + : : "b"(p), "f"(k) : "fr1", "fr2", "fr3", "fr4", "memory"); + k = k * 0.5f + 0.25f; + } + res[0x205] = tb() - t0; + } + + /* scalar FP latency: dependent chains vs independent vs integer */ + { + double x = 1.0, y = 1.0, z = 1.0, w = 1.0, h = 0.5, q = 0.25; + uint32_t r = 1, k = 3; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("fmadd %0,%0,%1,%2\n\tfmadd %0,%0,%1,%2\n\t" + "fmadd %0,%0,%1,%2\n\tfmadd %0,%0,%1,%2" + : "+f"(x) : "f"(h), "f"(q)); + } + res[0x206] = tb() - t0; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("fmadd %0,%0,%4,%5\n\tfmadd %1,%1,%4,%5\n\t" + "fmadd %2,%2,%4,%5\n\tfmadd %3,%3,%4,%5" + : "+f"(x), "+f"(y), "+f"(z), "+f"(w) : "f"(h), "f"(q)); + } + res[0x207] = tb() - t0; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("fadd %0,%0,%1\n\tfadd %0,%0,%1\n\t" + "fadd %0,%0,%1\n\tfadd %0,%0,%1" + : "+f"(x) : "f"(q)); + } + res[0x208] = tb() - t0; + + t0 = tb(); + for (i = 0; i < BENCH_ITERS; i++) { + asm volatile("add %0,%0,%1\n\tadd %0,%0,%1\n\t" + "add %0,%0,%1\n\tadd %0,%0,%1" + : "+r"(r) : "r"(k)); + } + res[0x209] = tb() - t0; + res[0x20a] = r ^ (uint32_t)(x + y + z + w); + } + + /* Mandelbrot escape loop, as compiled C: fcmpu decides every exit */ + { + uint32_t total = 0; + int px, py, n; + + t0 = tb(); + for (py = 0; py < 48; py++) { + for (px = 0; px < 64; px++) { + double cr = -2.0 + px * (2.5 / 64), ci = -1.25 + py * (2.5 / 48); + double zr = 0, zi = 0, zr2 = 0, zi2 = 0; + for (n = 0; n < 256 && zr2 + zi2 <= 4.0; n++) { + zi = 2.0 * zr * zi + ci; + zr = zr2 - zi2 + cr; + zr2 = zr * zr; + zi2 = zi * zi; + } + total += n; + } + } + res[0x20b] = tb() - t0; + res[0x20c] = total; + } + + /* Geekbench 2.2's Mandelbrot inner loop (GCC 4.0), instruction for + instruction, points that never escape: 255 iterations each */ + { + double c[4] = { 0.25, 0.0, 4.0, 0.0 }; /* cr, ci, escape radius^2 */ + uint32_t n = 0; + + t0 = tb(); + for (i = 0; i < 1000; i++) { + if (i == 500) { + res[0x20f] = tb() - t0; /* first half: never escapes */ + c[0] = 1.5; /* then: escapes after 2 */ + c[1] = 0.5; + } + if (i >= 500) { + int j; + for (j = 0; j < 100; j++) { + asm volatile( + "lfd 8,0(%1)\n\tlfd 6,8(%1)\n\tlfd 7,16(%1)\n\t" + "fmr 9,6\n\tfmr 11,8\n\tfmr 10,9\n\t" + "li 0,255\n\tmtctr 0\n" + "1:\tfmul 0,10,10\n\taddi %0,%0,1\n\t" + "fmsub 0,11,11,0\n\tfadd 11,8,0\n\tfadd 12,11,11\n\t" + "fsub 13,11,8\n\tfmadd 10,10,12,9\n\tfsub 0,10,9\n\t" + "fmul 0,0,0\n\tfmadd 13,13,13,0\n\tfcmpu 7,13,7\n\t" + "cror 30,29,30\n\tbeq 7,2f\n\tbdnz 1b\n2:" + : "+r"(n) : "b"(c) + : "fr0", "fr6", "fr7", "fr8", "fr9", "fr10", "fr11", "fr12", + "fr13", "ctr", "cr7", "r0"); + } + continue; + } + asm volatile( + "lfd 8,0(%1)\n\tlfd 6,8(%1)\n\tlfd 7,16(%1)\n\t" + "fmr 9,6\n\tfmr 11,8\n\tfmr 10,9\n\t" + "li 0,255\n\tmtctr 0\n" + "1:\tfmul 0,10,10\n\taddi %0,%0,1\n\t" + "fmsub 0,11,11,0\n\tfadd 11,8,0\n\tfadd 12,11,11\n\t" + "fsub 13,11,8\n\tfmadd 10,10,12,9\n\tfsub 0,10,9\n\t" + "fmul 0,0,0\n\tfmadd 13,13,13,0\n\tfcmpu 7,13,7\n\t" + "cror 30,29,30\n\tbeq 7,2f\n\tbdnz 1b\n2:" + : "+r"(n) : "b"(c) + : "fr0", "fr6", "fr7", "fr8", "fr9", "fr10", "fr11", "fr12", + "fr13", "ctr", "cr7", "r0"); + } + res[0x20d] = tb() - t0; + res[0x20e] = n; + } + + /* Geekbench 2.2's whole Mandelbrot routine (0x26ac0-0x26b98): rows and + columns converted to double through memory (stw, stw, lfd), the + loop, and the flop count kept in r27:r28 with addc/adde */ + { + double k[5] = { + 0.0, -2.0, 4.0, 1.25, 0.0, /* magic (set below), cr0, esc, ci0 */ + }; + uint32_t buf[4]; + uint32_t lo = 0, hi = 0; + union { uint64_t u; double d; } magic = { 0x4330000080000000ull }; + + k[0] = magic.d; + k[4] = 0.046875; /* 3/64: rows and columns */ + t0 = tb(); + for (i = 0; i < 4; i++) { + asm volatile( + "lfd 5,32(%[k])\n\t" /* row scale */ + "lfd 6,32(%[k])\n\t" /* column scale */ + "li 10,0\n\tli 26,48\n\tli 30,64\n\t" + "cmpwi 6,30,0\n" + "3:\txoris 2,10,0x8000\n\tlis 0,0x4330\n\tlfd 13,0(%[k])\n\t" + "li 9,0\n\tstw 2,12(%[b])\n\tstw 0,8(%[b])\n\t" + "lfd 0,8(%[b])\n\tfsub 0,0,13\n\tlfd 13,24(%[k])\n\t" + "fmsub 8,5,0,13\n" + "4:\txoris 2,9,0x8000\n\tlis 0,0x4330\n\tlfd 13,0(%[k])\n\t" + "lfd 12,8(%[k])\n\tfmr 11,8\n\tstw 0,0(%[b])\n\tstw 2,4(%[b])\n\t" + "li 0,0xff\n\tmtctr 0\n\tlfd 7,16(%[k])\n\tli 2,0\n\t" + "lfd 0,0(%[b])\n\tfsub 0,0,13\n\tfmadd 9,6,0,12\n\tfmr 10,9\n" + "1:\tfmul 0,10,10\n\taddi 2,2,1\n\t" + "fmsub 0,11,11,0\n\tfadd 11,8,0\n\tfadd 12,11,11\n\t" + "fsub 13,11,8\n\tfmadd 10,10,12,9\n\tfsub 0,10,9\n\t" + "fmul 0,0,0\n\tfmadd 13,13,13,0\n\tfcmpu 7,13,7\n\t" + "cror 30,29,30\n\tbeq 7,2f\n\tbdnz 1b\n" + "2:\taddi 9,9,1\n\tmulli 2,2,14\n\tcmpw 7,30,9\n\tmr 3,2\n\t" + "li 2,0\n\taddc %[lo],%[lo],3\n\tadde %[hi],%[hi],2\n\t" + "bne 7,4b\n\t" + "addi 10,10,1\n\tcmpw 7,26,10\n\tbeq 7,5f\n\t" + "ble 6,3b\n\tb 3b\n" + "5:" + : [lo] "+r"(lo), [hi] "+r"(hi) + : [k] "b"(k), [b] "b"(buf) + : "r0", "r2", "r3", "r9", "r10", "r26", "r30", + "fr0", "fr5", "fr6", "fr7", "fr8", "fr9", "fr10", "fr11", + "fr12", "fr13", "ctr", "cr6", "cr7", "xer", "memory"); + k[4] = 0.046875 + i * 0.001; /* a slightly different image each time */ + } + res[0x210] = tb() - t0; + res[0x211] = lo; + } +} + +/* + * Scalar lfs/stfs: single <-> double conversion, which the translator + * inlines for normal numbers (target/ppc/translate/fp-impl.c.inc). The + * references are helper_todouble/helper_tosingle's logic in integer code. + * lfd/stfd move the 64-bit register image in and out unconverted. + */ +static uint64_t ref_todouble(uint32_t a) +{ + uint32_t abs = a & 0x7fffffff, e = (a >> 23) & 0xff; + uint64_t r = (uint64_t)(a >> 31) << 63; + + if (abs >= 0x00800000) { + if (e == 0xff) { + return r | (0x7ffULL << 52) | (uint64_t)(a & 0x7fffff) << 29; + } + return r | (uint64_t)(e + 896) << 52 | (uint64_t)(a & 0x7fffff) << 29; + } + if (abs) { + int shift = __builtin_clz(abs) - 8; + r |= (uint64_t)(-126 - shift + 1023 - 1) << 52; + r += (uint64_t)abs << (52 - 23 + shift); + } + return r; +} + +static uint32_t ref_tosingle(uint64_t a) +{ + int e = (a >> 52) & 0x7ff; + uint32_t r; + + if (e > 896) { + return (uint32_t)(a >> 62) << 30 | (uint32_t)((a >> 29) & 0x3fffffff); + } + r = (uint32_t)(a >> 63) << 31; + if (e >= 874) { + r |= ((1ULL << 52) | (a & 0xfffffffffffffULL)) >> (896 + 30 - e); + } + return r; +} + +static uint64_t hw_lfs(uint32_t s) +{ + volatile uint32_t in = s; + volatile uint64_t out; + double f; + asm volatile("lfs %0,0(%1)" : "=f"(f) : "b"(&in) : "memory"); + asm volatile("stfd %0,0(%1)" : : "f"(f), "b"(&out) : "memory"); + return out; +} + +static uint32_t hw_stfs(uint64_t d) +{ + volatile uint64_t in = d; + volatile uint32_t out; + double f; + asm volatile("lfd %0,0(%1)" : "=f"(f) : "b"(&in) : "memory"); + asm volatile("stfs %0,0(%1)" : : "f"(f), "b"(&out) : "memory"); + return out; +} + +static void fp_log(uint32_t kind, uint64_t in, uint64_t got, uint64_t exp) +{ + volatile uint32_t *p = res + 0x2a0 + (res[0x281] - 1) * 8; + if (res[0x281] > 4) { + return; + } + p[0] = kind; + p[1] = in >> 32; p[2] = in; + p[3] = got >> 32; p[4] = got; + p[5] = exp >> 32; p[6] = exp; +} + +static void check_lfs(uint32_t s) +{ + uint64_t got = hw_lfs(s), exp = ref_todouble(s); + res[0x280]++; + if (got != exp) { + res[0x281]++; + fp_log(0, s, got, exp); + } +} + +static void check_stfs(uint64_t d) +{ + uint32_t got = hw_stfs(d), exp = ref_tosingle(d); + res[0x280]++; + if (got != exp) { + res[0x281]++; + fp_log(1, d, got, exp); + } +} + +static void scalar_ldst(uint32_t *seed) +{ + static const uint32_t s_edge[] = { + 0x00000000, 0x80000000, 0x00000001, 0x807fffff, 0x00400000, + 0x00800000, 0x80800000, 0x3f800000, 0xbf800000, 0x7f7fffff, + 0xff7fffff, 0x7f800000, 0xff800000, 0x7fc00000, 0x7f800001, + 0xffbfffff, 0x40000000, 0x3fffffff, 0x7f000000, 0x00ffffff, + }; + int i, e; + + for (i = 0; i < (int)(sizeof(s_edge) / sizeof(s_edge[0])); i++) { + check_lfs(s_edge[i]); + check_stfs(ref_todouble(s_edge[i])); + } + /* stfs around its exponent boundaries (874, 896/897, 0x7ff) */ + for (e = 860; e < 910; e++) { + for (i = 0; i < 20; i++) { + uint64_t m = (uint64_t)rnd(seed) << 32 | rnd(seed); + check_stfs((m & 0x800fffffffffffffULL) | (uint64_t)e << 52); + } + } + for (i = 0; i < 20; i++) { + uint64_t m = (uint64_t)rnd(seed) << 32 | rnd(seed); + check_stfs(m | 0x7ff0000000000000ULL); + check_stfs(m & 0x800fffffffffffffULL); + } + for (i = 0; i < 20000; i++) { + uint32_t s = rnd(seed); + check_lfs(s); + check_stfs((uint64_t)rnd(seed) << 32 | rnd(seed)); + } +} + + +/* + * Differential test for the inline scalar FP ops (fp-impl.c.inc + * native_fp_op()): every A-form arithmetic op, with the target distinct + * from or equal to each input, on operands from all the classes that + * decide between the inline path and the helper (zeros, denormals, + * infinities, quiet and signalling NaNs, exact and inexact singles, + * cancellation, overflow). Each case stores the result and FPSCR at + * FPD_BASE; run.py --fpdiff runs this with PPC_NATIVE_FP=0 and =1 and + * compares the two memory images. + */ +#define FPD_BASE 0x01000000u +#define FPD_BUF 0x00100000u +#define FPD_REC 6 /* a, c, b, result, fpscr, case id (u64) */ +/* the case id: FPSCR state << 16 | op << 8 | form, follow-up << 20, CR << 32 */ + +static uint64_t fpd_pool(uint32_t *seed) +{ + static const uint64_t special[] = { + 0x0000000000000000ull, 0x8000000000000000ull, /* +-0 */ + 0x0000000000000001ull, 0x800fffffffffffffull, /* denormals */ + 0x0010000000000000ull, 0x8010000000000000ull, /* min normal */ + 0x3ff0000000000000ull, 0xbff0000000000000ull, /* +-1 */ + 0x7fefffffffffffffull, 0xffefffffffffffffull, /* max */ + 0x7ff0000000000000ull, 0xfff0000000000000ull, /* +-inf */ + 0x7ff8000000000000ull, 0xfff8000000000123ull, /* qNaN */ + 0x7ff0000000000001ull, 0xfff4000000000000ull, /* sNaN */ + 0x3810000000000000ull, 0x36a0000000000000ull, /* single min normal, single denormal */ + 0x47efffffe0000000ull, 0x4800000000000000ull, /* single max, just above */ + 0x3ff0000000000001ull, 0x4000000010000000ull, /* inexact singles */ + 0x4059000000000000ull, 0xc059000000000000ull, /* +-100 */ + 0x8000000000000001ull, 0x000fffffffffffffull, /* -min, +max denormal */ + 0x380fffffffffffffull, 0xb80ffffff0000000ull, /* just under 2^-126 */ + 0x47efffffefffffffull, 0xc7effffff0000000ull, /* near single max */ + 0x3ff0000010000000ull, 0x3ff0000030000000ull, /* single ties */ + }; + uint32_t r = rnd(seed); + uint64_t m = (uint64_t)rnd(seed) << 32 | rnd(seed); + + switch (r & 7) { + case 0: case 1: + return special[(r >> 3) % (sizeof(special) / sizeof(special[0]))]; + case 2: case 3: /* exact single, moderate exponent */ + return (m & 0x800fffffe0000000ull) | (uint64_t)(1000 + (r >> 8) % 46) << 52; + case 4: /* double, moderate exponent */ + return (m & 0x800fffffffffffffull) | (uint64_t)(990 + (r >> 8) % 70) << 52; + case 5: /* exact single, full single range */ + return (m & 0x800fffffe0000000ull) | (uint64_t)(897 + (r >> 8) % 254) << 52; + default: /* anything */ + return m; + } +} + +#define FPD_ASM(insn) \ + asm volatile("lfd 2,0(%0)\n\tlfd 3,8(%0)\n\tlfd 4,16(%0)\n\tlfd 1,40(%0)\n\t" \ + "lfd 5,48(%0)\n\tmtfsf 0xff,5\n\t" insn \ + : : "b"(buf) : "fr1", "fr2", "fr3", "fr4", "fr5", "memory") +#define FPD_OUT(t) asm volatile("stfd " #t ",24(%0)" : : "b"(buf) : "memory") + +/* one op, four target choices: f1 (distinct), f2 (=A), f3 (=C), f4 (=B) */ +#define FPD_OP3(m) \ + case 0: FPD_ASM(m " 1,2,3,4"); FPD_OUT(1); break; \ + case 1: FPD_ASM(m " 2,2,3,4"); FPD_OUT(2); break; \ + case 2: FPD_ASM(m " 3,2,3,4"); FPD_OUT(3); break; \ + case 3: FPD_ASM(m " 4,2,3,4"); FPD_OUT(4); break; +#define FPD_OPB(m) \ + case 0: FPD_ASM(m " 1,2,4"); FPD_OUT(1); break; \ + case 1: FPD_ASM(m " 2,2,4"); FPD_OUT(2); break; \ + case 2: FPD_ASM(m " 4,4,2"); FPD_OUT(4); break; \ + case 3: FPD_ASM(m " 4,2,4"); FPD_OUT(4); break; +#define FPD_OPR(m) \ + case 0: FPD_ASM(m " 1,4"); FPD_OUT(1); break; \ + case 1: FPD_ASM(m " 4,4"); FPD_OUT(4); break; \ + case 2: FPD_ASM(m " 1,2"); FPD_OUT(1); break; \ + case 3: FPD_ASM(m " 2,2"); FPD_OUT(2); break; +#define FPD_OPC(m) \ + case 0: FPD_ASM(m " 1,2,3"); FPD_OUT(1); break; \ + case 1: FPD_ASM(m " 2,2,3"); FPD_OUT(2); break; \ + case 2: FPD_ASM(m " 3,2,3"); FPD_OUT(3); break; \ + case 3: FPD_ASM(m " 3,3,2"); FPD_OUT(3); break; + +static void fpd_one(volatile uint64_t *buf, int op, int form) +{ + switch (op) { + case 0: switch (form) { FPD_OPB("fadd") } break; + case 1: switch (form) { FPD_OPB("fadds") } break; + case 2: switch (form) { FPD_OPB("fsub") } break; + case 3: switch (form) { FPD_OPB("fsubs") } break; + case 4: switch (form) { FPD_OPC("fmul") } break; + case 5: switch (form) { FPD_OPC("fmuls") } break; + case 6: switch (form) { FPD_OPB("fdiv") } break; + case 7: switch (form) { FPD_OPB("fdivs") } break; + case 8: switch (form) { FPD_OP3("fmadd") } break; + case 9: switch (form) { FPD_OP3("fmadds") } break; + case 10: switch (form) { FPD_OP3("fmsub") } break; + case 11: switch (form) { FPD_OP3("fmsubs") } break; + case 12: switch (form) { FPD_OP3("fnmadd") } break; + case 13: switch (form) { FPD_OP3("fnmadds") } break; + case 14: switch (form) { FPD_OP3("fnmsub") } break; + case 15: switch (form) { FPD_OP3("fnmsubs") } break; + case 16: switch (form) { FPD_OPR("frsp") } break; + } +} + +/* + * What reads FPSCR after the op, in a separate asm (maybe a separate TB): + * mffs alone, or after an instruction that changes or reads part of FPRF. + * The CR is returned for mcrfs. + */ +static uint32_t fpd_tail(volatile uint64_t *buf, int follow) +{ + uint32_t cr = 0; + + switch (follow) { + case 0: + asm volatile("mffs 5\n\tstfd 5,32(%0)" + : : "b"(buf) : "fr5", "memory"); + break; + case 1: /* FPCC only, C kept */ + asm volatile("fcmpu 1,2,4\n\tmffs 5\n\tstfd 5,32(%1)\n\tmfcr %0" + : "=r"(cr) : "b"(buf) : "fr5", "cr1", "memory"); + break; + case 2: /* one FPCC bit (FU) */ + asm volatile("mtfsb1 19\n\tmffs 5\n\tstfd 5,32(%0)" + : : "b"(buf) : "fr5", "memory"); + break; + default: /* FPCC to CR1 */ + asm volatile("mcrfs 1,4\n\tmffs 5\n\tstfd 5,32(%1)\n\tmfcr %0" + : "=r"(cr) : "b"(buf) : "fr5", "cr1", "memory"); + break; + } + return cr; +} + +static void fp_diff(uint32_t *seed) +{ + volatile uint64_t *buf = (volatile uint64_t *)FPD_BUF; + volatile uint64_t *out = (volatile uint64_t *)FPD_BASE; + uint32_t n = 0; + /* FPSCR states: fast mode, then round-toward-zero (helper only) */ + static const uint64_t fpscr_in[2] = { 0, 1 }; + + for (int st = 0; st < 2; st++) { + for (int it = 0; it < (st ? 300 : 3000); it++) { + uint64_t a = fpd_pool(seed), c = fpd_pool(seed), b = fpd_pool(seed); + uint32_t k = rnd(seed); + if ((k & 15) == 0) { + b = a; /* x - x, x + -x shapes */ + } else if ((k & 15) == 1) { + b = a ^ 0x8000000000000000ull; + } + for (int op = 0; op < 17; op++) { + for (int form = 0; form < 4; form++) { + buf[0] = a; buf[1] = c; buf[2] = b; + buf[5] = 0x7ff8dead0000beefull; /* old f1 */ + buf[6] = fpscr_in[st]; + int follow = it & 3; + uint32_t cr; + + fpd_one(buf, op, form); + cr = fpd_tail(buf, follow); + out[0] = a; out[1] = c; out[2] = b; + out[3] = buf[3]; out[4] = buf[4]; + out[5] = (uint64_t)cr << 32 | follow << 20 | + st << 16 | op << 8 | form; + out += FPD_REC; + n++; + } + } + } + } + res[0x283] = n; + /* back to FPSCR 0: round to nearest, as the benchmarks expect */ + asm volatile("mtfsfi 7,0"); } int main(void) @@ -636,6 +1117,8 @@ int main(void) } res[1] = checks; res[2] = fails; + scalar_ldst(&seed); + fp_diff(&seed); bench(); res[0] = 0x564d5854; /* 'VMXT' */ return 0; From bf42e76e4e73b6ddab28a67a107e4d1e8742c987 Mon Sep 17 00:00:00 2001 From: Spartan0285 <291227+Spartan0285@users.noreply.github.com> Date: Sat, 19 Sep 2026 20:16:01 -0400 Subject: [PATCH 12/14] target/ppc: optional page-precise tlbie for 32-bit hash MMU guests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tlbie marks the whole TLB for flushing, which the architecture allows since real CPUs invalidate a congruence class. Remembering the pages tlbie named and flushing only those is available under PPC_TLBIE=page. It stays off by default: it measures the same as the faithful behaviour once emptying the jump cache is O(1) (fork+exec and allocation benchmarks in a Tiger guest, min of five runs), and there is no reason to deviate from the architecture for nothing. Opt-in: PPC_TLBIE=page. Off by default, so the architectural behaviour is unchanged. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- target/ppc/cpu.h | 11 +++++++++++ target/ppc/helper_regs.c | 14 ++++++++++++++ target/ppc/mmu_helper.c | 32 +++++++++++++++++++++++++++++--- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/target/ppc/cpu.h b/target/ppc/cpu.h index c5135c88eb036..99257eefc7a5f 100644 --- a/target/ppc/cpu.h +++ b/target/ppc/cpu.h @@ -1288,6 +1288,17 @@ struct CPUArchState { uint32_t tlb_need_flush; /* Delayed flush needed */ #define TLB_NEED_LOCAL_FLUSH 0x1 #define TLB_NEED_GLOBAL_FLUSH 0x2 +#define TLB_NEED_PAGE_FLUSH 0x4 +/* + * Pages named by tlbie since the last flush. A 32-bit hash MMU guest + * (Mac OS X) invalidates single pages constantly; turning each of those + * into a whole-TLB flush, as the architecture's congruence-class wording + * would allow, costs far more than flushing the pages it actually named. + * Past this many pending pages a full flush is cheaper anyway. + */ +#define PPC_TLB_PENDING_PAGES 64 + target_ulong tlb_flush_pages[PPC_TLB_PENDING_PAGES]; + int tlb_flush_npages; #endif /* Other registers */ diff --git a/target/ppc/helper_regs.c b/target/ppc/helper_regs.c index e93bbb5c4d97b..b2dc3b0a447bf 100644 --- a/target/ppc/helper_regs.c +++ b/target/ppc/helper_regs.c @@ -381,6 +381,8 @@ void check_tlb_flush(CPUPPCState *env, bool global) if (global && (env->tlb_need_flush & TLB_NEED_GLOBAL_FLUSH)) { env->tlb_need_flush &= ~TLB_NEED_GLOBAL_FLUSH; env->tlb_need_flush &= ~TLB_NEED_LOCAL_FLUSH; + env->tlb_need_flush &= ~TLB_NEED_PAGE_FLUSH; + env->tlb_flush_npages = 0; tlb_flush_all_cpus_synced(cs); return; } @@ -388,7 +390,19 @@ void check_tlb_flush(CPUPPCState *env, bool global) /* Then handle local ones */ if (env->tlb_need_flush & TLB_NEED_LOCAL_FLUSH) { env->tlb_need_flush &= ~TLB_NEED_LOCAL_FLUSH; + env->tlb_need_flush &= ~TLB_NEED_PAGE_FLUSH; + env->tlb_flush_npages = 0; tlb_flush(cs); + return; + } + + /* Otherwise only the pages tlbie named have to go. */ + if (env->tlb_need_flush & TLB_NEED_PAGE_FLUSH) { + env->tlb_need_flush &= ~TLB_NEED_PAGE_FLUSH; + for (int i = 0; i < env->tlb_flush_npages; i++) { + tlb_flush_page(cs, env->tlb_flush_pages[i]); + } + env->tlb_flush_npages = 0; } } #endif /* !CONFIG_USER_ONLY */ diff --git a/target/ppc/mmu_helper.c b/target/ppc/mmu_helper.c index 236f4933b8f27..e8100ee6d0c68 100644 --- a/target/ppc/mmu_helper.c +++ b/target/ppc/mmu_helper.c @@ -290,6 +290,23 @@ void ppc_tlb_invalidate_all(CPUPPCState *env) } } +/* + * Whether tlbie flushes the whole TLB, as the architecture allows and QEMU + * has always done, or only the page it names (PPC_TLBIE=page). Flushing + * just the named pages sounds better and measures the same once emptying + * the TB jump cache is O(1), so the faithful behaviour stays the default. + */ +static bool ppc_tlbie_flushes_all(void) +{ + static int mode = -1; + + if (mode < 0) { + const char *s = getenv("PPC_TLBIE"); + mode = !(s && !strcmp(s, "page")); + } + return mode; +} + void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr) { #if !defined(FLUSH_ALL_TLBS) @@ -314,10 +331,19 @@ void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr) /* * Actual CPUs invalidate entire congruence classes based on * the geometry of their TLBs and some OSes take that into - * account, we just mark the TLB to be flushed later (context - * synchronizing event or sync instruction on 32-bit). + * account. Remember the page this tlbie named instead, and flush + * just those at the next context-synchronizing event; an OS that + * leans on congruence-class behaviour (rather than naming every + * page it changes, as Darwin and Linux do) needs the default. */ - env->tlb_need_flush |= TLB_NEED_LOCAL_FLUSH; + if (ppc_tlbie_flushes_all()) { + env->tlb_need_flush |= TLB_NEED_LOCAL_FLUSH; + } else if (env->tlb_flush_npages < PPC_TLB_PENDING_PAGES) { + env->tlb_flush_pages[env->tlb_flush_npages++] = addr; + env->tlb_need_flush |= TLB_NEED_PAGE_FLUSH; + } else { + env->tlb_need_flush |= TLB_NEED_LOCAL_FLUSH; + } break; default: /* Should never reach here with other MMU models */ From 758a336de5e09be65ea55c4057f75780f71e91fb Mon Sep 17 00:00:00 2001 From: Teufelhunden-0311 <106038146+Teufelhunden-0311@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:45:46 -0700 Subject: [PATCH 13/14] target/ppc: keep a QEMU TLB per segment register set on 32-bit hash MMUs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 32-bit hash MMU's TLB is tagged with the VSID, so reloading the segment registers keeps it. Mac OS X reloads 12 of the 16 on every exception entry and exit, and QEMU flushed its whole TLB each time, up to 50,000 times a second. Give each of the 4 most recently used sets of segment register values its own pair of MMU indexes (index | slot << 2, the TB's cs_base holding the slot) and evict the least recently used set instead of flushing. tlbie and tlbia still flush every set. About 90% of switches find their set cached; Geekbench 2 integer on Tiger goes from 1190 to 1242. PPC_SR_SLOTS=0 restores the flush. PPC_TLBIE=page now flushes the named page in all 16 segments, since tlbie ignores the segment number and a page can be mapped through another segment register or in another set's TLB. Opt-in: PPC_SR_SLOTS=1. On Tiger the slots made the Quartz Extreme desktop much slower (opening a folder took up to 7 s, Dashboard ran at about 1 fps instead of 7), so by default the segment registers flush the TLB as before and only the first slot is used. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- target/ppc/cpu.h | 29 ++++++++++++++- target/ppc/helper_regs.c | 23 ++++++++++-- target/ppc/machine.c | 3 ++ target/ppc/mmu_helper.c | 79 +++++++++++++++++++++++++++++++++++++++- target/ppc/translate.c | 4 ++ 5 files changed, 132 insertions(+), 6 deletions(-) diff --git a/target/ppc/cpu.h b/target/ppc/cpu.h index 99257eefc7a5f..072df9cb6427a 100644 --- a/target/ppc/cpu.h +++ b/target/ppc/cpu.h @@ -1289,6 +1289,7 @@ struct CPUArchState { #define TLB_NEED_LOCAL_FLUSH 0x1 #define TLB_NEED_GLOBAL_FLUSH 0x2 #define TLB_NEED_PAGE_FLUSH 0x4 +#define TLB_NEED_SR_SWITCH 0x8 /* segment registers changed */ /* * Pages named by tlbie since the last flush. A 32-bit hash MMU guest * (Mac OS X) invalidates single pages constantly; turning each of those @@ -1299,6 +1300,15 @@ struct CPUArchState { #define PPC_TLB_PENDING_PAGES 64 target_ulong tlb_flush_pages[PPC_TLB_PENDING_PAGES]; int tlb_flush_npages; +/* + * The segment register sets that have their own QEMU TLB on a 32-bit hash + * MMU (see ppc_mmu_slot_sync), each with its last use; 0 means unused. + */ +#define PPC_MMU_SLOTS 4 + target_ulong mmu_slot_sr[PPC_MMU_SLOTS][16]; + uint64_t mmu_slot_used[PPC_MMU_SLOTS]; + uint64_t mmu_slot_clock; + int mmu_slot; /* the current set's slot */ #endif /* Other registers */ @@ -1663,6 +1673,8 @@ void store_40x_tsr(CPUPPCState *env, target_ulong val); void store_booke_tcr(CPUPPCState *env, target_ulong val); void store_booke_tsr(CPUPPCState *env, target_ulong val); void ppc_tlb_invalidate_all(CPUPPCState *env); +void ppc_mmu_slot_sync(CPUPPCState *env); +void ppc_mmu_slots_reset(CPUPPCState *env); void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr); void cpu_ppc_set_vhyp(PowerPCCPU *cpu, PPCVirtualHypervisor *vhyp); void cpu_ppc_set_1lpar(PowerPCCPU *cpu); @@ -1721,7 +1733,10 @@ static inline int ppc_env_mmu_index(CPUPPCState *env, bool ifetch) #ifdef CONFIG_USER_ONLY return MMU_USER_IDX; #else - return (env->hflags >> (ifetch ? HFLAGS_IMMU_IDX : HFLAGS_DMMU_IDX)) & 7; + int idx = (env->hflags >> (ifetch ? HFLAGS_IMMU_IDX : HFLAGS_DMMU_IDX)) & 7; + + /* Translated accesses use the current segment register set's TLB. */ + return idx & 2 ? idx : idx | env->mmu_slot << 2; #endif } @@ -2796,6 +2811,16 @@ void cpu_write_xer(CPUPPCState *env, target_ulong xer); */ #define is_book3s_arch2x(ctx) (!!((ctx)->insns_flags & PPC_SEGMENT_64B)) +/* The TB's memory accesses use its segment register set's TLB. */ +static inline uint64_t ppc_tb_cs_base(CPUPPCState *env) +{ +#ifdef CONFIG_USER_ONLY + return 0; +#else + return env->mmu_slot; +#endif +} + #ifdef CONFIG_DEBUG_TCG void cpu_get_tb_cpu_state(CPUPPCState *env, vaddr *pc, uint64_t *cs_base, uint32_t *flags); @@ -2804,7 +2829,7 @@ static inline void cpu_get_tb_cpu_state(CPUPPCState *env, vaddr *pc, uint64_t *cs_base, uint32_t *flags) { *pc = env->nip; - *cs_base = 0; + *cs_base = ppc_tb_cs_base(env); *flags = env->hflags; } #endif diff --git a/target/ppc/helper_regs.c b/target/ppc/helper_regs.c index b2dc3b0a447bf..c088e07a4e58a 100644 --- a/target/ppc/helper_regs.c +++ b/target/ppc/helper_regs.c @@ -272,7 +272,7 @@ void cpu_get_tb_cpu_state(CPUPPCState *env, vaddr *pc, uint32_t hflags_rebuilt; *pc = env->nip; - *cs_base = 0; + *cs_base = ppc_tb_cs_base(env); *flags = hflags_current; hflags_rebuilt = hreg_compute_hflags_value(env); @@ -384,6 +384,7 @@ void check_tlb_flush(CPUPPCState *env, bool global) env->tlb_need_flush &= ~TLB_NEED_PAGE_FLUSH; env->tlb_flush_npages = 0; tlb_flush_all_cpus_synced(cs); + ppc_mmu_slots_reset(env); return; } @@ -393,17 +394,33 @@ void check_tlb_flush(CPUPPCState *env, bool global) env->tlb_need_flush &= ~TLB_NEED_PAGE_FLUSH; env->tlb_flush_npages = 0; tlb_flush(cs); + ppc_mmu_slots_reset(env); return; } - /* Otherwise only the pages tlbie named have to go. */ + /* + * Otherwise only the pages tlbie named have to go, in every segment: + * tlbie ignores the segment number, and the page may also be mapped + * through another segment register, as Mac OS X's copyin window does, + * or in another set's TLB (see ppc_mmu_slot_sync). Real-mode + * translations don't depend on the page table. + */ if (env->tlb_need_flush & TLB_NEED_PAGE_FLUSH) { env->tlb_need_flush &= ~TLB_NEED_PAGE_FLUSH; for (int i = 0; i < env->tlb_flush_npages; i++) { - tlb_flush_page(cs, env->tlb_flush_pages[i]); + for (uint32_t seg = 0; seg < 16; seg++) { + tlb_flush_page_by_mmuidx(cs, (seg << 28) | + (env->tlb_flush_pages[i] & 0x0fffffff), + 0x3333); + } } env->tlb_flush_npages = 0; } + + if (env->tlb_need_flush & TLB_NEED_SR_SWITCH) { + env->tlb_need_flush &= ~TLB_NEED_SR_SWITCH; + ppc_mmu_slot_sync(env); + } } #endif /* !CONFIG_USER_ONLY */ diff --git a/target/ppc/machine.c b/target/ppc/machine.c index 411e52277b806..9e820b09e2b9f 100644 --- a/target/ppc/machine.c +++ b/target/ppc/machine.c @@ -261,6 +261,9 @@ static int cpu_post_load(void *opaque, int version_id) ppc_fprf_clear(env); post_load_update_msr(env); + if (tcg_enabled()) { + ppc_mmu_slots_reset(env); /* the QEMU TLB starts empty */ + } if (tcg_enabled()) { /* Re-set breaks based on regs */ diff --git a/target/ppc/mmu_helper.c b/target/ppc/mmu_helper.c index e8100ee6d0c68..bd33ce8423895 100644 --- a/target/ppc/mmu_helper.c +++ b/target/ppc/mmu_helper.c @@ -282,6 +282,7 @@ void ppc_tlb_invalidate_all(CPUPPCState *env) case POWERPC_MMU_32B: env->tlb_need_flush = 0; tlb_flush(env_cpu(env)); + ppc_mmu_slots_reset(env); break; default: /* XXX: TODO */ @@ -290,6 +291,52 @@ void ppc_tlb_invalidate_all(CPUPPCState *env) } } +/* + * A 32-bit hash MMU's TLB is tagged with the VSID, so reloading the segment + * registers keeps it, and Mac OS X reloads them on every exception entry and + * exit to switch between the kernel's and the user's address space. QEMU's + * TLB is indexed by effective address instead, and flushing it on each of + * those switches made the guest walk its page table millions of times a + * second. So each recently used set of segment register values gets its + * own pair of MMU indexes (translated, user and supervisor; see + * ppc_env_mmu_index) and switching sets only evicts the least recently used + * one. tlbie and tlbia still flush every set. + * + * Called at the context-synchronizing event after the segment registers + * changed. + */ +void ppc_mmu_slot_sync(CPUPPCState *env) +{ + int i, victim = 0; + + for (i = 0; i < PPC_MMU_SLOTS; i++) { + if (env->mmu_slot_used[i] && + !memcmp(env->mmu_slot_sr[i], env->sr, sizeof(env->mmu_slot_sr[i]))) { + break; + } + if (env->mmu_slot_used[i] < env->mmu_slot_used[victim]) { + victim = i; + } + } + if (i == PPC_MMU_SLOTS) { + i = victim; + memcpy(env->mmu_slot_sr[i], env->sr, sizeof(env->mmu_slot_sr[i])); + tlb_flush_by_mmuidx(env_cpu(env), 3 << (4 * i)); + } + env->mmu_slot_used[i] = ++env->mmu_slot_clock; + env->mmu_slot = i; +} + +/* After the whole QEMU TLB was flushed: only the current set is cached. */ +void ppc_mmu_slots_reset(CPUPPCState *env) +{ + env->tlb_need_flush &= ~TLB_NEED_SR_SWITCH; + memset(env->mmu_slot_used, 0, sizeof(env->mmu_slot_used)); + memcpy(env->mmu_slot_sr[env->mmu_slot], env->sr, + sizeof(env->mmu_slot_sr[0])); + env->mmu_slot_used[env->mmu_slot] = ++env->mmu_slot_clock; +} + /* * Whether tlbie flushes the whole TLB, as the architecture allows and QEMU * has always done, or only the page it names (PPC_TLBIE=page). Flushing @@ -358,6 +405,24 @@ void ppc_tlb_invalidate_one(CPUPPCState *env, target_ulong addr) /* Special registers manipulation */ /* Segment registers load and store */ + +/* + * The per-segment-register TLB slots are opt-in (PPC_SR_SLOTS=1); by default + * a segment register change flushes the whole TLB, as before. On Mac OS X + * 10.4 guests the slots made the Quartz Extreme desktop much slower: opening + * a folder took up to 7 s and Dashboard managed under 1 fps instead of ~7 + * (measured: 4-6 vs 29-41 distinct frames in 12 s with them off). + */ +static bool ppc_mmu_slots_on(void) +{ + static int on = -1; + + if (on < 0) { + const char *s = getenv("PPC_SR_SLOTS"); + on = s && !strcmp(s, "1"); + } + return on; +} target_ulong helper_load_sr(CPUPPCState *env, target_ulong sr_num) { #if defined(TARGET_PPC64) @@ -407,7 +472,9 @@ void helper_store_sr(CPUPPCState *env, target_ulong srnum, target_ulong value) } } #else - env->tlb_need_flush |= TLB_NEED_LOCAL_FLUSH; + env->tlb_need_flush |= env->mmu_model == POWERPC_MMU_32B && + ppc_mmu_slots_on() ? + TLB_NEED_SR_SWITCH : TLB_NEED_LOCAL_FLUSH; #endif } } @@ -1396,6 +1463,16 @@ bool ppc_cpu_tlb_fill(CPUState *cs, vaddr eaddr, int size, hwaddr raddr; int page_size, prot; + if (cpu->env.mmu_model == POWERPC_MMU_32B && !(mmu_idx & 2) && + ((cpu->env.tlb_need_flush & TLB_NEED_SR_SWITCH) || + mmu_idx >> 2 != cpu->env.mmu_slot)) { + /* + * Between a segment register write and the next context + * synchronization, entries made from the new values would land in + * the old set's TLB; never reuse that one for the old set. + */ + cpu->env.mmu_slot_used[mmu_idx >> 2] = 0; + } if (ppc_xlate(cpu, eaddr, access_type, &raddr, &page_size, &prot, mmu_idx, !probe)) { tlb_set_page(cs, eaddr & TARGET_PAGE_MASK, raddr & TARGET_PAGE_MASK, diff --git a/target/ppc/translate.c b/target/ppc/translate.c index c7eed092177f3..723a8b8e22220 100644 --- a/target/ppc/translate.c +++ b/target/ppc/translate.c @@ -6554,6 +6554,10 @@ static void ppc_tr_init_disas_context(DisasContextBase *dcbase, CPUState *cs) ctx->n_nfp = 0; ctx->pr = (hflags >> HFLAGS_PR) & 1; ctx->mem_idx = (hflags >> HFLAGS_DMMU_IDX) & 7; + if (!(ctx->mem_idx & 2)) { + /* As ppc_env_mmu_index(): cs_base is the TLB slot. */ + ctx->mem_idx |= ctx->base.tb->cs_base << 2; + } ctx->dr = (hflags >> HFLAGS_DR) & 1; ctx->hv = (hflags >> HFLAGS_HV) & 1; ctx->insns_flags = env->insns_flags; From a08b8b17fa2d07594a1476c324565505a8b1ea71 Mon Sep 17 00:00:00 2001 From: Teufelhunden-0311 <106038146+Teufelhunden-0311@users.noreply.github.com> Date: Thu, 1 Oct 2026 06:25:51 -0700 Subject: [PATCH 14/14] target/ppc, tcg: flush only the data TLB entries a DBAT change can affect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After the previous change, three quarters of the vCPU's time in a file copy was still do_invalidate_BAT: Tiger's physical-copy window maps DBAT0/1 thousands of times a second, and each mapping flushed its 32 pages with tlb_flush_page -- every MMU index, plus two jump-cache clears per page. A data BAT translates only data accesses made with translation on. Add tlb_flush_data_pages_by_mmuidx() (cputlb.c), which flushes a run of pages for the given MMU indexes under one lock and leaves the TB jump cache alone, and use it for DBATs on the 32-bit hash MMU with the translated indexes (0x3333; real-mode indexes have bit 1 set). IBATs keep the full page flush. PPC_DBAT_FAST=0 restores it for DBATs too. Tiger 10.4.11, M1 Max, ditto of a 480 MB file inside the guest (3 alternating pairs, md5 verified): 14.5 / 14.2 / 14.4 s -> 4.8 / 4.8 / 4.7 s. Quake III timedemo unchanged (70.7 vs 69.6 fps). Stress test passes. Default-on for DBATs on 32-bit hash MMUs; PPC_DBAT_FAST=0 flushes them like IBATs again. Based on code from linuxkid473/ppc-osx-vgpu (poweremu-qemu, r300 branch, by Spartan0285, Vihaan Nathan, Teufelhunden-0311 and linuxkid473; GPL-2.0-or-later). Signed-off-by: Bruno Castelló Assisted-by: Claude:claude-opus-5-5 --- accel/tcg/cputlb.c | 18 ++++++++++++++++++ include/exec/cputlb.h | 18 ++++++++++++++++++ target/ppc/mmu_helper.c | 30 ++++++++++++++++++++++++------ 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/accel/tcg/cputlb.c b/accel/tcg/cputlb.c index 3b18f11ec125e..a270c7846442f 100644 --- a/accel/tcg/cputlb.c +++ b/accel/tcg/cputlb.c @@ -606,6 +606,24 @@ void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, uint16_t idxmap) tlb_flush_page_by_mmuidx_async_0(cpu, addr, idxmap); } +void tlb_flush_data_pages_by_mmuidx(CPUState *cpu, vaddr addr, vaddr npages, + uint16_t idxmap) +{ + assert_cpu_is_self(cpu); + addr &= TARGET_PAGE_MASK; + + qemu_spin_lock(&cpu->neg.tlb.c.lock); + for (vaddr i = 0; i < npages; i++) { + for (int mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) { + if ((idxmap >> mmu_idx) & 1) { + tlb_flush_page_locked(cpu, mmu_idx, + addr + i * TARGET_PAGE_SIZE); + } + } + } + qemu_spin_unlock(&cpu->neg.tlb.c.lock); +} + void tlb_flush_page(CPUState *cpu, vaddr addr) { tlb_flush_page_by_mmuidx(cpu, addr, ALL_MMUIDX_BITS); diff --git a/include/exec/cputlb.h b/include/exec/cputlb.h index 8125f6809c6f1..4ad958938bcc6 100644 --- a/include/exec/cputlb.h +++ b/include/exec/cputlb.h @@ -152,6 +152,20 @@ void tlb_flush_all_cpus_synced(CPUState *src_cpu); void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, uint16_t idxmap); +/** + * tlb_flush_data_pages_by_mmuidx: + * @cpu: CPU whose TLB should be flushed + * @addr: virtual address of the first page + * @npages: number of consecutive pages + * @idxmap: bitmap of MMU indexes to flush + * + * Like tlb_flush_page_by_mmuidx on each page, for a mapping change that + * cannot affect instruction fetch (a data-only translation): the TB jump + * cache is left alone, and the TLB lock is taken once. + */ +void tlb_flush_data_pages_by_mmuidx(CPUState *cpu, vaddr addr, vaddr npages, + uint16_t idxmap); + /** * tlb_flush_page_by_mmuidx_all_cpus_synced: * @cpu: Originating CPU of the flush @@ -246,6 +260,10 @@ static inline void tlb_flush_page_by_mmuidx(CPUState *cpu, vaddr addr, uint16_t idxmap) { } +static inline void tlb_flush_data_pages_by_mmuidx(CPUState *cpu, vaddr addr, + vaddr npages, uint16_t idxmap) +{ +} static inline void tlb_flush_by_mmuidx(CPUState *cpu, uint16_t idxmap) { diff --git a/target/ppc/mmu_helper.c b/target/ppc/mmu_helper.c index bd33ce8423895..090670aff2d82 100644 --- a/target/ppc/mmu_helper.c +++ b/target/ppc/mmu_helper.c @@ -150,7 +150,7 @@ static void booke206_flush_tlb(CPUPPCState *env, int flags, * MMU indexes that use address translation (see hreg_compute_hflags_value()): * bit 1 of the index is set in real mode, where BATs never apply. */ -#define PPC_BAT_MMUIDX_BITS ((1 << 0) | (1 << 1) | (1 << 4) | (1 << 5)) +#define PPC_BAT_MMUIDX_BITS 0x3333 /* also the SR-slot copies, bits 2-3 */ /* * Drop the TLB entries a BAT can affect: the ones it translated, and the @@ -158,7 +158,8 @@ static void booke206_flush_tlb(CPUPPCState *env, int flags, * not of the value that replaces it, or entries beyond the new length * would survive a BAT being shrunk or cleared. */ -static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu) +static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu, + bool data) { target_ulong base, len; @@ -170,6 +171,23 @@ static inline void do_invalidate_BAT(CPUPPCState *env, target_ulong BATu) len = ((BATu << 15) & 0x0FFE0000UL) + 0x00020000; qemu_log_mask(CPU_LOG_MMU, "Flush BAT from " TARGET_FMT_lx " length " TARGET_FMT_lx "\n", base, len); + /* + * From ppc-osx-vgpu (poweremu-qemu 1b270be60f): a data BAT translates + * only data accesses made with translation on, so leave instruction + * fetches and the jump cache alone -- Tiger rewrites DBAT0/1 tens of + * thousands of times a second during file I/O. PPC_DBAT_FAST=0 + * flushes as for any BAT. + */ + static int fast = -1; + if (fast < 0) { + const char *e = getenv("PPC_DBAT_FAST"); + fast = !(e && e[0] == '0'); + } + if (data && fast && env->mmu_model == POWERPC_MMU_32B) { + tlb_flush_data_pages_by_mmuidx(env_cpu(env), base, len >> TARGET_PAGE_BITS, + PPC_BAT_MMUIDX_BITS); + return; + } tlb_flush_range_by_mmuidx(env_cpu(env), base, len, PPC_BAT_MMUIDX_BITS, TARGET_LONG_BITS); } @@ -191,7 +209,7 @@ void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong value) if (env->IBAT[0][nr] != value) { mask = (value << 15) & 0x0FFE0000UL; #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->IBAT[0][nr]); + do_invalidate_BAT(env, env->IBAT[0][nr], false); #endif /* * When storing valid upper BAT, mask BEPI and BRPN and @@ -203,7 +221,7 @@ void helper_store_ibatu(CPUPPCState *env, uint32_t nr, target_ulong value) env->IBAT[1][nr] = (env->IBAT[1][nr] & 0x0000007B) | (env->IBAT[1][nr] & ~0x0001FFFF & ~mask); #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->IBAT[0][nr]); + do_invalidate_BAT(env, env->IBAT[0][nr], false); #else tlb_flush(env_cpu(env)); #endif @@ -228,7 +246,7 @@ void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong value) */ mask = (value << 15) & 0x0FFE0000UL; #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->DBAT[0][nr]); + do_invalidate_BAT(env, env->DBAT[0][nr], true); #endif mask = (value << 15) & 0x0FFE0000UL; env->DBAT[0][nr] = (value & 0x00001FFFUL) | @@ -236,7 +254,7 @@ void helper_store_dbatu(CPUPPCState *env, uint32_t nr, target_ulong value) env->DBAT[1][nr] = (env->DBAT[1][nr] & 0x0000007B) | (env->DBAT[1][nr] & ~0x0001FFFF & ~mask); #if !defined(FLUSH_ALL_TLBS) - do_invalidate_BAT(env, env->DBAT[0][nr]); + do_invalidate_BAT(env, env->DBAT[0][nr], true); #else tlb_flush(env_cpu(env)); #endif