From 8c8d629056ba88c9c34131e39e9bb7871b3ba35f Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 21:32:21 +0100 Subject: [PATCH 1/9] [VFDLIBM-139] Assert the width, no FMA and no call in the C2 code of exp's arms dev/hsdis-build.sh builds hsdis into target/hsdis from two pinned files of jdk-25-ga against Capstone 5 (built from a pinned release when the system's is older) and checks that HotSpot disassembles with it. hsdis is a tool: its source and binary are never committed. ExpAsmProbe runs each exp arm in a loop, one JVM per width, under -Xbatch with the body forced inline and CompileCommand=print; AsmCheck parses the last standard C2 nmethod and holds the rules (every byte decoded, packed-double arithmetic on the width's registers, no FMA, no call but uncommon traps and the entry barrier, no StrictMath frame). ExpAsmTest applies them at each width, skipping with its reason without hsdis; AsmCheckSelfTest shows each rule failing. CI's x86 rows build hsdis and require the check. SKILLS.md holds the rules, the lessons and the laptop's census. Part of #139. Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 14 + AGENTS.md | 6 + SKILLS.md | 108 +++++ dev/hsdis-build.sh | 178 ++++++++ .../io/github/vecbricks/vfdlibm/AsmCheck.java | 410 ++++++++++++++++++ .../vecbricks/vfdlibm/AsmCheckSelfTest.java | 250 +++++++++++ .../github/vecbricks/vfdlibm/ExpAsmProbe.java | 118 +++++ .../github/vecbricks/vfdlibm/ExpAsmTest.java | 120 +++++ 8 files changed, 1204 insertions(+) create mode 100755 dev/hsdis-build.sh create mode 100644 src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java create mode 100644 src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java create mode 100644 src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java create mode 100644 src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b87df6..1066288 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: jvm-args: "" # The one row that also runs the jar check's self-test. jar-self-test: true + asm: true # x86 compiled as an AVX2 host, the headline EPYC 7763, whatever runner is drawn: # UseAVX=2 caps vectors at 256 bits and takes AVX-512's instructions away, so the # preferred species is 256 bits on every draw, and an operation C2 lowers only with @@ -41,11 +42,13 @@ jobs: - name: x86 as AVX2, 128+256 bits os: ubuntu-latest jvm-args: -XX:UseAVX=2 -XX:MaxVectorSize=32 + asm: true # x86 with vectors capped at 16 bytes: every case runs at 128 bits (the preferred # species is 128 bits too), and the 256- and 512-bit cases are skipped. - name: x86 128 bits os: ubuntu-latest jvm-args: -XX:MaxVectorSize=16 + asm: true # Arm: GitHub's Arm runners have 128-bit vectors, so the 128-bit and preferred cases # run there and the 256- and 512-bit cases are skipped. - name: Arm 128 bits @@ -67,7 +70,18 @@ jobs: key: m2-${{ runner.os }}-${{ runner.arch }}-java25-build-${{ hashFiles('**/pom.xml') }} restore-keys: | m2-${{ runner.os }}-${{ runner.arch }}-java25-build- + # The assembly check (ExpAsmTest; SKILLS.md, "The assembly check") reads C2's code through + # hsdis, which dev/hsdis-build.sh builds into target/hsdis from two pinned files of the JDK's + # source and a pinned Capstone 5, in seconds; it is a tool, never committed or shipped. The + # runner's own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. On + # the x86 rows VFDLIBM_ASM_REQUIRED turns the check's skip for a missing or unloaded hsdis + # into a failure, so a green row has read the code. The Arm row skips it: its rules are x86's. + - name: Build hsdis for the assembly check + if: matrix.asm + run: dev/hsdis-build.sh - name: Build and test + env: + VFDLIBM_ASM_REQUIRED: ${{ matrix.asm }} run: >- mvn -B --no-transfer-progress verify "-Dvfdlibm.test.jvmArgs=${{ matrix.jvm-args }}" diff --git a/AGENTS.md b/AGENTS.md index 5abbdd3..69b5d0b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,12 @@ vfdlibm ports fdlibm's double functions to the Java Vector API, each lane bit-id `PairBits` for two arguments), `Inputs` makes the inputs, `VectorWidth` runs a test at 128, 256 and 512 bits and the preferred species, and `PlantedFaultTest` requires each fault planted through `Faults` (in the main sources) to be caught by its check. `HarnessSelfTest` tests them. +- The assembly check: `ExpAsmTest` reads the C2 code of exp's arms through hsdis and asserts + the width, no fused multiply-add and no call but uncommon traps (`AsmCheckSelfTest` shows + each rule failing). `dev/hsdis-build.sh` builds hsdis into `target/hsdis`; it is OpenJDK's + GPL source compiled as a tool, never committed or shipped. Without it the check skips and + says why; CI's x86 rows build it and set `VFDLIBM_ASM_REQUIRED=true`, so there a skip fails. + See `SKILLS.md`, "The assembly check". - A width wider than the host's vectors is skipped. To see an AVX2 host's skips on an AVX-512 one: `mvn -B test -Dvfdlibm.test.jvmArgs=-XX:MaxVectorSize=32`. That keeps AVX-512's instructions at 256 bits, though: to make C2 compile as on an AVX2 host such as the EPYC diff --git a/SKILLS.md b/SKILLS.md index c9c4e27..1ed19cd 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -226,6 +226,114 @@ stops the next port re-trying a settled question. against 256-bit ones on three; EPYC 9V45 (Zen 5) 1.99. GitHub's x86 runners draw from all of these. `HARDWARE.md` holds the table, with sources, and vfdlibm's runs extend it. +## The assembly check + +`ExpAsmTest` reads the machine code C2 emits for each of exp's vector arms and asserts on it +(issue #139; the idea is Varka's assembly suite, the code vfdlibm's own). `ExpAsmProbe` runs in a +JVM of its own per `VectorWidth` the host has, under `-Xbatch` and the row's `-XX` options, with +vfdlibm forced inline and `-XX:CompileCommand=print` on its loops; `AsmCheck` parses the last +standard `C2-compiled nmethod` of each, from its entry point to its stubs, in Intel syntax. +`AsmCheckSelfTest` shows each rule failing on crafted disassembly. To run it here: +`dev/hsdis-build.sh`, then `mvn -q test -Dtest='ExpAsmTest,AsmCheckSelfTest'`. + +- **The rules.** Every byte decoded; packed-double arithmetic (`v(add|sub|mul|div)pd`) present + and on the width's registers only (`xmm`, `ymm`, `zmm`), no scalar `*sd` arithmetic; no fused + multiply-add of any form (`vfmadd*`, `vfmsub*`, `vfnmadd*`, `vfnmsub*`, `vfmaddsub*`, + `vfmsubadd*`); no call but `{runtime_call UncommonTrapBlob}` and `{runtime_call + Stub::method_entry_barrier}`; no inlined frame of `StrictMath` or `FdLibm`. Narrower registers + elsewhere are allowed: a 512-bit body keeps its int lanes in a `ymm`. Counts are not asserted + (Varka: a register-allocation roll moves them with nothing wrong). +- **Common data makes the call rule exact.** On `[-20, 20]` no lane is rare, so C2 compiles the + per-lane finish as an uncommon trap, a deoptimizing exit the common path never takes; any other + call anywhere in the method fails. The same data keep `StrictMath`'s code out of the dump (no + rare lane, no call to compile), which the licence rule needs; the last rule is a backstop, since + HotSpot names inlined frames only at calls, traps and safepoints. +- **At 128 bits on x86 the call rule is not asserted.** Every arm calls the Vector API's Java + fallback, 60 to 132 calls per method (the census below), as "At two 64-bit lanes x86 C2 lowers + no mask" predicts. Width and FMA are asserted there; the width is the child's species, so the + preferred species of the `MaxVectorSize=16` row counts as 128 bits. +- **Print the caller's loop, not exp's methods.** Without the forced inline, `Exp`'s shared + three-argument body compiles as a method of its own whose `arm` is no constant; it takes and + returns heap vectors, calls `blend` and `convert` unintrinsified and allocates (`C2 Runtime + new_instance`, `new_array`), and the public `VFdlibm.exp` is a `{static_call}` into it. With the + forced inline, whether any `Exp` method gets a C2 compile of its own depends on timing (one run + printed only `expBlended`). So the probe's loops, in `ExpBenchmark`'s shape, are what is read. +- **`expRare` before `expCore`, or it boxes.** The first run of the check failed the `core` arm at + 256 and 512 bits: a loop calling `Exp.expCore(x)` and then `Exp.expRare(x)` on one vector has a + `{static_call}` to `expRare` and to `AbstractMask.intoArray`, which `PrintInlining` shows refused + for `NodeCountInliningCutoff` once `expCore` is inlined. In `ExpBenchmark`'s order, `expRare` + first, both inline and the rules pass. "Two port bodies in one loop do not fit" above is the + same budget; here one body and a small one fit only in that order. +- **hsdis needs Capstone 5.** `dev/hsdis-build.sh` compiles the JDK's + `src/utils/hsdis/capstone/hsdis-capstone.c` and `hsdis.h` (jdk-25-ga, fetched alone, SHA-256 + pinned, compiled and never read) against Capstone. Ubuntu 24.04's Capstone 4.0.2, GitHub's + ubuntu-latest, printed exp's 256-bit AVX-512 bodies with 19 to 43 undecoded `.byte` lines + each, an EVEX prefix it did not know followed by garbage with a `call` in it (read in an + ubuntu:24.04 container on the laptop). So the script uses the system's Capstone only at 5 or + later and otherwise builds the pinned 5.0.7 from source with cmake, five seconds in that + container, whose census then matched the laptop's to the instruction; and the check fails on + any `.byte` or `(bad)`. +- **Skips say which.** Not x86-64; hsdis not found (the script's `target/hsdis`, `~/hsdis` or + `$VFDLIBM_HSDIS_DIR`); or found but not loaded, decided by the output holding no + `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, which it + printed both with no library and with a file that was none. CI's x86 rows build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes + the last two fail instead; the Arm row skips. + +**The census of exp's arms, 22 November 2026, on the laptop** (AMD Ryzen AI 9 HX PRO 370, JDK +25.0.5.1, hsdis on Capstone 5.0.7). Not a headline and no timing: counts of instructions only, one +run, the same in a second. Each is the whole nmethod of the probe's loop, prologue and +out-of-line paths included, so the constant broadcasts C2 hoists before the loop count, and +from 256 bits up the stack accesses are the stack bang and the uncommon traps' saves, not +spills; `bench/asm/README.md` counts the hot loop alone. The columns: all instructions, packed-double arithmetic, `vdivpd`, blends, broadcasts, +compares (`vpcmp*`, `vcmp*`), mask-register operations (`k*`), conversions (`vcvt*`, `vpmov*`), +operands on `[rsp`, calls, FMA. The preferred species read the same as its fixed width (512 bits +on the host's flags, 256 as an AVX2 host). The rows come from the test's output: `grep '^| exp '`. + +On the host's own flags (AVX-512, `MaxVectorSize=64`): + +| bits | arm | insns | pd | div | blend | bcast | cmp | k | cvt | stack | calls | fma | +| ---: | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 128 | finish | 1195 | 24 | 1 | 0 | 9 | 3 | 2 | 19 | 351 | 60 | 0 | +| 128 | finishMasked | 1366 | 24 | 1 | 0 | 9 | 3 | 2 | 19 | 421 | 71 | 0 | +| 128 | blended | 2289 | 26 | 1 | 0 | 14 | 3 | 2 | 20 | 535 | 126 | 0 | +| 128 | blendedMasked | 2469 | 26 | 1 | 0 | 14 | 3 | 2 | 20 | 682 | 132 | 0 | +| 128 | core | 1872 | 24 | 1 | 0 | 14 | 6 | 4 | 24 | 555 | 91 | 0 | +| 256 | finish | 137 | 24 | 1 | 2 | 17 | 7 | 5 | 4 | 8 | 3 | 0 | +| 256 | finishMasked | 159 | 24 | 1 | 3 | 17 | 7 | 6 | 4 | 10 | 3 | 0 | +| 256 | blended | 145 | 26 | 1 | 8 | 24 | 12 | 4 | 4 | 2 | 2 | 0 | +| 256 | blendedMasked | 157 | 26 | 1 | 9 | 24 | 12 | 4 | 4 | 3 | 2 | 0 | +| 256 | core | 133 | 24 | 1 | 2 | 17 | 7 | 3 | 4 | 3 | 2 | 0 | +| 512 | finish | 140 | 24 | 1 | 2 | 17 | 7 | 5 | 4 | 8 | 3 | 0 | +| 512 | finishMasked | 155 | 24 | 1 | 3 | 17 | 7 | 7 | 4 | 10 | 3 | 0 | +| 512 | blended | 145 | 26 | 1 | 8 | 24 | 12 | 4 | 4 | 2 | 2 | 0 | +| 512 | blendedMasked | 155 | 26 | 1 | 9 | 24 | 12 | 4 | 4 | 3 | 2 | 0 | +| 512 | core | 134 | 24 | 1 | 2 | 17 | 7 | 3 | 4 | 3 | 2 | 0 | + +As an AVX2 host (`-XX:UseAVX=2 -XX:MaxVectorSize=32`): + +| bits | arm | insns | pd | div | blend | bcast | cmp | k | cvt | stack | calls | fma | +| ---: | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 128 | finish | 1147 | 24 | 1 | 2 | 9 | 4 | 0 | 18 | 295 | 60 | 0 | +| 128 | finishMasked | 1321 | 24 | 1 | 2 | 9 | 4 | 0 | 18 | 374 | 71 | 0 | +| 128 | blended | 2313 | 26 | 1 | 2 | 14 | 4 | 0 | 19 | 573 | 126 | 0 | +| 128 | blendedMasked | 2272 | 26 | 1 | 2 | 14 | 4 | 0 | 19 | 505 | 132 | 0 | +| 128 | core | 1745 | 24 | 1 | 4 | 14 | 8 | 0 | 22 | 438 | 91 | 0 | +| 256 | finish | 144 | 24 | 1 | 5 | 17 | 8 | 0 | 3 | 8 | 3 | 0 | +| 256 | finishMasked | 167 | 24 | 1 | 6 | 17 | 8 | 0 | 4 | 10 | 3 | 0 | +| 256 | blended | 152 | 26 | 1 | 10 | 25 | 13 | 0 | 3 | 2 | 2 | 0 | +| 256 | blendedMasked | 167 | 26 | 1 | 11 | 25 | 13 | 0 | 4 | 5 | 2 | 0 | +| 256 | core | 140 | 24 | 1 | 5 | 17 | 8 | 0 | 3 | 3 | 2 | 0 | + +What it reads: no FMA in any arm at any width under either flag set. From 256 bits up every arm is +one copy of the body (24 packed-double operations, one `vdivpd`; the blended arm's two more are +its filter's `x + x` and the subnormal scale's product) and calls only its traps and the entry +barrier: three for the finish arms (the finish's trap, the loop's range check, the barrier), two +for the others. The blended arm has 6 more blends than the finish on AVX-512 and 5 more on AVX2, and 7 to 8 +more broadcasts, its filter's constants. AVX2 has no mask registers, so its masks are vector +compares and `vblendvps`, 2 to 3 more blends per arm than AVX-512's `vpblendmq`. Masking adds one +blend and 10 to 23 instructions. At 128 bits the bodies are 8 to 16 times longer: the Java +fallback. + ## Where headline numbers come from: four named hosts - **Headline numbers are measured on four named CPUs**, each drawn from GitHub's standard diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh new file mode 100755 index 0000000..347dc42 --- /dev/null +++ b/dev/hsdis-build.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# +# Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. You may obtain a copy of the +# License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +# express or implied. See the License for the specific language governing permissions and +# limitations under the License. +# +# Builds hsdis, the disassembler plugin HotSpot loads to print compiled code, so that the +# assembly check (ExpAsmTest, SKILLS.md "The assembly check") can read what C2 emits for a port's +# arms. The idea is Varka's dev/varka_hsdis_build.sh; this script is written for vfdlibm. +# +# dev/hsdis-build.sh # fetch the two pinned source files, build, check +# dev/hsdis-build.sh --src # take them from a JDK source tree instead +# dev/hsdis-build.sh --capstone-source # build Capstone too, even if the system's would do +# dev/hsdis-build.sh --check # only check that HotSpot loads 's hsdis +# +# hsdis is a tool and nothing of it is vfdlibm's: its source is OpenJDK's, under the GPL, and is +# never committed here, and neither is the library built from it; both stay under target/, which +# git ignores and no jar holds. The source is two files of the jdk-25-ga tag of openjdk/jdk, +# src/utils/hsdis/capstone/hsdis-capstone.c and src/utils/hsdis/hsdis.h, fetched one by one and +# checked against the SHA-256 pinned below; they are compiled, not read. A product JVM finds +# hsdis-.so on LD_LIBRARY_PATH; no JDK is built. +# +# The disassembler behind them is Capstone (BSD), version 5 or later. The system's is used when +# its capstone.h says 5 or more (apt install libcapstone-dev, Ubuntu 25.04 and later), and the +# build takes gcc and a second. Otherwise, or with --capstone-source, Capstone's pinned release is +# fetched, checked against its SHA-256 and built with cmake under target/hsdis/capstone, for this +# host's architecture only, and linked in statically. Version 4 will not do: Ubuntu 24.04's +# 4.0.2, which GitHub's ubuntu-latest has, printed an AVX-512 body of exp at 256 bits with +# ".byte 0x62" and garbage after it, a "call" among the garbage (SKILLS.md, "The assembly check"). +# +# The library goes to target/hsdis/hsdis-amd64.so on x86-64 and target/hsdis/hsdis-aarch64.so on +# Arm (or --out ). Then the check runs: a JVM with LD_LIBRARY_PATH= prints one compiled +# method of a two-line class of this script's own, and the build passes only if the output holds +# a [Disassembly] section with an instruction line in it. Without a disassembler HotSpot prints +# raw hex instead and does not fail, so the exit status of that JVM would prove nothing. +set -euo pipefail +usage() { sed -n '/^# Builds hsdis/,/^[^#]/p' "$0" | sed '$d'; exit "${1:-2}"; } + +tag=jdk-25-ga +# SHA-256 of the two files at $tag. +sha_c=e805c9bb6a9bff3de2ac59870b00409b350e8dc147b77336e5e6f7e6b5d76b74 +sha_h=a7fe8a90a1dbe55bd9ba08e82ee6b519965f7f2457f0f588c960b8b1b2d2e976 +# Capstone's release, and the SHA-256 of GitHub's archive of its tag. +capstone=5.0.7 +sha_capstone=6427a724726d161d1e05fb49fff8cd0064f67836c04ffca3c11d6d859e719caa +root=$(cd "$(dirname "$0")/.." && pwd) +src="" +out="$root/target/hsdis" +check_only="" +capstone_source="" +while [ "$#" -gt 0 ]; do + case "$1" in + -h|--help) usage 0 ;; + --src) src="$2"; shift 2 ;; + --out) out="$2"; shift 2 ;; + --capstone-source) capstone_source=yes; shift ;; + --check) check_only="$2"; shift 2 ;; + *) usage ;; + esac +done + +case "$(uname -m)" in + x86_64) arch=amd64; cs_arch=CS_ARCH_X86; cs_mode=CS_MODE_64 ;; + aarch64) arch=aarch64; cs_arch=CS_ARCH_ARM64; cs_mode=CS_MODE_ARM ;; + *) echo "hsdis-build: unsupported architecture $(uname -m)" >&2; exit 1 ;; +esac +java_home="${JAVA_HOME:-$(dirname "$(dirname "$(readlink -f "$(command -v java)")")")}" + +# Passes when a JVM given $1 on LD_LIBRARY_PATH prints real instructions for a compiled method. +check_loads() { + local dir=$1 work + if [ ! -f "$dir/hsdis-$arch.so" ]; then + echo "hsdis-build: no hsdis-$arch.so in $dir" >&2 + return 1 + fi + work=$(mktemp -d) + cat > "$work/HsdisCheck.java" << 'EOF' +public class HsdisCheck { + static int twice(int x) { return x + x; } + public static void main(String[] args) { + int s = 0; + for (int i = 0; i < 20000; i++) s += twice(i); + System.out.println(s); + } +} +EOF + LD_LIBRARY_PATH="$dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" "$java_home/bin/java" -Xbatch \ + -XX:+UnlockDiagnosticVMOptions -XX:CompileCommand=quiet \ + -XX:CompileCommand=print,HsdisCheck::twice "$work/HsdisCheck.java" > "$work/out.txt" 2>&1 \ + || { cat "$work/out.txt" >&2; rm -rf "$work"; return 1; } + # An instruction line inside [Disassembly]: an address, a tab-separated mnemonic that a hex + # word cannot be (HotSpot's raw dump also has the 0x
: shape). + if awk '/^\[Disassembly\]/ { inside = 1 } /^\[\/Disassembly\]/ { inside = 0 } + inside && /^ *0x[0-9a-f]+: +(push|pushq|sub|subq|mov|movl|movq|ret|retq|stp|ldr|add)[ \t]/ { found = 1 } + END { exit found ? 0 : 1 }' "$work/out.txt"; then + rm -rf "$work" + return 0 + fi + echo "hsdis-build: HotSpot did not disassemble with $dir/hsdis-$arch.so; its output:" >&2 + head -40 "$work/out.txt" >&2 + rm -rf "$work" + return 1 +} + +if [ -n "$check_only" ]; then + check_loads "$check_only" + echo "HotSpot loads $check_only/hsdis-$arch.so" + exit 0 +fi + +command -v gcc > /dev/null || { echo "hsdis-build: gcc not found" >&2; exit 1; } +[ -f "$java_home/include/jni.h" ] \ + || { echo "hsdis-build: no jni.h under $java_home/include" >&2; exit 1; } +mkdir -p "$out" + +# The system's Capstone if it is 5 or later, else the pinned release built here. +system_major=$(sed -n 's/^#define CS_API_MAJOR \([0-9]*\).*/\1/p' \ + /usr/include/capstone/capstone.h 2> /dev/null || true) +if [ -z "$capstone_source" ] && [ "${system_major:-0}" -ge 5 ]; then + echo "using the system's Capstone (API $system_major)" + cs_include=/usr/include/capstone + cs_link=(-lcapstone) +else + echo "building Capstone $capstone (the system's: ${system_major:-none})" + command -v cmake > /dev/null || { echo "hsdis-build: cmake not found" >&2; exit 1; } + cs="$out/capstone" + rm -rf "$cs" + mkdir -p "$cs" + curl -fsSL --retry 3 -o "$cs/capstone.tar.gz" \ + "https://github.com/capstone-engine/capstone/archive/refs/tags/$capstone.tar.gz" + echo "$sha_capstone $cs/capstone.tar.gz" | sha256sum -c --quiet - \ + || { echo "hsdis-build: Capstone's archive does not match its pinned SHA-256" >&2; exit 1; } + tar -xzf "$cs/capstone.tar.gz" -C "$cs" + cmake -S "$cs/capstone-$capstone" -B "$cs/build" -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_SHARED_LIBS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON \ + -DCAPSTONE_BUILD_TESTS=OFF -DCAPSTONE_BUILD_CSTOOL=OFF -DCAPSTONE_ARCHITECTURE_DEFAULT=OFF \ + -DCAPSTONE_X86_SUPPORT=ON -DCAPSTONE_ARM64_SUPPORT=ON > "$cs/cmake.log" 2>&1 \ + || { cat "$cs/cmake.log" >&2; exit 1; } + cmake --build "$cs/build" -j "$(nproc)" > "$cs/build.log" 2>&1 \ + || { tail -40 "$cs/build.log" >&2; exit 1; } + cs_include="$cs/capstone-$capstone/include/capstone" + cs_link=("$cs/build/libcapstone.a") +fi + +hsdis="$out/src" +rm -rf "$hsdis" +mkdir -p "$hsdis/capstone" +if [ -n "$src" ]; then + cp "$src/src/utils/hsdis/capstone/hsdis-capstone.c" "$hsdis/capstone/" + cp "$src/src/utils/hsdis/hsdis.h" "$hsdis/" +else + base="https://raw.githubusercontent.com/openjdk/jdk/$tag/src/utils/hsdis" + curl -fsSL --retry 3 -o "$hsdis/capstone/hsdis-capstone.c" "$base/capstone/hsdis-capstone.c" + curl -fsSL --retry 3 -o "$hsdis/hsdis.h" "$base/hsdis.h" +fi +# A tree given with --src may be another version: its files are used, and a mismatch is said. +status=0 +echo "$sha_c $hsdis/capstone/hsdis-capstone.c" | sha256sum -c --quiet - || status=$? +echo "$sha_h $hsdis/hsdis.h" | sha256sum -c --quiet - || status=$? +if [ "$status" -ne 0 ]; then + if [ -z "$src" ]; then + echo "hsdis-build: the fetched files do not match the SHA-256 pinned for $tag" >&2 + exit 1 + fi + echo "hsdis-build: $src's files are not $tag's; building them anyway" >&2 +fi + +# A shared object against Capstone, told the host's architecture and mode; jni.h for hsdis.h. +gcc -shared -fPIC -O2 -I"$hsdis" -I"$cs_include" \ + -I"$java_home/include" -I"$java_home/include/linux" \ + -DCAPSTONE_ARCH="$cs_arch" -DCAPSTONE_MODE="$cs_mode" \ + -o "$out/hsdis-$arch.so" "$hsdis/capstone/hsdis-capstone.c" "${cs_link[@]}" +echo "built $out/hsdis-$arch.so" +check_loads "$out" +echo "HotSpot loads it; the assembly check finds it in target/hsdis (or set VFDLIBM_HSDIS_DIR=$out)" diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java new file mode 100644 index 0000000..a0c9a75 --- /dev/null +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java @@ -0,0 +1,410 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.vecbricks.vfdlibm; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.lang.management.ManagementFactory; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The assembly check's machinery: finds hsdis, runs a probe class in a child JVM that prints its + * methods' C2 code, parses that output and holds the rules a port's arm must meet (SKILLS.md, "The + * assembly check"). x86 only: the rules name x86 mnemonics and registers. + * + *

What is read: the last standard (not on-stack-replacement) {@code C2-compiled nmethod} of a + * method, from its entry point to its stub code, in Intel syntax (pinned by {@code + * PrintAssemblyOptions=intel}). The constant pool, the C1 nmethod and the stubs are not read. + * Nothing is read unless HotSpot printed a {@code [Disassembly]} section: without a working + * hsdis it prints the code as hex words under {@code [MachCode]}, whose lines have the same + * {@code 0x

:} shape, and a rule that found no instruction would pass vacuously. + * + *

The rules, each a list of violations (empty is a pass): + * + *

    + *
  • {@link #undecodedViolations}: every byte decoded, or the other rules read garbage (hsdis + * needs Capstone 5 or later for AVX-512; {@code dev/hsdis-build.sh}). + *
  • {@link #widthViolations}: at least one packed-double arithmetic instruction ({@code + * v(add|sub|mul|div)pd}), every one of them on registers of the width's class ({@code xmm} + * at 128 bits, {@code ymm} at 256, {@code zmm} at 512), and no scalar double arithmetic + * ({@code (v)(add|sub|mul|div)sd}). Narrower registers elsewhere are allowed: the int lanes + * of a 512-bit body are a {@code ymm}, and zeroing idioms name {@code xmm}. + *
  • {@link #fmaViolations}: no fused multiply-add of any form ({@code vfmadd*}, {@code + * vfmsub*}, {@code vfnmadd*}, {@code vfnmsub*}, {@code vfmaddsub*}, {@code vfmsubadd*}). + *
  • {@link #callViolations}: every {@code call} goes to an uncommon trap ({@code {runtime_call + * UncommonTrapBlob}}) or the method entry barrier ({@code {runtime_call + * Stub::method_entry_barrier}}). On data where no lane is rare C2 compiles each rare branch + * as an uncommon trap, a deoptimizing exit that is never the common path; so any other + * call, anywhere in the method, fails, which is stricter than the common path alone. + *
  • {@link #licenceViolations}: no inlined frame of {@code java.lang.StrictMath} or {@code + * FdLibm}, whose compiled code this project does not read (AGENTS.md, licence). HotSpot + * names frames only at calls, traps and safepoints, so this is a backstop; what keeps that + * code out is the probe's data, on which no lane reaches the per-lane finish. + *
+ */ +final class AsmCheck { + + private AsmCheck() {} + + /** The environment variable that names a directory holding {@code hsdis-.so}. */ + static final String HSDIS_DIR_ENV = "VFDLIBM_HSDIS_DIR"; + /** Set to {@code true}, a skip for want of hsdis fails instead (CI's x86 rows set it). */ + static final String REQUIRED_ENV = "VFDLIBM_ASM_REQUIRED"; + /** How long a probe JVM may take. */ + static final int CHILD_SECONDS = 180; + + // --------------------------------------------------------------------------------------------- + // Finding hsdis + + /** Where hsdis was looked for, and what was found. */ + record Hsdis(Path dir, String why) { + boolean found() { + return dir != null; + } + } + + /** The library's file name on this architecture, or null where the check does not run. */ + static String libraryName() { + String arch = System.getProperty("os.arch"); + return switch (arch) { + case "amd64", "x86_64" -> "hsdis-amd64.so"; + default -> null; + }; + } + + /** + * The directory holding hsdis: {@code $VFDLIBM_HSDIS_DIR} if set, else {@code target/hsdis} + * (where {@code dev/hsdis-build.sh} builds it), else {@code ~/hsdis}. Found means the file + * exists; whether HotSpot loads it is known only from a probe's output ({@link + * #disassembled}). + */ + static Hsdis findHsdis() { + return findHsdis(System.getenv(HSDIS_DIR_ENV), libraryName(), + List.of(Path.of("target", "hsdis").toAbsolutePath(), + Path.of(System.getProperty("user.home"), "hsdis"))); + } + + /** {@link #findHsdis()} with the environment's value and the default places given. */ + static Hsdis findHsdis(String env, String name, List defaults) { + List candidates = env != null && !env.isEmpty() ? List.of(Path.of(env)) : defaults; + for (Path dir : candidates) { + if (Files.isRegularFile(dir.resolve(name))) { + return new Hsdis(dir, null); + } + } + return new Hsdis(null, "hsdis not found: no " + name + " in " + candidates + + " (build it with dev/hsdis-build.sh, or set " + HSDIS_DIR_ENV + ")"); + } + + /** Whether {@link #REQUIRED_ENV} turns a skip into a failure. */ + static boolean required() { + return "true".equals(System.getenv(REQUIRED_ENV)); + } + + // --------------------------------------------------------------------------------------------- + // Running a probe + + /** + * The output of {@code probe}'s {@code main} in a JVM that prints the C2 code of every method + * of {@code probe}, with vfdlibm's methods forced inline as the benchmarks run them, compiled on + * the calling thread ({@code -Xbatch}: a warm-up count alone only queues a compile), with hsdis + * from {@code hsdisDir} and this JVM's {@code -XX} options (a CI row's {@code UseAVX} and + * {@code MaxVectorSize}). Fails on a non-zero exit, a timeout, or output without the probe's + * done line. + */ + static String runProbe(Class probe, Path hsdisDir, List properties) + throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add(Path.of(System.getProperty("java.home"), "bin", "java").toString()); + command.addAll(List.of("-Xbatch", "-Xmx512m", "--add-modules", "jdk.incubator.vector", + "-XX:+UnlockDiagnosticVMOptions")); + for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) { + if (arg.startsWith("-XX:")) { + command.add(arg); + } + } + command.addAll(properties); + command.addAll(List.of("-XX:PrintAssemblyOptions=intel", "-XX:CompileCommand=quiet", + "-XX:CompileCommand=inline,io.github.vecbricks.vfdlibm.*::*", + "-XX:CompileCommand=print," + probe.getName() + "::*", + "-cp", System.getProperty("java.class.path"), probe.getName())); + ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true); + builder.environment().keySet().removeAll( + List.of("JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS", "_JAVA_OPTIONS")); + String path = builder.environment().get("LD_LIBRARY_PATH"); + builder.environment().put("LD_LIBRARY_PATH", + hsdisDir + (path == null || path.isEmpty() ? "" : ":" + path)); + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + Process process = builder.start(); + try { + CompletableFuture drained = CompletableFuture.runAsync(() -> { + try (InputStream in = process.getInputStream()) { + in.transferTo(bytes); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); + if (!process.waitFor(CHILD_SECONDS, TimeUnit.SECONDS)) { + throw new AssertionError("the probe JVM did not finish in " + CHILD_SECONDS + " s: " + + command); + } + drained.join(); + } finally { + process.destroyForcibly(); + } + String text = bytes.toString(StandardCharsets.UTF_8); + if (process.exitValue() != 0 || !text.contains("asm-probe done")) { + throw new AssertionError("the probe JVM failed (exit " + process.exitValue() + "): " + + command + "\n" + tail(text, 60)); + } + return text; + } + + /** The last {@code lines} lines of {@code text}. */ + static String tail(String text, int lines) { + List all = text.lines().toList(); + return String.join("\n", all.subList(Math.max(0, all.size() - lines), all.size())); + } + + // --------------------------------------------------------------------------------------------- + // Parsing + + /** One instruction: its address, mnemonic, operands and the comments HotSpot put after it. */ + record Instruction(long address, String mnemonic, String operands, String notes) { + @Override + public String toString() { + return String.format(Locale.ROOT, "0x%x: %s %s", address, mnemonic, operands); + } + } + + /** A method's C2 code from its entry point to its stubs. */ + record Body(String method, List code) {} + + // A mnemonic may be a directive (".byte") or "(bad)": what a disassembler prints for bytes it + // does not decode, which undecodedViolations must see rather than the parser drop. + private static final Pattern INSTRUCTION = Pattern.compile( + "^\\s*0x([0-9a-f]+):\\s+([a-z.(][a-z0-9_.()]*)(?:\\s+([^;]*?))?\\s*(;.*)?$"); + private static final Pattern NOTE = Pattern.compile("^\\s+;(.*)$"); + + /** + * Whether HotSpot disassembled: a {@code [Disassembly]} section holding an instruction line + * after an entry point. Without hsdis loaded neither appears. + */ + static boolean disassembled(String output) { + boolean inside = false; + boolean code = false; + for (String line : output.split("\n", -1)) { + if (line.startsWith("[Disassembly]")) { + inside = true; + } else if (line.startsWith("[/Disassembly]")) { + inside = false; + code = false; + } else if (inside && isEntry(line)) { + code = true; + } else if (inside && code && INSTRUCTION.matcher(line).matches()) { + return true; + } + } + return false; + } + + private static boolean isEntry(String line) { + return line.startsWith("[Entry Point]") || line.startsWith("[Verified Entry Point]"); + } + + private static boolean isEndOfCode(String line) { + return line.startsWith("[Stub Code]") || line.startsWith("[Exception Handler]") + || line.startsWith("[Deopt Handler Code]") || line.startsWith("[/Disassembly]"); + } + + /** + * The last standard C2 compile of {@code method} ({@code package.Class::name}), or empty when + * there is none: no C2 compile, only an on-stack-replacement one, or no disassembly. + */ + static Optional lastC2(String output, String method) { + String[] lines = output.split("\n", -1); + int start = -1; + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + if (line.startsWith("Compiled method (c2)") && line.contains(" " + method + " (") + && !line.contains(" % ")) { + start = i; + } + } + if (start < 0) { + return Optional.empty(); + } + List code = new ArrayList<>(); + boolean disassembly = false; + boolean inCode = false; + for (int i = start + 1; i < lines.length; i++) { + String line = lines[i]; + if (line.startsWith("Compiled method (") || line.startsWith("[/Disassembly]")) { + break; + } + if (line.startsWith("[Disassembly]")) { + disassembly = true; + } else if (disassembly && isEntry(line)) { + inCode = true; + } else if (inCode && isEndOfCode(line)) { + inCode = false; + } else if (inCode) { + Matcher m = INSTRUCTION.matcher(line); + if (m.matches()) { + String operands = m.group(3) == null ? "" : m.group(3).trim(); + String note = m.group(4) == null ? "" : m.group(4); + code.add(new Instruction(Long.parseUnsignedLong(m.group(1), 16), m.group(2), operands, + note)); + } else { + Matcher n = NOTE.matcher(line); + if (n.matches() && !code.isEmpty()) { + Instruction last = code.remove(code.size() - 1); + code.add(new Instruction(last.address(), last.mnemonic(), last.operands(), + last.notes() + " ;" + n.group(1).trim())); + } + } + } + } + return disassembly && !code.isEmpty() ? Optional.of(new Body(method, code)) : Optional.empty(); + } + + // --------------------------------------------------------------------------------------------- + // The rules + + private static final Pattern PACKED_DOUBLE = Pattern.compile("v(add|sub|mul|div)pd"); + private static final Pattern SCALAR_DOUBLE = Pattern.compile("v?(add|sub|mul|div)sd"); + private static final Pattern FMA = Pattern.compile("vfn?m(add|sub).*"); + private static final Pattern VECTOR_REGISTER = Pattern.compile("\\b([xyz]mm)\\d+\\b"); + private static final List ALLOWED_CALLS = + List.of("{runtime_call UncommonTrapBlob}", "{runtime_call Stub::method_entry_barrier}"); + + /** The register class of a vector of {@code bits}. */ + static String registerClass(int bits) { + return switch (bits) { + case 128 -> "xmm"; + case 256 -> "ymm"; + case 512 -> "zmm"; + default -> throw new IllegalArgumentException(bits + " bits"); + }; + } + + /** Packed-double arithmetic on {@code bits}' registers only, some of it, and no scalar. */ + static List widthViolations(Body body, int bits) { + String expected = registerClass(bits); + List violations = new ArrayList<>(); + int packed = 0; + for (Instruction insn : body.code()) { + if (PACKED_DOUBLE.matcher(insn.mnemonic()).matches()) { + packed++; + Matcher m = VECTOR_REGISTER.matcher(insn.operands()); + while (m.find()) { + if (!m.group(1).equals(expected)) { + violations.add(body.method() + ": " + insn + " is not on " + expected + + " registers alone"); + break; + } + } + } else if (SCALAR_DOUBLE.matcher(insn.mnemonic()).matches()) { + violations.add(body.method() + ": " + insn + " is scalar double arithmetic"); + } + } + if (packed == 0) { + violations.add(body.method() + ": no packed-double arithmetic (v(add|sub|mul|div)pd)"); + } + return violations; + } + + /** Every fused multiply-add instruction. */ + static List fmaViolations(Body body) { + return matching(body, insn -> FMA.matcher(insn.mnemonic()).matches(), + "is a fused multiply-add"); + } + + /** Every call that is not an uncommon trap or the entry barrier. */ + static List callViolations(Body body) { + return matching(body, insn -> insn.mnemonic().startsWith("call") + && ALLOWED_CALLS.stream().noneMatch(insn.notes()::contains), "is a call"); + } + + /** + * Every run of bytes the disassembler did not decode ({@code .byte}, {@code (bad)}). After one, + * the instructions that follow are read out of step, so no other rule can be trusted on the + * body: Capstone 4.0.2 printed {@code .byte 0x62} for an EVEX prefix and a {@code call} among + * the garbage after it. + */ + static List undecodedViolations(Body body) { + return matching(body, insn -> insn.mnemonic().startsWith(".") + || insn.mnemonic().equals("(bad)"), "was not decoded (hsdis's Capstone is older than 5?)"); + } + + /** Every instruction whose inlined frames name StrictMath or FdLibm. */ + static List licenceViolations(Body body) { + return matching(body, insn -> insn.notes().contains("java.lang.StrictMath::") + || insn.notes().contains("FdLibm"), "is StrictMath's code, which is not read here"); + } + + private static List matching(Body body, Predicate bad, String what) { + List violations = new ArrayList<>(); + for (Instruction insn : body.code()) { + if (bad.test(insn)) { + violations.add(body.method() + ": " + insn + " " + what + + (insn.notes().isEmpty() ? "" : " (" + insn.notes().trim() + ")")); + } + } + return violations; + } + + // --------------------------------------------------------------------------------------------- + // The census + + /** The census's columns, in order, each a family of mnemonics or operands. */ + static final Map> CENSUS = censusColumns(); + + private static Map> censusColumns() { + Map> c = new LinkedHashMap<>(); + c.put("insns", insn -> true); + c.put("pd arith", insn -> PACKED_DOUBLE.matcher(insn.mnemonic()).matches()); + c.put("vdivpd", insn -> insn.mnemonic().equals("vdivpd")); + c.put("blends", insn -> insn.mnemonic().contains("blend")); + c.put("broadcasts", insn -> insn.mnemonic().contains("broadcast")); + c.put("compares", insn -> insn.mnemonic().startsWith("vpcmp") + || insn.mnemonic().startsWith("vcmp")); + c.put("k ops", insn -> insn.mnemonic().startsWith("k")); + c.put("converts", insn -> insn.mnemonic().startsWith("vcvt") + || insn.mnemonic().matches("vpmov(s|us)?(q|d|w)(d|w|b)|vpmov[sz]x.*")); + c.put("stack", insn -> insn.operands().contains("[rsp")); + c.put("calls", insn -> insn.mnemonic().startsWith("call")); + c.put("fma", insn -> FMA.matcher(insn.mnemonic()).matches()); + return c; + } + + /** The census's counts for {@code body}, in {@link #CENSUS}'s order. */ + static List census(Body body) { + List counts = new ArrayList<>(); + for (Predicate column : CENSUS.values()) { + counts.add((int) body.code().stream().filter(column).count()); + } + return counts; + } +} diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java new file mode 100644 index 0000000..4bcfeb9 --- /dev/null +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java @@ -0,0 +1,250 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.vecbricks.vfdlibm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Tests of {@link AsmCheck} on crafted disassembly, written in the shapes HotSpot prints with + * hsdis (Capstone, Intel syntax: an address, the mnemonic and its operands separated by tabs, the + * inlined frames and the relocation on comment lines below): a clean body passes every rule, and + * a body with one defect, a fused multiply-add, a narrow or scalar instruction, a call, or + * StrictMath's code, fails the rule for it. The parser must also find nothing to read in HotSpot's + * hex dump (no hsdis loaded), in a C1 compile and in an on-stack-replacement one, since a rule + * that reads no instruction passes vacuously. + */ +class AsmCheckSelfTest { + + private static final String METHOD = "io.github.vecbricks.vfdlibm.Fixture::arm"; + + /** A C2 nmethod of {@link #METHOD} holding {@code code}, with a constant pool and stubs. */ + private static String nmethod(String code) { + return nmethod("c2", "", code); + } + + private static String nmethod(String compiler, String osr, String code) { + return """ + ============================= %s-compiled nmethod ============================== + ----------------------------------- Assembly ----------------------------------- + + Compiled method (%s) 2537 1030 %s 4 %s%s (41 bytes) + total in heap [0x00007ac3981f8708,0x00007ac3981f8c50] = 1352 + main code [0x00007ac3981f88c0,0x00007ac3981f8c30] = 880 + + [Disassembly] + -------------------------------------------------------------------------------- + + [Constant Pool] + Address hex4 hex8 + 0x00007ac3981f8800: 0xf4f4f4f4 0xf4f4f4f4f4f4f4f4 + + -------------------------------------------------------------------------------- + + [Verified Entry Point] + # {method} {0x00007ac34c401928} 'arm' '([D[D)V' in 'io/github/vecbricks/vfdlibm/Fixture' + # parm0: rsi:rsi = '[D' + %s\ + [Exception Handler] + 0x00007ac3981f8c30: jmp\t\t0x7ac397b923e0 ; {runtime_call ExceptionBlob} + [Deopt Handler Code] + 0x00007ac3981f8c35: call\t\t0x7ac3981f8c3a + 0x00007ac3981f8c3a: jmp\t\t0x7ac397aaf2e0 ; {runtime_call DeoptimizationBlob} + -------------------------------------------------------------------------------- + [/Disassembly] + """.formatted(compiler.toUpperCase(), compiler, osr, METHOD, osr.isEmpty() ? "" : " @ 2", + code); + } + + /** One instruction line at {@code address}. */ + private static String insn(int address, String mnemonic, String operands) { + return String.format(" 0x00007ac3981f%04x: %s\t\t%s%n", address, mnemonic, operands); + } + + /** A call with the comment lines HotSpot prints under it, ending in {@code relocation}. */ + private static String call(int address, String frame, String relocation) { + return insn(address, "call", "0x7ac397aae4e0 ; ImmutableOopMap {rbp=Oop }") + + " ;*ifeq {reexecute=1}\n" + + " ; - " + frame + "\n" + + " ; " + relocation + "\n"; + } + + /** A clean 512-bit body: zmm arithmetic, a ymm int lane, an xmm zeroing idiom, two calls. */ + private static String clean512() { + return insn(0x88c0, "call", "0x7ac397a975c0 ; {runtime_call Stub::method_entry_barrier}") + + insn(0x88c5, "vxorps", "xmm3, xmm3, xmm3") + + insn(0x88c9, "vmovupd", "zmm21, zmmword ptr [r8 + r11*8 + 0x10]") + + insn(0x88d4, "vmulpd", "zmm0, zmm19, zmm21") + + insn(0x88da, "vaddpd", "zmm0, zmm0, zmmword ptr [rip + 0x20]") + + insn(0x88e4, "vcvttpd2dq", "ymm15, zmm0") + + insn(0x88ea, "vpmovsxdq", "zmm2, ymm15") + + insn(0x88f0, "vdivpd", "zmm0, zmm24, zmm0") + + insn(0x88f6, "vpblendmq", "zmm1 {k3}, zmm0, zmm23") + + insn(0x88fc, "kortestb", "k7, k7") + + insn(0x8900, "jne", "0x7ac3981f8a00") + + call(0x8a00, "io.github.vecbricks.vfdlibm.Exp::exp@615 (line 298)", + "{runtime_call UncommonTrapBlob}"); + } + + private static AsmCheck.Body body(String output) { + Optional body = AsmCheck.lastC2(output, METHOD); + assertTrue(body.isPresent(), "no C2 body parsed"); + return body.get(); + } + + @Test + void aCleanBodyPassesEveryRule() { + String output = nmethod(clean512()); + assertTrue(AsmCheck.disassembled(output)); + AsmCheck.Body body = body(output); + // the constant pool and the stubs are not code; the entry barrier is the first instruction + assertEquals(12, body.code().size(), body.code().toString()); + assertEquals(List.of(), AsmCheck.widthViolations(body, 512)); + assertEquals(List.of(), AsmCheck.fmaViolations(body)); + assertEquals(List.of(), AsmCheck.callViolations(body)); + assertEquals(List.of(), AsmCheck.licenceViolations(body)); + List census = AsmCheck.census(body); + List columns = List.copyOf(AsmCheck.CENSUS.keySet()); + assertEquals(3, census.get(columns.indexOf("pd arith"))); + assertEquals(1, census.get(columns.indexOf("vdivpd"))); + assertEquals(2, census.get(columns.indexOf("calls"))); + assertEquals(2, census.get(columns.indexOf("converts"))); + assertEquals(0, census.get(columns.indexOf("fma"))); + } + + @ParameterizedTest + @ValueSource(strings = {"vfmadd231pd", "vfmsub132pd", "vfnmadd213pd", "vfnmsub231sd", + "vfmaddsub213pd", "vfmsubadd231pd", "vfmadd213ps"}) + void aFusedMultiplyAddFails(String fma) { + AsmCheck.Body body = body(nmethod(clean512().replace("vmulpd", fma))); + assertEquals(1, AsmCheck.fmaViolations(body).size(), fma); + } + + @Test + void aNarrowBodyFailsTheWidthRule() { + // the whole body a width down: every packed-double instruction on ymm + String narrow = clean512().replace("zmm", "ymm"); + List violations = AsmCheck.widthViolations(body(nmethod(narrow)), 512); + assertEquals(3, violations.size(), violations.toString()); + // the same body read at its own width passes + assertEquals(List.of(), AsmCheck.widthViolations(body(nmethod(narrow)), 256)); + // one instruction narrow, and one wider than expected + assertEquals(1, AsmCheck.widthViolations( + body(nmethod(clean512().replace("vdivpd\t\tzmm0", "vdivpd\t\tymm0"))), 512).size()); + assertEquals(1, AsmCheck.widthViolations(body(nmethod(narrow.replace( + "vdivpd\t\tymm0, ymm24, ymm0", "vdivpd\t\tzmm0, zmm24, zmm0"))), 256).size()); + } + + @Test + void scalarOrNoPackedArithmeticFailsTheWidthRule() { + String scalar = + clean512().replace("vmulpd\t\tzmm0, zmm19, zmm21", "vmulsd\t\txmm0, xmm19, xmm21"); + List violations = AsmCheck.widthViolations(body(nmethod(scalar)), 512); + assertEquals(1, violations.size(), violations.toString()); + assertTrue(violations.get(0).contains("scalar"), violations.toString()); + String none = clean512().replaceAll("v(mul|add|div)pd", "vpaddq"); + violations = AsmCheck.widthViolations(body(nmethod(none)), 512); + assertEquals(1, violations.size(), violations.toString()); + assertTrue(violations.get(0).contains("no packed-double"), violations.toString()); + } + + @ParameterizedTest + @ValueSource(strings = {"{static_call}", "{optimized virtual_call}", "{virtual_call}", + "{runtime_call C2 Runtime new_instance}", "{runtime_call StubRoutines::dexp}"}) + void aCallThatIsNotATrapFails(String relocation) { + String code = clean512() + + call(0x8a40, "jdk.incubator.vector.DoubleVector::fromArray@24 (line 2832)", relocation); + List violations = AsmCheck.callViolations(body(nmethod(code))); + assertEquals(1, violations.size(), violations.toString()); + assertTrue(violations.get(0).contains(relocation), violations.toString()); + } + + @ParameterizedTest + @ValueSource(strings = {"java.lang.StrictMath::exp@1 (line 254)", + "java.lang.FdLibm$Exp::compute@12 (line 2400)"}) + void strictMathCodeFails(String frame) { + String code = clean512() + call(0x8a40, frame, "{runtime_call UncommonTrapBlob}"); + assertEquals(1, AsmCheck.licenceViolations(body(nmethod(code))).size()); + } + + /** Capstone 4.0.2's reading of an AVX-512 body: an EVEX prefix as .byte, garbage after it. */ + @Test + void undecodedBytesFail() { + String code = clean512() + + insn(0x8a40, ".byte", "0x62") + + insn(0x8a41, "cmc", "") + + insn(0x8a42, "call", "0x76759d920cce") + + insn(0x8a47, "(bad)", ""); + AsmCheck.Body body = body(nmethod(code)); + assertEquals(2, AsmCheck.undecodedViolations(body).size(), body.code().toString()); + assertEquals(List.of(), AsmCheck.undecodedViolations(body(nmethod(clean512())))); + } + + /** HotSpot's output when no hsdis is loaded: the same nmethod as hex words under MachCode. */ + @Test + void aHexDumpIsNotDisassembly() { + String hex = """ + ============================= C2-compiled nmethod ============================== + Compiled method (c2) 544 1419 4 %s (41 bytes) + main code [0x00007b7f141fe580,0x00007b7f141fe5d0] = 80 + + [Constant Pool (empty)] + + [MachCode] + [Verified Entry Point] + # {method} {0x00007b7ec0a9c298} 'arm' '([D[D)V' in 'io/github/vecbricks/vfdlibm/Fixture' + 0x00007b7f141fe580: 4881 ec18 | 0000 0048 | 896c 2410 | 4181 7f20 | 0000 0000 | 0f85 + 0x00007b7f141fe5a0: ; {poll_return} + 0x00007b7f141fe5a0: 105d 493b | 6728 0f87 | 0100 0000 + 0x00007b7f141fe5ac: c349 baa2 | e51f 147f | 7b00 004d | 8997 3805 + [Exception Handler] + 0x00007b7f141fe5d0: e90b 3e99 | ffe8 0000 | 0000 4883 + [/MachCode] + """.formatted(METHOD); + assertFalse(AsmCheck.disassembled(hex)); + assertEquals(Optional.empty(), AsmCheck.lastC2(hex, METHOD)); + } + + @Test + void aC1OrOnStackReplacementCompileIsNotRead() { + assertEquals(Optional.empty(), AsmCheck.lastC2(nmethod("c1", "", clean512()), METHOD)); + assertEquals(Optional.empty(), AsmCheck.lastC2(nmethod("c2", "%", clean512()), METHOD)); + // with an OSR compile after the standard one, the standard one is read + String narrowOsr = nmethod("c2", "%", clean512().replace("zmm", "ymm")); + AsmCheck.Body body = body(nmethod(clean512()) + narrowOsr); + assertEquals(List.of(), AsmCheck.widthViolations(body, 512)); + // of two standard compiles, the last is read + body = body(nmethod(clean512()) + nmethod(clean512().replace("zmm", "ymm"))); + assertEquals(3, AsmCheck.widthViolations(body, 512).size()); + } + + @Test + void hsdisNotFoundSaysWhereItLooked(@TempDir Path dir) throws Exception { + AsmCheck.Hsdis none = AsmCheck.findHsdis(null, "hsdis-amd64.so", List.of(dir)); + assertFalse(none.found()); + assertTrue(none.why().startsWith("hsdis not found") && none.why().contains(dir.toString()), + none.why()); + Files.createFile(dir.resolve("hsdis-amd64.so")); + assertEquals(dir, AsmCheck.findHsdis(null, "hsdis-amd64.so", List.of(dir)).dir()); + // the environment's directory replaces the defaults + AsmCheck.Hsdis env = AsmCheck.findHsdis(dir.resolve("elsewhere").toString(), "hsdis-amd64.so", + List.of(dir)); + assertFalse(env.found()); + } +} diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java new file mode 100644 index 0000000..bff4b97 --- /dev/null +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java @@ -0,0 +1,118 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.vecbricks.vfdlibm; + +import java.util.SplittableRandom; +import jdk.incubator.vector.DoubleVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorSpecies; + +/** + * The child JVM of {@link ExpAsmTest}: each of exp's vector arms in a loop over an array, the + * shape {@code ExpBenchmark}'s rows have, warmed until C2 compiles the loop with the arm inlined, + * so that {@code -XX:CompileCommand=print} on this class prints the code a caller runs. + * + *

One species per JVM, named by the {@link VectorWidth} in {@code -Dvfdlibm.asm.width} and read + * into a {@code static final}, a constant to C2. The data are {@code ExpBenchmark}'s common inputs, + * {@code [-20, 20]}, so no lane takes a rare path: the per-lane finish is compiled as an uncommon + * trap, and no {@code StrictMath} code is compiled into the loops (AGENTS.md, licence). + */ +final class ExpAsmProbe { + + /** The width this JVM runs, from {@code -Dvfdlibm.asm.width}. */ + static final VectorWidth WIDTH = VectorWidth.valueOf(System.getProperty("vfdlibm.asm.width")); + static final VectorSpecies S = WIDTH.species(); + static final int N = 256; + /** Calls of each loop: past C2's thresholds, and under -Xbatch each compile completes. */ + static final int CALLS = 12_000; + + private ExpAsmProbe() {} + + /** {@link VFdlibm#exp(DoubleVector)}: the finish arm, every lane. */ + static void finish(double[] in, double[] out) { + for (int i = 0; i < N; i += S.length()) { + VFdlibm.exp(DoubleVector.fromArray(S, in, i)).intoArray(out, i); + } + } + + /** {@link VFdlibm#exp(DoubleVector, VectorMask)}: the finish arm, live lanes only. */ + static void finishMasked(double[] in, double[] out, boolean[] live) { + for (int i = 0; i < N; i += S.length()) { + VFdlibm.exp(DoubleVector.fromArray(S, in, i), VectorMask.fromArray(S, live, i)) + .intoArray(out, i); + } + } + + /** {@link Exp#expBlended}: every branch computed and blended, every lane. */ + static void blended(double[] in, double[] out) { + for (int i = 0; i < N; i += S.length()) { + Exp.expBlended(DoubleVector.fromArray(S, in, i), null).intoArray(out, i); + } + } + + /** {@link Exp#expBlended}, live lanes only. */ + static void blendedMasked(double[] in, double[] out, boolean[] live) { + for (int i = 0; i < N; i += S.length()) { + Exp.expBlended(DoubleVector.fromArray(S, in, i), VectorMask.fromArray(S, live, i)) + .intoArray(out, i); + } + } + + /** + * {@link Exp#expRare} and {@link Exp#expCore}: the rare lanes and the branch-free part, in + * {@code ExpBenchmark}'s order. The other order boxes: with {@code expCore} inlined first, C2 + * refuses {@code expRare} for {@code NodeCountInliningCutoff} (SKILLS.md, "The assembly check"). + */ + static void core(double[] in, double[] out, boolean[] rare) { + for (int i = 0; i < N; i += S.length()) { + DoubleVector x = DoubleVector.fromArray(S, in, i); + Exp.expRare(x).intoArray(rare, i); + Exp.expCore(x).intoArray(out, i); + } + } + + /** + * Prints a start line with the species, warms each arm in turn and prints a done line. A + * species other than the one named fails, since the test would then check the wrong width. + */ + public static void main(String[] args) { + System.out.println("asm-probe start: width " + WIDTH + ", " + S.vectorBitSize() + " bits"); + SplittableRandom random = new SplittableRandom(1L); + double[] in = new double[N]; + double[] out = new double[N]; + boolean[] live = new boolean[N]; + boolean[] flags = new boolean[N]; + for (int i = 0; i < N; i++) { + in[i] = random.nextDouble(-20.0, 20.0); + live[i] = random.nextBoolean(); + } + double sink = 0; + for (int c = 0; c < CALLS; c++) { + finish(in, out); + sink += out[c & (N - 1)]; + } + for (int c = 0; c < CALLS; c++) { + finishMasked(in, out, live); + sink += out[c & (N - 1)]; + } + for (int c = 0; c < CALLS; c++) { + blended(in, out); + sink += out[c & (N - 1)]; + } + for (int c = 0; c < CALLS; c++) { + blendedMasked(in, out, live); + sink += out[c & (N - 1)]; + } + for (int c = 0; c < CALLS; c++) { + core(in, out, flags); + sink += out[c & (N - 1)]; + } + System.out.println("asm-probe done: " + sink); + } +} diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java new file mode 100644 index 0000000..60e6128 --- /dev/null +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -0,0 +1,120 @@ +/* + * Licensed to the vecbricks contributors under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy of the + * License at http://www.apache.org/licenses/LICENSE-2.0. Software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.github.vecbricks.vfdlibm; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assumptions.abort; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * The assembly check of exp's vector arms (SKILLS.md, "The assembly check"): at each {@link + * VectorWidth} the host has, {@link ExpAsmProbe} runs in a JVM of its own and prints the C2 code + * of a loop over each arm with the arm inlined, and each arm's code must meet {@link AsmCheck}'s + * rules: packed-double arithmetic on registers of the width, no fused multiply-add, no call but + * uncommon traps and the entry barrier, and no StrictMath code. + * + *

The arms are {@code VFdlibm.exp} unmasked and masked (the finish arm), {@code + * Exp.expBlended} unmasked and masked, and {@code Exp.expCore} with {@code Exp.expRare}. Exp's + * own methods are not printed alone: without the forced inline the arms' shared body compiles as + * a method of its own whose {@code arm} is no constant, taking and returning its vectors as heap + * objects, which is not code any caller runs inline (SKILLS.md). + * + *

At 128 bits on x86 the call rule is not asserted: C2 lowers no mask of two 64-bit lanes + * there (SKILLS.md, "At two 64-bit lanes x86 C2 lowers no mask"), so every arm calls into the + * Vector API's Java fallback. Its width and FMA rules are asserted. The width is the child's + * species, so the preferred species at 128 bits ({@code -XX:MaxVectorSize=16}) is treated alike. + * + *

Skipped, with the reason, on a host that is not x86-64, when no hsdis is found ({@link + * AsmCheck#findHsdis}), and when one is found but HotSpot printed no disassembly with it; with + * {@code VFDLIBM_ASM_REQUIRED=true}, as CI's x86 rows set, the last two fail instead. + */ +class ExpAsmTest { + + private static final String PROBE = ExpAsmProbe.class.getName(); + /** + * The probe's methods, one per arm. Named here, not read from the probe, whose initialization + * reads the child's width property. + */ + static final List ARMS = + List.of("finish", "finishMasked", "blended", "blendedMasked", "core"); + + @ParameterizedTest + @EnumSource(VectorWidth.class) + void eachArmIsVectorAtItsWidthWithNoFmaAndNoCall(VectorWidth width) throws Exception { + int bits = width.species().vectorBitSize(); + String output = probe(width); + assertTrue(output.contains("asm-probe start: width " + width + ", " + bits + " bits"), + "the probe ran another species than " + width + " at " + bits + " bits"); + boolean callsChecked = bits > 128; + List violations = new ArrayList<>(); + // The census, as Markdown rows: `grep '^| exp '` on the test's output gives SKILLS.md's table. + System.out.println("| function | width | bits | arm | " + String.join(" | ", + AsmCheck.CENSUS.keySet()) + " |"); + for (String arm : ARMS) { + Optional body = AsmCheck.lastC2(output, PROBE + "::" + arm); + if (body.isEmpty()) { + fail("no standard C2 compile of " + arm + " at " + width + "; the probe's output ends:\n" + + AsmCheck.tail(output, 40)); + } + System.out.println("| exp | " + width + " | " + bits + " | " + arm + " | " + + String.join(" | ", AsmCheck.census(body.get()).stream().map(String::valueOf).toList()) + + " |"); + violations.addAll(AsmCheck.undecodedViolations(body.get())); + violations.addAll(AsmCheck.widthViolations(body.get(), bits)); + violations.addAll(AsmCheck.fmaViolations(body.get())); + violations.addAll(AsmCheck.licenceViolations(body.get())); + if (callsChecked) { + violations.addAll(AsmCheck.callViolations(body.get())); + } + } + if (!callsChecked) { + System.out.println("exp asm " + width + ": calls not checked at 128 bits on x86 (no mask " + + "of two lanes lowers; SKILLS.md)"); + } + assertEquals(List.of(), violations, "exp's arms at " + width + " (" + bits + " bits)"); + } + + /** + * The probe's output at {@code width}, or a skip (a failure when required) when this host has + * no hsdis that HotSpot loads. + */ + static String probe(VectorWidth width) throws IOException, InterruptedException { + if (AsmCheck.libraryName() == null) { + abort("the assembly check reads x86-64 code only; this host is " + + System.getProperty("os.arch")); + } + AsmCheck.Hsdis hsdis = AsmCheck.findHsdis(); + if (!hsdis.found()) { + skipOrFail(hsdis.why()); + } + String output = AsmCheck.runProbe(ExpAsmProbe.class, hsdis.dir(), + List.of("-Dvfdlibm.asm.width=" + width.name())); + if (!AsmCheck.disassembled(output)) { + skipOrFail("hsdis found but not loaded: " + hsdis.dir().resolve(AsmCheck.libraryName()) + + " exists, and HotSpot printed no [Disassembly] with it; the probe's output ends:\n" + + AsmCheck.tail(output, 20)); + } + return output; + } + + private static void skipOrFail(String why) { + if (AsmCheck.required()) { + fail(why + " (" + AsmCheck.REQUIRED_ENV + "=true)"); + } + abort(why); + } +} From a0e38ec09f736c535071c2c85081b83dbd2153ca Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 21:42:21 +0100 Subject: [PATCH 2/9] [VFDLIBM-139] Address review: Linux only, Capstone 5 exactly, no ~/hsdis, cached hsdis in CI Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 26 +++++++++++++++---- SKILLS.md | 11 ++++---- dev/hsdis-build.sh | 12 ++++----- .../io/github/vecbricks/vfdlibm/AsmCheck.java | 12 ++++++--- .../github/vecbricks/vfdlibm/ExpAsmTest.java | 6 ++--- 5 files changed, 44 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1066288..b417647 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,13 +72,29 @@ jobs: m2-${{ runner.os }}-${{ runner.arch }}-java25-build- # The assembly check (ExpAsmTest; SKILLS.md, "The assembly check") reads C2's code through # hsdis, which dev/hsdis-build.sh builds into target/hsdis from two pinned files of the JDK's - # source and a pinned Capstone 5, in seconds; it is a tool, never committed or shipped. The - # runner's own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. On - # the x86 rows VFDLIBM_ASM_REQUIRED turns the check's skip for a missing or unloaded hsdis - # into a failure, so a green row has read the code. The Arm row skips it: its rules are x86's. + # source and a pinned Capstone 5; it is a tool, never committed or shipped. The runner's + # own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. The build is + # cached on the script, which pins every source, so a run fetches nothing once it is; a + # cached one is still checked to load. On the x86 rows VFDLIBM_ASM_REQUIRED turns the + # check's skip for a missing or unloaded hsdis into a failure, so a green row has read the + # code. The Arm row skips it: its rules are x86's. + - name: Cache hsdis + if: matrix.asm + id: hsdis + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: target/hsdis + key: hsdis-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('dev/hsdis-build.sh') }} - name: Build hsdis for the assembly check if: matrix.asm - run: dev/hsdis-build.sh + env: + CACHED: ${{ steps.hsdis.outputs.cache-hit }} + run: | + if [ "$CACHED" = true ]; then + dev/hsdis-build.sh --check target/hsdis + else + dev/hsdis-build.sh + fi - name: Build and test env: VFDLIBM_ASM_REQUIRED: ${{ matrix.asm }} diff --git a/SKILLS.md b/SKILLS.md index 1ed19cd..991c95a 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -269,12 +269,13 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In pinned, compiled and never read) against Capstone. Ubuntu 24.04's Capstone 4.0.2, GitHub's ubuntu-latest, printed exp's 256-bit AVX-512 bodies with 19 to 43 undecoded `.byte` lines each, an EVEX prefix it did not know followed by garbage with a `call` in it (read in an - ubuntu:24.04 container on the laptop). So the script uses the system's Capstone only at 5 or - later and otherwise builds the pinned 5.0.7 from source with cmake, five seconds in that - container, whose census then matched the laptop's to the instruction; and the check fails on + ubuntu:24.04 container on the laptop). So the script uses the system's Capstone only at 5 and + otherwise builds the pinned 5.0.7 from source with cmake; in that container the census then + matched the laptop's to the instruction; and the check fails on any `.byte` or `(bad)`. -- **Skips say which.** Not x86-64; hsdis not found (the script's `target/hsdis`, `~/hsdis` or - `$VFDLIBM_HSDIS_DIR`); or found but not loaded, decided by the output holding no +- **Skips say which.** Not Linux on x86-64; hsdis not found (the script's `target/hsdis`, which + `mvn clean` deletes, or `$VFDLIBM_HSDIS_DIR`; a binutils hsdis such as `bench/asm`'s prints + another format, which the rules were not written for); or found but not loaded, decided by the output holding no `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, which it printed both with no library and with a file that was none. CI's x86 rows build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes the last two fail instead; the Arm row skips. diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh index 347dc42..96d67c3 100755 --- a/dev/hsdis-build.sh +++ b/dev/hsdis-build.sh @@ -23,16 +23,16 @@ # checked against the SHA-256 pinned below; they are compiled, not read. A product JVM finds # hsdis-.so on LD_LIBRARY_PATH; no JDK is built. # -# The disassembler behind them is Capstone (BSD), version 5 or later. The system's is used when -# its capstone.h says 5 or more (apt install libcapstone-dev, Ubuntu 25.04 and later), and the -# build takes gcc and a second. Otherwise, or with --capstone-source, Capstone's pinned release is +# The disassembler behind them is Capstone (BSD), version 5. The system's is used when its +# capstone.h says 5 (apt install libcapstone-dev, Ubuntu 25.04 and later), and the build takes +# gcc only; 6 renamed the Arm architecture this script names. Otherwise, or with --capstone-source, Capstone's pinned release is # fetched, checked against its SHA-256 and built with cmake under target/hsdis/capstone, for this # host's architecture only, and linked in statically. Version 4 will not do: Ubuntu 24.04's # 4.0.2, which GitHub's ubuntu-latest has, printed an AVX-512 body of exp at 256 bits with # ".byte 0x62" and garbage after it, a "call" among the garbage (SKILLS.md, "The assembly check"). # # The library goes to target/hsdis/hsdis-amd64.so on x86-64 and target/hsdis/hsdis-aarch64.so on -# Arm (or --out

). Then the check runs: a JVM with LD_LIBRARY_PATH= prints one compiled +# Arm (or --out ); mvn clean deletes it, and the check then skips until it is built again. Then the check runs: a JVM with LD_LIBRARY_PATH= prints one compiled # method of a two-line class of this script's own, and the build passes only if the output holds # a [Disassembly] section with an instruction line in it. Without a disassembler HotSpot prints # raw hex instead and does not fail, so the exit status of that JVM would prove nothing. @@ -116,10 +116,10 @@ command -v gcc > /dev/null || { echo "hsdis-build: gcc not found" >&2; exit 1; } || { echo "hsdis-build: no jni.h under $java_home/include" >&2; exit 1; } mkdir -p "$out" -# The system's Capstone if it is 5 or later, else the pinned release built here. +# The system's Capstone if it is 5, else the pinned release built here. system_major=$(sed -n 's/^#define CS_API_MAJOR \([0-9]*\).*/\1/p' \ /usr/include/capstone/capstone.h 2> /dev/null || true) -if [ -z "$capstone_source" ] && [ "${system_major:-0}" -ge 5 ]; then +if [ -z "$capstone_source" ] && [ "${system_major:-0}" = 5 ]; then echo "using the system's Capstone (API $system_major)" cs_include=/usr/include/capstone cs_link=(-lcapstone) diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java index a0c9a75..898f02d 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java @@ -86,6 +86,9 @@ boolean found() { /** The library's file name on this architecture, or null where the check does not run. */ static String libraryName() { + if (!System.getProperty("os.name").equals("Linux")) { + return null; + } String arch = System.getProperty("os.arch"); return switch (arch) { case "amd64", "x86_64" -> "hsdis-amd64.so"; @@ -95,14 +98,14 @@ static String libraryName() { /** * The directory holding hsdis: {@code $VFDLIBM_HSDIS_DIR} if set, else {@code target/hsdis} - * (where {@code dev/hsdis-build.sh} builds it), else {@code ~/hsdis}. Found means the file + * (where {@code dev/hsdis-build.sh} builds it, on Capstone, the output the rules and the + * self-test read; a binutils hsdis prints another one). Found means the file * exists; whether HotSpot loads it is known only from a probe's output ({@link * #disassembled}). */ static Hsdis findHsdis() { return findHsdis(System.getenv(HSDIS_DIR_ENV), libraryName(), - List.of(Path.of("target", "hsdis").toAbsolutePath(), - Path.of(System.getProperty("user.home"), "hsdis"))); + List.of(Path.of("target", "hsdis").toAbsolutePath())); } /** {@link #findHsdis()} with the environment's value and the default places given. */ @@ -166,8 +169,9 @@ static String runProbe(Class probe, Path hsdisDir, List properties) } }); if (!process.waitFor(CHILD_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly().waitFor(10, TimeUnit.SECONDS); throw new AssertionError("the probe JVM did not finish in " + CHILD_SECONDS + " s: " - + command); + + command + "\n" + tail(bytes.toString(StandardCharsets.UTF_8), 60)); } drained.join(); } finally { diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java index 60e6128..52da313 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -38,7 +38,7 @@ * Vector API's Java fallback. Its width and FMA rules are asserted. The width is the child's * species, so the preferred species at 128 bits ({@code -XX:MaxVectorSize=16}) is treated alike. * - *

Skipped, with the reason, on a host that is not x86-64, when no hsdis is found ({@link + *

Skipped, with the reason, on a host that is not Linux on x86-64, when no hsdis is found ({@link * AsmCheck#findHsdis}), and when one is found but HotSpot printed no disassembly with it; with * {@code VFDLIBM_ASM_REQUIRED=true}, as CI's x86 rows set, the last two fail instead. */ @@ -94,8 +94,8 @@ void eachArmIsVectorAtItsWidthWithNoFmaAndNoCall(VectorWidth width) throws Excep */ static String probe(VectorWidth width) throws IOException, InterruptedException { if (AsmCheck.libraryName() == null) { - abort("the assembly check reads x86-64 code only; this host is " - + System.getProperty("os.arch")); + abort("the assembly check reads Linux x86-64 code only; this host is " + + System.getProperty("os.name") + " " + System.getProperty("os.arch")); } AsmCheck.Hsdis hsdis = AsmCheck.findHsdis(); if (!hsdis.found()) { From 8e9d9b6a89613d8a50de67b25665ab5240d1a703 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 21:48:38 +0100 Subject: [PATCH 3/9] [VFDLIBM-139] Address review: rebuild a stale cached hsdis, check option arguments, rewrap Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 8 ++--- AGENTS.md | 8 ++--- SKILLS.md | 36 +++++++++---------- dev/hsdis-build.sh | 30 ++++++++-------- .../github/vecbricks/vfdlibm/ExpAsmProbe.java | 5 +-- .../github/vecbricks/vfdlibm/ExpAsmTest.java | 6 ++-- 6 files changed, 48 insertions(+), 45 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b417647..af09e89 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -75,9 +75,9 @@ jobs: # source and a pinned Capstone 5; it is a tool, never committed or shipped. The runner's # own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. The build is # cached on the script, which pins every source, so a run fetches nothing once it is; a - # cached one is still checked to load. On the x86 rows VFDLIBM_ASM_REQUIRED turns the - # check's skip for a missing or unloaded hsdis into a failure, so a green row has read the - # code. The Arm row skips it: its rules are x86's. + # cached one is still checked to load, and rebuilt if it does not. On the x86 rows + # VFDLIBM_ASM_REQUIRED turns the check's skip for a missing or unloaded hsdis into a + # failure, so a green row has read the code. The Arm row skips it: its rules are x86's. - name: Cache hsdis if: matrix.asm id: hsdis @@ -91,7 +91,7 @@ jobs: CACHED: ${{ steps.hsdis.outputs.cache-hit }} run: | if [ "$CACHED" = true ]; then - dev/hsdis-build.sh --check target/hsdis + dev/hsdis-build.sh --check target/hsdis || dev/hsdis-build.sh else dev/hsdis-build.sh fi diff --git a/AGENTS.md b/AGENTS.md index 69b5d0b..8bb1c7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,10 +53,10 @@ vfdlibm ports fdlibm's double functions to the Java Vector API, each lane bit-id and 512 bits and the preferred species, and `PlantedFaultTest` requires each fault planted through `Faults` (in the main sources) to be caught by its check. `HarnessSelfTest` tests them. - The assembly check: `ExpAsmTest` reads the C2 code of exp's arms through hsdis and asserts - the width, no fused multiply-add and no call but uncommon traps (`AsmCheckSelfTest` shows - each rule failing). `dev/hsdis-build.sh` builds hsdis into `target/hsdis`; it is OpenJDK's - GPL source compiled as a tool, never committed or shipped. Without it the check skips and - says why; CI's x86 rows build it and set `VFDLIBM_ASM_REQUIRED=true`, so there a skip fails. + the width, no fused multiply-add and no call but uncommon traps and the entry barrier + (`AsmCheckSelfTest` shows each rule failing). `dev/hsdis-build.sh` builds hsdis into + `target/hsdis`; it is OpenJDK's GPL source compiled as a tool, never committed or shipped. + Without it the check skips and says why; CI's x86 rows build it and set `VFDLIBM_ASM_REQUIRED=true`, so there a skip fails. See `SKILLS.md`, "The assembly check". - A width wider than the host's vectors is skipped. To see an AVX2 host's skips on an AVX-512 one: `mvn -B test -Dvfdlibm.test.jvmArgs=-XX:MaxVectorSize=32`. That keeps AVX-512's diff --git a/SKILLS.md b/SKILLS.md index 991c95a..9a2c94b 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -274,21 +274,22 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In matched the laptop's to the instruction; and the check fails on any `.byte` or `(bad)`. - **Skips say which.** Not Linux on x86-64; hsdis not found (the script's `target/hsdis`, which - `mvn clean` deletes, or `$VFDLIBM_HSDIS_DIR`; a binutils hsdis such as `bench/asm`'s prints - another format, which the rules were not written for); or found but not loaded, decided by the output holding no - `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, which it - printed both with no library and with a file that was none. CI's x86 rows build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes - the last two fail instead; the Arm row skips. + `mvn clean` deletes, or `$VFDLIBM_HSDIS_DIR`; a binutils hsdis such as `bench/asm`'s prints another + format, which the rules were not written for); or found but not loaded, decided by the output + holding no `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, + which it printed both with no library and with a file that was none. CI's x86 rows build hsdis and + set `VFDLIBM_ASM_REQUIRED=true`, which makes the last two fail instead; the Arm row skips. **The census of exp's arms, 22 November 2026, on the laptop** (AMD Ryzen AI 9 HX PRO 370, JDK 25.0.5.1, hsdis on Capstone 5.0.7). Not a headline and no timing: counts of instructions only, one -run, the same in a second. Each is the whole nmethod of the probe's loop, prologue and -out-of-line paths included, so the constant broadcasts C2 hoists before the loop count, and -from 256 bits up the stack accesses are the stack bang and the uncommon traps' saves, not -spills; `bench/asm/README.md` counts the hot loop alone. The columns: all instructions, packed-double arithmetic, `vdivpd`, blends, broadcasts, -compares (`vpcmp*`, `vcmp*`), mask-register operations (`k*`), conversions (`vcvt*`, `vpmov*`), -operands on `[rsp`, calls, FMA. The preferred species read the same as its fixed width (512 bits -on the host's flags, 256 as an AVX2 host). The rows come from the test's output: `grep '^| exp '`. +run, the same in a second. Each is the whole nmethod of the probe's loop, prologue and out-of-line +paths included, so the constant broadcasts C2 hoists before the loop count, and from 256 bits up the +stack accesses are the stack bang and the uncommon traps' saves, not spills; `bench/asm/README.md` +counts the hot loop alone. The columns: all instructions, packed-double arithmetic, `vdivpd`, +blends, broadcasts, compares (`vpcmp*`, `vcmp*`), mask-register operations (`k*`), conversions +(`vcvt*`, `vpmov*`), operands on `[rsp`, calls, FMA. The preferred species read the same as its +fixed width (512 bits on the host's flags, 256 as an AVX2 host). The rows are the test's output +(`grep '^| exp '`), less its function and width columns, under shorter headers. On the host's own flags (AVX-512, `MaxVectorSize=64`): @@ -326,14 +327,13 @@ As an AVX2 host (`-XX:UseAVX=2 -XX:MaxVectorSize=32`): | 256 | core | 140 | 24 | 1 | 5 | 17 | 8 | 0 | 3 | 3 | 2 | 0 | What it reads: no FMA in any arm at any width under either flag set. From 256 bits up every arm is -one copy of the body (24 packed-double operations, one `vdivpd`; the blended arm's two more are -its filter's `x + x` and the subnormal scale's product) and calls only its traps and the entry -barrier: three for the finish arms (the finish's trap, the loop's range check, the barrier), two -for the others. The blended arm has 6 more blends than the finish on AVX-512 and 5 more on AVX2, and 7 to 8 +one copy of the body (24 packed-double operations, one `vdivpd`; the blended arm's two more are its +filter's `x + x` and the subnormal scale's product) and calls only its traps and the entry barrier: +three for the finish arms (the finish's trap, the loop's range check, the barrier), two for the +others. The blended arm has 6 more blends than the finish on AVX-512 and 5 more on AVX2, and 7 to 8 more broadcasts, its filter's constants. AVX2 has no mask registers, so its masks are vector compares and `vblendvps`, 2 to 3 more blends per arm than AVX-512's `vpblendmq`. Masking adds one -blend and 10 to 23 instructions. At 128 bits the bodies are 8 to 16 times longer: the Java -fallback. +blend and 10 to 23 instructions. At 128 bits the bodies are 8 to 16 times longer: the Java fallback. ## Where headline numbers come from: four named hosts diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh index 96d67c3..76d0862 100755 --- a/dev/hsdis-build.sh +++ b/dev/hsdis-build.sh @@ -24,18 +24,20 @@ # hsdis-.so on LD_LIBRARY_PATH; no JDK is built. # # The disassembler behind them is Capstone (BSD), version 5. The system's is used when its -# capstone.h says 5 (apt install libcapstone-dev, Ubuntu 25.04 and later), and the build takes -# gcc only; 6 renamed the Arm architecture this script names. Otherwise, or with --capstone-source, Capstone's pinned release is -# fetched, checked against its SHA-256 and built with cmake under target/hsdis/capstone, for this -# host's architecture only, and linked in statically. Version 4 will not do: Ubuntu 24.04's -# 4.0.2, which GitHub's ubuntu-latest has, printed an AVX-512 body of exp at 256 bits with -# ".byte 0x62" and garbage after it, a "call" among the garbage (SKILLS.md, "The assembly check"). +# capstone.h says 5 (apt install libcapstone-dev, Ubuntu 25.04 and later), and the build takes gcc +# only; 6 renamed the Arm architecture this script names. Otherwise, or with --capstone-source, +# Capstone's pinned release is fetched, checked against its SHA-256 and built with cmake under +# target/hsdis/capstone, for x86 and Arm only, and linked in statically. Version 4 will not do: +# Ubuntu 24.04's 4.0.2, which GitHub's ubuntu-latest has, printed an AVX-512 body of exp at 256 bits +# with ".byte 0x62" and garbage after it, a "call" among the garbage (SKILLS.md, "The assembly +# check"). # -# The library goes to target/hsdis/hsdis-amd64.so on x86-64 and target/hsdis/hsdis-aarch64.so on -# Arm (or --out

); mvn clean deletes it, and the check then skips until it is built again. Then the check runs: a JVM with LD_LIBRARY_PATH= prints one compiled -# method of a two-line class of this script's own, and the build passes only if the output holds -# a [Disassembly] section with an instruction line in it. Without a disassembler HotSpot prints -# raw hex instead and does not fail, so the exit status of that JVM would prove nothing. +# The library goes to target/hsdis/hsdis-amd64.so on x86-64 and target/hsdis/hsdis-aarch64.so on Arm +# (or --out ); mvn clean deletes it, and the check then skips until it is built again. Then the +# check runs: a JVM with LD_LIBRARY_PATH= prints one compiled method of a two-line class of +# this script's own, and the build passes only if the output holds a [Disassembly] section with an +# instruction line in it. Without a disassembler HotSpot prints raw hex instead and does not fail, +# so the exit status of that JVM would prove nothing. set -euo pipefail usage() { sed -n '/^# Builds hsdis/,/^[^#]/p' "$0" | sed '$d'; exit "${1:-2}"; } @@ -54,10 +56,10 @@ capstone_source="" while [ "$#" -gt 0 ]; do case "$1" in -h|--help) usage 0 ;; - --src) src="$2"; shift 2 ;; - --out) out="$2"; shift 2 ;; + --src) [ "$#" -ge 2 ] || usage; src="$2"; shift 2 ;; + --out) [ "$#" -ge 2 ] || usage; out="$2"; shift 2 ;; --capstone-source) capstone_source=yes; shift ;; - --check) check_only="$2"; shift 2 ;; + --check) [ "$#" -ge 2 ] || usage; check_only="$2"; shift 2 ;; *) usage ;; esac done diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java index bff4b97..424f8b2 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java @@ -78,8 +78,9 @@ static void core(double[] in, double[] out, boolean[] rare) { } /** - * Prints a start line with the species, warms each arm in turn and prints a done line. A - * species other than the one named fails, since the test would then check the wrong width. + * Prints a start line with the width and the species' bits, which {@link ExpAsmTest} compares + * with its own so that it never checks another width, warms each arm in turn and prints a done + * line. */ public static void main(String[] args) { System.out.println("asm-probe start: width " + WIDTH + ", " + S.vectorBitSize() + " bits"); diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java index 52da313..6ff6be3 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -38,9 +38,9 @@ * Vector API's Java fallback. Its width and FMA rules are asserted. The width is the child's * species, so the preferred species at 128 bits ({@code -XX:MaxVectorSize=16}) is treated alike. * - *

Skipped, with the reason, on a host that is not Linux on x86-64, when no hsdis is found ({@link - * AsmCheck#findHsdis}), and when one is found but HotSpot printed no disassembly with it; with - * {@code VFDLIBM_ASM_REQUIRED=true}, as CI's x86 rows set, the last two fail instead. + *

Skipped, with the reason, on a host that is not Linux on x86-64, when no hsdis is found + * ({@link AsmCheck#findHsdis}), and when one is found but HotSpot printed no disassembly with it; + * with {@code VFDLIBM_ASM_REQUIRED=true}, as CI's x86 rows set, the last two fail instead. */ class ExpAsmTest { From 25bdd8eb523114bce9b2a96c6181da96e7fe88a6 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 21:56:53 +0100 Subject: [PATCH 4/9] [VFDLIBM-139] Address review: build in a directory of the script's own, key the cache on the image, skip on a JDK's own hsdis Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 5 +++-- AGENTS.md | 10 +++++----- SKILLS.md | 17 +++++++++-------- dev/hsdis-build.sh | 9 ++++++--- .../io/github/vecbricks/vfdlibm/AsmCheck.java | 15 +++++++++++++++ .../io/github/vecbricks/vfdlibm/ExpAsmTest.java | 5 +++++ 6 files changed, 43 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af09e89..361f025 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,7 +74,8 @@ jobs: # hsdis, which dev/hsdis-build.sh builds into target/hsdis from two pinned files of the JDK's # source and a pinned Capstone 5; it is a tool, never committed or shipped. The runner's # own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. The build is - # cached on the script, which pins every source, so a run fetches nothing once it is; a + # cached on the script, which pins every source, and the runner image, so a run fetches + # nothing once it is; a # cached one is still checked to load, and rebuilt if it does not. On the x86 rows # VFDLIBM_ASM_REQUIRED turns the check's skip for a missing or unloaded hsdis into a # failure, so a green row has read the code. The Arm row skips it: its rules are x86's. @@ -84,7 +85,7 @@ jobs: uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: target/hsdis - key: hsdis-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('dev/hsdis-build.sh') }} + key: hsdis-${{ runner.os }}-${{ runner.arch }}-${{ env.ImageVersion }}-${{ hashFiles('dev/hsdis-build.sh') }} - name: Build hsdis for the assembly check if: matrix.asm env: diff --git a/AGENTS.md b/AGENTS.md index 8bb1c7a..8684603 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,12 +52,12 @@ vfdlibm ports fdlibm's double functions to the Java Vector API, each lane bit-id `PairBits` for two arguments), `Inputs` makes the inputs, `VectorWidth` runs a test at 128, 256 and 512 bits and the preferred species, and `PlantedFaultTest` requires each fault planted through `Faults` (in the main sources) to be caught by its check. `HarnessSelfTest` tests them. -- The assembly check: `ExpAsmTest` reads the C2 code of exp's arms through hsdis and asserts - the width, no fused multiply-add and no call but uncommon traps and the entry barrier +- The assembly check: `ExpAsmTest` reads the C2 code of exp's arms through hsdis and asserts the + width, no fused multiply-add and no call but uncommon traps and the entry barrier (`AsmCheckSelfTest` shows each rule failing). `dev/hsdis-build.sh` builds hsdis into - `target/hsdis`; it is OpenJDK's GPL source compiled as a tool, never committed or shipped. - Without it the check skips and says why; CI's x86 rows build it and set `VFDLIBM_ASM_REQUIRED=true`, so there a skip fails. - See `SKILLS.md`, "The assembly check". + `target/hsdis`; it is OpenJDK's GPL source compiled as a tool, never committed or shipped. Without + it the check skips and says why; CI's x86 rows build it and set `VFDLIBM_ASM_REQUIRED=true`, so + there a skip fails. See `SKILLS.md`, "The assembly check". - A width wider than the host's vectors is skipped. To see an AVX2 host's skips on an AVX-512 one: `mvn -B test -Dvfdlibm.test.jvmArgs=-XX:MaxVectorSize=32`. That keeps AVX-512's instructions at 256 bits, though: to make C2 compile as on an AVX2 host such as the EPYC diff --git a/SKILLS.md b/SKILLS.md index 9a2c94b..455b7ee 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -267,18 +267,19 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In - **hsdis needs Capstone 5.** `dev/hsdis-build.sh` compiles the JDK's `src/utils/hsdis/capstone/hsdis-capstone.c` and `hsdis.h` (jdk-25-ga, fetched alone, SHA-256 pinned, compiled and never read) against Capstone. Ubuntu 24.04's Capstone 4.0.2, GitHub's - ubuntu-latest, printed exp's 256-bit AVX-512 bodies with 19 to 43 undecoded `.byte` lines - each, an EVEX prefix it did not know followed by garbage with a `call` in it (read in an - ubuntu:24.04 container on the laptop). So the script uses the system's Capstone only at 5 and - otherwise builds the pinned 5.0.7 from source with cmake; in that container the census then - matched the laptop's to the instruction; and the check fails on - any `.byte` or `(bad)`. + ubuntu-latest, printed exp's 256-bit AVX-512 bodies with 19 to 43 undecoded `.byte` lines each, an + EVEX prefix it did not know followed by garbage with a `call` in it (read in an ubuntu:24.04 + container on the laptop). So the script uses the system's Capstone only at 5 and otherwise builds + the pinned 5.0.7 from source with cmake; in that container the census then matched the laptop's to + the instruction; and the check fails on any `.byte` or `(bad)`. - **Skips say which.** Not Linux on x86-64; hsdis not found (the script's `target/hsdis`, which `mvn clean` deletes, or `$VFDLIBM_HSDIS_DIR`; a binutils hsdis such as `bench/asm`'s prints another format, which the rules were not written for); or found but not loaded, decided by the output holding no `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, - which it printed both with no library and with a file that was none. CI's x86 rows build hsdis and - set `VFDLIBM_ASM_REQUIRED=true`, which makes the last two fail instead; the Arm row skips. + which it printed both with no library and with a file that was none. An hsdis in the JDK's own + `lib` would be loaded first, so the check skips (fails, required) when one is there. CI's x86 rows + build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes the last two fail instead; the Arm + row skips. **The census of exp's arms, 22 November 2026, on the laptop** (AMD Ryzen AI 9 HX PRO 370, JDK 25.0.5.1, hsdis on Capstone 5.0.7). Not a headline and no timing: counts of instructions only, one diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh index 76d0862..05aa2e8 100755 --- a/dev/hsdis-build.sh +++ b/dev/hsdis-build.sh @@ -27,7 +27,7 @@ # capstone.h says 5 (apt install libcapstone-dev, Ubuntu 25.04 and later), and the build takes gcc # only; 6 renamed the Arm architecture this script names. Otherwise, or with --capstone-source, # Capstone's pinned release is fetched, checked against its SHA-256 and built with cmake under -# target/hsdis/capstone, for x86 and Arm only, and linked in statically. Version 4 will not do: +# target/hsdis/.hsdis-build, for x86 and Arm only, and linked in statically. Version 4 will not do: # Ubuntu 24.04's 4.0.2, which GitHub's ubuntu-latest has, printed an AVX-512 body of exp at 256 bits # with ".byte 0x62" and garbage after it, a "call" among the garbage (SKILLS.md, "The assembly # check"). @@ -117,6 +117,9 @@ command -v gcc > /dev/null || { echo "hsdis-build: gcc not found" >&2; exit 1; } [ -f "$java_home/include/jni.h" ] \ || { echo "hsdis-build: no jni.h under $java_home/include" >&2; exit 1; } mkdir -p "$out" +# Sources and builds go to a directory of the script's own, the only one it deletes, so --out can +# name any directory. +work="$out/.hsdis-build" # The system's Capstone if it is 5, else the pinned release built here. system_major=$(sed -n 's/^#define CS_API_MAJOR \([0-9]*\).*/\1/p' \ @@ -128,7 +131,7 @@ if [ -z "$capstone_source" ] && [ "${system_major:-0}" = 5 ]; then else echo "building Capstone $capstone (the system's: ${system_major:-none})" command -v cmake > /dev/null || { echo "hsdis-build: cmake not found" >&2; exit 1; } - cs="$out/capstone" + cs="$work/capstone" rm -rf "$cs" mkdir -p "$cs" curl -fsSL --retry 3 -o "$cs/capstone.tar.gz" \ @@ -147,7 +150,7 @@ else cs_link=("$cs/build/libcapstone.a") fi -hsdis="$out/src" +hsdis="$work/src" rm -rf "$hsdis" mkdir -p "$hsdis/capstone" if [ -n "$src" ]; then diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java index 898f02d..6c4fc9e 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java @@ -120,6 +120,21 @@ static Hsdis findHsdis(String env, String name, List defaults) { + " (build it with dev/hsdis-build.sh, or set " + HSDIS_DIR_ENV + ")"); } + /** + * An hsdis in the running JDK's own library directories, or null: HotSpot loads one there before + * it looks on {@code LD_LIBRARY_PATH}, so the probe would read that one, not the one found. + */ + static String hsdisInJdk() { + Path lib = Path.of(System.getProperty("java.home"), "lib"); + for (Path dir : List.of(lib, lib.resolve("server"))) { + Path file = dir.resolve(libraryName()); + if (Files.exists(file)) { + return file.toString(); + } + } + return null; + } + /** Whether {@link #REQUIRED_ENV} turns a skip into a failure. */ static boolean required() { return "true".equals(System.getenv(REQUIRED_ENV)); diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java index 6ff6be3..e609ab3 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -101,6 +101,11 @@ static String probe(VectorWidth width) throws IOException, InterruptedException if (!hsdis.found()) { skipOrFail(hsdis.why()); } + String inJdk = AsmCheck.hsdisInJdk(); + if (inJdk != null) { + skipOrFail("the JDK has an hsdis of its own, " + inJdk + ", which HotSpot loads before " + + hsdis.dir() + "'s; the rules read Capstone's output only"); + } String output = AsmCheck.runProbe(ExpAsmProbe.class, hsdis.dir(), List.of("-Dvfdlibm.asm.width=" + width.name())); if (!AsmCheck.disassembled(output)) { From 4a054b15792dfd54b259e80103e5038d43496b27 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 22:02:30 +0100 Subject: [PATCH 5/9] [VFDLIBM-139] Address review: key the hsdis cache on the image a step reads, refuse a JDK's own hsdis in the script Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 18 ++++++++++++------ AGENTS.md | 4 ++-- SKILLS.md | 2 +- dev/hsdis-build.sh | 8 ++++++++ .../github/vecbricks/vfdlibm/ExpAsmTest.java | 5 +++-- 5 files changed, 26 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 361f025..7bdcf51 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,18 +74,24 @@ jobs: # hsdis, which dev/hsdis-build.sh builds into target/hsdis from two pinned files of the JDK's # source and a pinned Capstone 5; it is a tool, never committed or shipped. The runner's # own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. The build is - # cached on the script, which pins every source, and the runner image, so a run fetches - # nothing once it is; a - # cached one is still checked to load, and rebuilt if it does not. On the x86 rows - # VFDLIBM_ASM_REQUIRED turns the check's skip for a missing or unloaded hsdis into a - # failure, so a green row has read the code. The Arm row skips it: its rules are x86's. + # cached on the runner image (its ImageVersion, which only a step can read) and the script, + # which pins every source, so a run fetches nothing once it is; a cached one is still + # checked to load, and rebuilt if it does not. On the x86 rows VFDLIBM_ASM_REQUIRED turns + # the check's skip for a missing, shadowed or unloaded hsdis into a failure, so a green row + # has read the code. The Arm row skips it: its rules are x86's. + - name: Read the runner image + if: matrix.asm + id: image + run: echo "version=${ImageVersion:-unknown}" >> "$GITHUB_OUTPUT" - name: Cache hsdis if: matrix.asm id: hsdis uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: target/hsdis - key: hsdis-${{ runner.os }}-${{ runner.arch }}-${{ env.ImageVersion }}-${{ hashFiles('dev/hsdis-build.sh') }} + key: >- + hsdis-${{ runner.os }}-${{ runner.arch }}-${{ steps.image.outputs.version }}-${{ + hashFiles('dev/hsdis-build.sh') }} - name: Build hsdis for the assembly check if: matrix.asm env: diff --git a/AGENTS.md b/AGENTS.md index 8684603..9947d0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,8 +53,8 @@ vfdlibm ports fdlibm's double functions to the Java Vector API, each lane bit-id and 512 bits and the preferred species, and `PlantedFaultTest` requires each fault planted through `Faults` (in the main sources) to be caught by its check. `HarnessSelfTest` tests them. - The assembly check: `ExpAsmTest` reads the C2 code of exp's arms through hsdis and asserts the - width, no fused multiply-add and no call but uncommon traps and the entry barrier - (`AsmCheckSelfTest` shows each rule failing). `dev/hsdis-build.sh` builds hsdis into + width, no fused multiply-add and, from 256 bits up, no call but uncommon traps and the entry + barrier (`AsmCheckSelfTest` shows each rule failing). `dev/hsdis-build.sh` builds hsdis into `target/hsdis`; it is OpenJDK's GPL source compiled as a tool, never committed or shipped. Without it the check skips and says why; CI's x86 rows build it and set `VFDLIBM_ASM_REQUIRED=true`, so there a skip fails. See `SKILLS.md`, "The assembly check". diff --git a/SKILLS.md b/SKILLS.md index 455b7ee..f8a8d06 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -278,7 +278,7 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In holding no `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, which it printed both with no library and with a file that was none. An hsdis in the JDK's own `lib` would be loaded first, so the check skips (fails, required) when one is there. CI's x86 rows - build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes the last two fail instead; the Arm + build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes the last three fail instead; the Arm row skips. **The census of exp's arms, 22 November 2026, on the laptop** (AMD Ryzen AI 9 HX PRO 370, JDK diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh index 05aa2e8..b77d574 100755 --- a/dev/hsdis-build.sh +++ b/dev/hsdis-build.sh @@ -78,6 +78,14 @@ check_loads() { echo "hsdis-build: no hsdis-$arch.so in $dir" >&2 return 1 fi + # HotSpot loads an hsdis in the JDK's own lib before LD_LIBRARY_PATH's; the check would read it. + local own + for own in "$java_home/lib/hsdis-$arch.so" "$java_home/lib/server/hsdis-$arch.so"; do + if [ -e "$own" ]; then + echo "hsdis-build: the JDK has its own $own, which HotSpot loads instead of $dir's" >&2 + return 1 + fi + done work=$(mktemp -d) cat > "$work/HsdisCheck.java" << 'EOF' public class HsdisCheck { diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java index e609ab3..96e12d1 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -39,8 +39,9 @@ * species, so the preferred species at 128 bits ({@code -XX:MaxVectorSize=16}) is treated alike. * *

Skipped, with the reason, on a host that is not Linux on x86-64, when no hsdis is found - * ({@link AsmCheck#findHsdis}), and when one is found but HotSpot printed no disassembly with it; - * with {@code VFDLIBM_ASM_REQUIRED=true}, as CI's x86 rows set, the last two fail instead. + * ({@link AsmCheck#findHsdis}), when the JDK has one of its own that HotSpot would load first, and + * when one is found but HotSpot printed no disassembly with it; with {@code + * VFDLIBM_ASM_REQUIRED=true}, as CI's x86 rows set, the last three fail instead. */ class ExpAsmTest { From d63cd8328691363c31668be909fc14ffdf4b0169 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 22:10:50 +0100 Subject: [PATCH 6/9] [VFDLIBM-139] Address review: report unread code lines, refuse libhsdis in the JDK too, name a missing JDK Generated-by: Claude Code (Opus 5.5) --- dev/hsdis-build.sh | 5 ++-- .../io/github/vecbricks/vfdlibm/AsmCheck.java | 27 ++++++++++++++----- .../vecbricks/vfdlibm/AsmCheckSelfTest.java | 5 ++++ .../github/vecbricks/vfdlibm/ExpAsmTest.java | 4 ++- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh index b77d574..f06a3cf 100755 --- a/dev/hsdis-build.sh +++ b/dev/hsdis-build.sh @@ -69,7 +69,8 @@ case "$(uname -m)" in aarch64) arch=aarch64; cs_arch=CS_ARCH_ARM64; cs_mode=CS_MODE_ARM ;; *) echo "hsdis-build: unsupported architecture $(uname -m)" >&2; exit 1 ;; esac -java_home="${JAVA_HOME:-$(dirname "$(dirname "$(readlink -f "$(command -v java)")")")}" +java_home="${JAVA_HOME:-$(dirname "$(dirname "$(readlink -f "$(command -v java || true)")")")}" +[ -x "$java_home/bin/java" ] || { echo "hsdis-build: no JDK found (set JAVA_HOME)" >&2; exit 1; } # Passes when a JVM given $1 on LD_LIBRARY_PATH prints real instructions for a compiled method. check_loads() { @@ -80,7 +81,7 @@ check_loads() { fi # HotSpot loads an hsdis in the JDK's own lib before LD_LIBRARY_PATH's; the check would read it. local own - for own in "$java_home/lib/hsdis-$arch.so" "$java_home/lib/server/hsdis-$arch.so"; do + for own in "$java_home"/lib/{,server/}{,lib}hsdis-"$arch".so; do if [ -e "$own" ]; then echo "hsdis-build: the JDK has its own $own, which HotSpot loads instead of $dir's" >&2 return 1 diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java index 6c4fc9e..a6ebcdc 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java @@ -127,9 +127,11 @@ static Hsdis findHsdis(String env, String name, List defaults) { static String hsdisInJdk() { Path lib = Path.of(System.getProperty("java.home"), "lib"); for (Path dir : List.of(lib, lib.resolve("server"))) { - Path file = dir.resolve(libraryName()); - if (Files.exists(file)) { - return file.toString(); + for (String name : List.of(libraryName(), "lib" + libraryName())) { + Path file = dir.resolve(name); + if (Files.exists(file)) { + return file.toString(); + } } } return null; @@ -217,8 +219,11 @@ public String toString() { } } - /** A method's C2 code from its entry point to its stubs. */ - record Body(String method, List code) {} + /** + * A method's C2 code from its entry point to its stubs, and the lines in that range that were + * neither an instruction, a comment HotSpot attaches to one, a {@code #} header line nor blank. + */ + record Body(String method, List code, List unread) {} // A mnemonic may be a directive (".byte") or "(bad)": what a disassembler prints for bytes it // does not decode, which undecodedViolations must see rather than the parser drop. @@ -275,6 +280,7 @@ static Optional lastC2(String output, String method) { return Optional.empty(); } List code = new ArrayList<>(); + List unread = new ArrayList<>(); boolean disassembly = false; boolean inCode = false; for (int i = start + 1; i < lines.length; i++) { @@ -301,11 +307,13 @@ static Optional lastC2(String output, String method) { Instruction last = code.remove(code.size() - 1); code.add(new Instruction(last.address(), last.mnemonic(), last.operands(), last.notes() + " ;" + n.group(1).trim())); + } else if (!line.isBlank() && !line.trim().startsWith("#") && !isEntry(line)) { + unread.add(line); } } } } - return disassembly && !code.isEmpty() ? Optional.of(new Body(method, code)) : Optional.empty(); + return disassembly && !code.isEmpty() ? Optional.of(new Body(method, code, unread)) : Optional.empty(); } // --------------------------------------------------------------------------------------------- @@ -373,8 +381,13 @@ static List callViolations(Body body) { * the garbage after it. */ static List undecodedViolations(Body body) { - return matching(body, insn -> insn.mnemonic().startsWith(".") + List violations = matching(body, insn -> insn.mnemonic().startsWith(".") || insn.mnemonic().equals("(bad)"), "was not decoded (hsdis's Capstone is older than 5?)"); + // A line in the code that the parser could not read could hide a call or an FMA. + for (String line : body.unread()) { + violations.add(body.method() + ": a line in its code was not read: " + line.trim()); + } + return violations; } /** Every instruction whose inlined frames name StrictMath or FdLibm. */ diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java index 4bcfeb9..712acc0 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheckSelfTest.java @@ -194,6 +194,11 @@ void undecodedBytesFail() { AsmCheck.Body body = body(nmethod(code)); assertEquals(2, AsmCheck.undecodedViolations(body).size(), body.code().toString()); assertEquals(List.of(), AsmCheck.undecodedViolations(body(nmethod(clean512())))); + // a line the parser does not read (here a mnemonic in capitals) is reported, not dropped + String odd = clean512() + " 0x00007ac3981f8a50: VFMADD231PD\t\tzmm0, zmm1, zmm2\n"; + List violations = AsmCheck.undecodedViolations(body(nmethod(odd))); + assertEquals(1, violations.size(), violations.toString()); + assertTrue(violations.get(0).contains("not read"), violations.toString()); } /** HotSpot's output when no hsdis is loaded: the same nmethod as hex words under MachCode. */ diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java index 96e12d1..6fa2612 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -68,7 +68,9 @@ void eachArmIsVectorAtItsWidthWithNoFmaAndNoCall(VectorWidth width) throws Excep for (String arm : ARMS) { Optional body = AsmCheck.lastC2(output, PROBE + "::" + arm); if (body.isEmpty()) { - fail("no standard C2 compile of " + arm + " at " + width + "; the probe's output ends:\n" + fail("no standard C2 compile of " + arm + " at " + width + " (this JVM's options, " + + "which the probe got too: " + java.lang.management.ManagementFactory + .getRuntimeMXBean().getInputArguments() + "); the probe's output ends:\n" + AsmCheck.tail(output, 40)); } System.out.println("| exp | " + width + " | " + bits + " | " + arm + " | " From 797e1ef94e14810af441109987d3a762c1d45941 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 22:11:39 +0100 Subject: [PATCH 7/9] [VFDLIBM-139] Wrap a long line Generated-by: Claude Code (Opus 5.5) --- src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java index a6ebcdc..75722f0 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java @@ -313,7 +313,9 @@ static Optional lastC2(String output, String method) { } } } - return disassembly && !code.isEmpty() ? Optional.of(new Body(method, code, unread)) : Optional.empty(); + return disassembly && !code.isEmpty() + ? Optional.of(new Body(method, code, unread)) + : Optional.empty(); } // --------------------------------------------------------------------------------------------- From c8654cf4b5cc7380c8e9dc86ffc2fd83f2a93380 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 22:25:03 +0100 Subject: [PATCH 8/9] [VFDLIBM-139] Address review: read the arms by reflection, say the C1 dump is not read, cache the library alone Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 2 ++ SKILLS.md | 24 ++++++++++--------- dev/hsdis-build.sh | 3 ++- .../github/vecbricks/vfdlibm/ExpAsmProbe.java | 4 +++- .../github/vecbricks/vfdlibm/ExpAsmTest.java | 12 ++++++---- 5 files changed, 28 insertions(+), 17 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7bdcf51..829990b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,6 +102,8 @@ jobs: else dev/hsdis-build.sh fi + # Only the library is cached, not the fetched sources and Capstone's build. + rm -rf target/hsdis/.hsdis-build - name: Build and test env: VFDLIBM_ASM_REQUIRED: ${{ matrix.asm }} diff --git a/SKILLS.md b/SKILLS.md index f8a8d06..c9b3a5d 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -245,9 +245,11 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In (Varka: a register-allocation roll moves them with nothing wrong). - **Common data makes the call rule exact.** On `[-20, 20]` no lane is rare, so C2 compiles the per-lane finish as an uncommon trap, a deoptimizing exit the common path never takes; any other - call anywhere in the method fails. The same data keep `StrictMath`'s code out of the dump (no - rare lane, no call to compile), which the licence rule needs; the last rule is a backstop, since - HotSpot names inlined frames only at calls, traps and safepoints. + call anywhere in the method fails. The same data keep `StrictMath`'s code out of the C2 body + that is read (no rare lane, no call to compile), which the licence rule needs; the last rule is a + backstop, since HotSpot names inlined frames only at calls, traps and safepoints. The output + also holds each loop's C1 compile, which is not read: it keeps the finish, and with it a call to + `StrictMath.exp`, a call and not that method's code. - **At 128 bits on x86 the call rule is not asserted.** Every arm calls the Vector API's Java fallback, 60 to 132 calls per method (the census below), as "At two 64-bit lanes x86 C2 lowers no mask" predicts. Width and FMA are asserted there; the width is the child's species, so the @@ -272,14 +274,14 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In container on the laptop). So the script uses the system's Capstone only at 5 and otherwise builds the pinned 5.0.7 from source with cmake; in that container the census then matched the laptop's to the instruction; and the check fails on any `.byte` or `(bad)`. -- **Skips say which.** Not Linux on x86-64; hsdis not found (the script's `target/hsdis`, which - `mvn clean` deletes, or `$VFDLIBM_HSDIS_DIR`; a binutils hsdis such as `bench/asm`'s prints another - format, which the rules were not written for); or found but not loaded, decided by the output - holding no `[Disassembly]` instruction line, not by HotSpot's `Loading hsdis library failed`, - which it printed both with no library and with a file that was none. An hsdis in the JDK's own - `lib` would be loaded first, so the check skips (fails, required) when one is there. CI's x86 rows - build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes the last three fail instead; the Arm - row skips. +- **Skips say which.** Not Linux on x86-64 (a skip even when required); hsdis not found (the + script's `target/hsdis`, which `mvn clean` deletes, or `$VFDLIBM_HSDIS_DIR`; a binutils hsdis such + as `bench/asm`'s prints another format, which the rules were not written for); or found but not + loaded, decided by the output holding no `[Disassembly]` instruction line, not by HotSpot's + `Loading hsdis library failed`, which it printed both with no library and with a file that was + none. An hsdis in the JDK's own `lib` would be loaded first, so the check skips (fails, required) + when one is there. CI's x86 rows build hsdis and set `VFDLIBM_ASM_REQUIRED=true`, which makes the + last three fail instead; the Arm row skips. **The census of exp's arms, 22 November 2026, on the laptop** (AMD Ryzen AI 9 HX PRO 370, JDK 25.0.5.1, hsdis on Capstone 5.0.7). Not a headline and no timing: counts of instructions only, one diff --git a/dev/hsdis-build.sh b/dev/hsdis-build.sh index f06a3cf..2548fa4 100755 --- a/dev/hsdis-build.sh +++ b/dev/hsdis-build.sh @@ -105,7 +105,8 @@ EOF # An instruction line inside [Disassembly]: an address, a tab-separated mnemonic that a hex # word cannot be (HotSpot's raw dump also has the 0x

: shape). if awk '/^\[Disassembly\]/ { inside = 1 } /^\[\/Disassembly\]/ { inside = 0 } - inside && /^ *0x[0-9a-f]+: +(push|pushq|sub|subq|mov|movl|movq|ret|retq|stp|ldr|add)[ \t]/ { found = 1 } + inside && /^ *0x[0-9a-f]+: +(push|pushq|sub|subq|mov|movl|movq)[ \t]/ { found = 1 } + inside && /^ *0x[0-9a-f]+: +(ret|retq|stp|ldr|add)[ \t]/ { found = 1 } END { exit found ? 0 : 1 }' "$work/out.txt"; then rm -rf "$work" return 0 diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java index 424f8b2..e92c345 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java @@ -21,7 +21,9 @@ *

One species per JVM, named by the {@link VectorWidth} in {@code -Dvfdlibm.asm.width} and read * into a {@code static final}, a constant to C2. The data are {@code ExpBenchmark}'s common inputs, * {@code [-20, 20]}, so no lane takes a rare path: the per-lane finish is compiled as an uncommon - * trap, and no {@code StrictMath} code is compiled into the loops (AGENTS.md, licence). + * trap, and no {@code StrictMath} code is compiled into the C2 loops (AGENTS.md, licence). The + * C1 compiles printed beside them keep the finish's calls to {@code StrictMath.exp} and are not + * read. Every static method but {@code main} is an arm, and {@link ExpAsmTest} checks each. */ final class ExpAsmProbe { diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java index 6fa2612..d28bbc6 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmTest.java @@ -47,11 +47,13 @@ class ExpAsmTest { private static final String PROBE = ExpAsmProbe.class.getName(); /** - * The probe's methods, one per arm. Named here, not read from the probe, whose initialization - * reads the child's width property. + * The probe's arms: its static methods but {@code main}, read by reflection, which does not run + * the probe's static initializer (it reads the child's width property). */ - static final List ARMS = - List.of("finish", "finishMasked", "blended", "blendedMasked", "core"); + static final List ARMS = java.util.Arrays.stream(ExpAsmProbe.class.getDeclaredMethods()) + .filter(m -> java.lang.reflect.Modifier.isStatic(m.getModifiers()) && !m.isSynthetic() + && !m.getName().equals("main")) + .map(java.lang.reflect.Method::getName).sorted().toList(); @ParameterizedTest @EnumSource(VectorWidth.class) @@ -60,6 +62,7 @@ void eachArmIsVectorAtItsWidthWithNoFmaAndNoCall(VectorWidth width) throws Excep String output = probe(width); assertTrue(output.contains("asm-probe start: width " + width + ", " + bits + " bits"), "the probe ran another species than " + width + " at " + bits + " bits"); + assertEquals(5, ARMS.size(), "the probe's arms: " + ARMS); boolean callsChecked = bits > 128; List violations = new ArrayList<>(); // The census, as Markdown rows: `grep '^| exp '` on the test's output gives SKILLS.md's table. @@ -96,6 +99,7 @@ void eachArmIsVectorAtItsWidthWithNoFmaAndNoCall(VectorWidth width) throws Excep * no hsdis that HotSpot loads. */ static String probe(VectorWidth width) throws IOException, InterruptedException { + // Not a failure even when required: the rules are x86's, and CI requires the x86 rows only. if (AsmCheck.libraryName() == null) { abort("the assembly check reads Linux x86-64 code only; this host is " + System.getProperty("os.name") + " " + System.getProperty("os.arch")); From 6ae7bf0abdd6b841335c559aeee8ee4ffe3b3025 Mon Sep 17 00:00:00 2001 From: Max Gekk Date: Sun, 22 Nov 2026 22:43:28 +0100 Subject: [PATCH 9/9] [VFDLIBM-139] Build hsdis on every CI run, no cache; skip leading notes; correct the C1 note Generated-by: Claude Code (Opus 5.5) --- .github/workflows/ci.yml | 38 ++++--------------- SKILLS.md | 4 +- .../io/github/vecbricks/vfdlibm/AsmCheck.java | 3 +- .../github/vecbricks/vfdlibm/ExpAsmProbe.java | 5 ++- 4 files changed, 14 insertions(+), 36 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 829990b..d72f31e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,39 +71,15 @@ jobs: restore-keys: | m2-${{ runner.os }}-${{ runner.arch }}-java25-build- # The assembly check (ExpAsmTest; SKILLS.md, "The assembly check") reads C2's code through - # hsdis, which dev/hsdis-build.sh builds into target/hsdis from two pinned files of the JDK's - # source and a pinned Capstone 5; it is a tool, never committed or shipped. The runner's - # own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds its own. The build is - # cached on the runner image (its ImageVersion, which only a step can read) and the script, - # which pins every source, so a run fetches nothing once it is; a cached one is still - # checked to load, and rebuilt if it does not. On the x86 rows VFDLIBM_ASM_REQUIRED turns - # the check's skip for a missing, shadowed or unloaded hsdis into a failure, so a green row - # has read the code. The Arm row skips it: its rules are x86's. - - name: Read the runner image - if: matrix.asm - id: image - run: echo "version=${ImageVersion:-unknown}" >> "$GITHUB_OUTPUT" - - name: Cache hsdis - if: matrix.asm - id: hsdis - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: target/hsdis - key: >- - hsdis-${{ runner.os }}-${{ runner.arch }}-${{ steps.image.outputs.version }}-${{ - hashFiles('dev/hsdis-build.sh') }} + # hsdis, which dev/hsdis-build.sh builds into target/hsdis on every run from two pinned + # files of the JDK's source and a pinned Capstone 5; it is a tool, never committed or + # shipped. The runner's own Capstone, 4.0.2, decodes no AVX-512 body, so the script builds + # its own. On the x86 rows VFDLIBM_ASM_REQUIRED turns the check's skip for a missing, + # shadowed or unloaded hsdis into a failure, so a green row has read the code. The Arm row + # skips it: its rules are x86's. - name: Build hsdis for the assembly check if: matrix.asm - env: - CACHED: ${{ steps.hsdis.outputs.cache-hit }} - run: | - if [ "$CACHED" = true ]; then - dev/hsdis-build.sh --check target/hsdis || dev/hsdis-build.sh - else - dev/hsdis-build.sh - fi - # Only the library is cached, not the fetched sources and Capstone's build. - rm -rf target/hsdis/.hsdis-build + run: dev/hsdis-build.sh - name: Build and test env: VFDLIBM_ASM_REQUIRED: ${{ matrix.asm }} diff --git a/SKILLS.md b/SKILLS.md index c9b3a5d..fd0e9c5 100644 --- a/SKILLS.md +++ b/SKILLS.md @@ -248,8 +248,8 @@ standard `C2-compiled nmethod` of each, from its entry point to its stubs, in In call anywhere in the method fails. The same data keep `StrictMath`'s code out of the C2 body that is read (no rare lane, no call to compile), which the licence rule needs; the last rule is a backstop, since HotSpot names inlined frames only at calls, traps and safepoints. The output - also holds each loop's C1 compile, which is not read: it keeps the finish, and with it a call to - `StrictMath.exp`, a call and not that method's code. + also holds each loop's C1 compile, which is not read: it keeps the finish, with `StrictMath.exp`'s + one-line wrapper inlined and a call into `FdLibm`, whose code is not in it. - **At 128 bits on x86 the call rule is not asserted.** Every arm calls the Vector API's Java fallback, 60 to 132 calls per method (the census below), as "At two 64-bit lanes x86 C2 lowers no mask" predicts. Width and FMA are asserted there; the width is the child's species, so the diff --git a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java index 75722f0..75d712e 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/AsmCheck.java @@ -307,7 +307,8 @@ static Optional lastC2(String output, String method) { Instruction last = code.remove(code.size() - 1); code.add(new Instruction(last.address(), last.mnemonic(), last.operands(), last.notes() + " ;" + n.group(1).trim())); - } else if (!line.isBlank() && !line.trim().startsWith("#") && !isEntry(line)) { + } else if (!n.matches() && !line.isBlank() && !line.trim().startsWith("#") + && !isEntry(line)) { unread.add(line); } } diff --git a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java index e92c345..7097390 100644 --- a/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java +++ b/src/test/java/io/github/vecbricks/vfdlibm/ExpAsmProbe.java @@ -22,8 +22,9 @@ * into a {@code static final}, a constant to C2. The data are {@code ExpBenchmark}'s common inputs, * {@code [-20, 20]}, so no lane takes a rare path: the per-lane finish is compiled as an uncommon * trap, and no {@code StrictMath} code is compiled into the C2 loops (AGENTS.md, licence). The - * C1 compiles printed beside them keep the finish's calls to {@code StrictMath.exp} and are not - * read. Every static method but {@code main} is an arm, and {@link ExpAsmTest} checks each. + * C1 compiles printed beside them keep the finish, with {@code StrictMath.exp}'s one-line wrapper + * inlined and a call into {@code FdLibm}, and are not read. Every static method but {@code main} + * is an arm, and {@link ExpAsmTest} checks each. */ final class ExpAsmProbe {