okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-3c 0c83610e5 into f-own-int805e11c3d

main
5.2 KiB108 linesraw
1#!/usr/bin/env python3
2"""Which code of a linked strata-vision (or strata-vision-own) holds instructions an older CPU lacks (RESULTS-OWN-3V.md PART H).
3
4The CPU tower compiles each kernel tier in a file of its own with that tier's flags and calls it only after a CPU check (cpu_caps.h); everything else
5must stay at the floor of the build.  An instruction-set flag on a file that uses the standard library also reaches its inline and template copies
6(weak / COMDAT symbols), and the linker may keep such a copy for the whole program, so the check looks at the LINKED binary, function by function:
7
8  floor none  (SSE4.2, Nehalem / Westmere): no VEX / EVEX instruction (no AVX of any kind), no BMI1/2, no MOVBE;
9  floor avx   (Sandy Bridge): AVX allowed; no AVX2 (256-bit integer ops, broadcasts / permutes / gathers of AVX2), no FMA, no F16C, no EVEX, no BMI;
10  floor avx_f16c (Ivy Bridge): as avx, F16C allowed.
11
12A function with such an instruction passes only if it is a LOCAL symbol of a kernel tier (the anonymous namespace `kn` of cpu_kernels_impl.h) or a tier's
13table getter (strata_vit::cpu_ops_<tier>), i.e. code reached only behind the CPU check.  Anything else is printed, weak / COMDAT copies marked.
14
15    python3 check_floor_isa.py <binary> --floor none|avx|avx_f16c        exit 0 clean, 1 a violation, 77 no objdump / nm
16Linux (GNU binutils) only.
17"""
18import argparse
19import re
20import shutil
21import subprocess
22import sys
23
24FMA = re.compile(r"^vf(n?m(add|sub)|maddsub|msubadd)")
25F16C = re.compile(r"^vcvt(ph2ps|ps2ph)")
26AVX2_ONLY = re.compile(r"^(vpbroadcast|vbroadcasti128|vperm2i128|vpermd|vpermq|vpermps|vpermpd|v(p)?gather|vinserti128|vextracti128|vpmaskmov|vps[lr]lv|vpsrav|vpblendd)")
27BMI = re.compile(r"^(andn|bextr|blsi|blsmsk|blsr|bzhi|mulx|pdep|pext|rorx|sarx|shlx|shrx|movbe)\b")
28AVX1_YMM_INT_OK = ("vptest", "vpermilps", "vpermilpd", "vperm2f128")      # AVX (1) instructions whose names start with "vp" and take ymm
29
30
31def bad_reason(mn, ops, floor):
32    if "zmm" in ops or re.search(r"%k[0-7]|\{%k", ops) or re.search(r"[xy]mm(1[6-9]|2\d|3[01])\b", ops):
33        return "AVX-512"
34    if BMI.match(mn):
35        return "BMI/MOVBE"
36    if floor == "none":
37        if mn.startswith("v") and mn not in ("verr", "verw"):
38            return "AVX"
39        return None
40    if FMA.match(mn):
41        return "FMA"
42    if F16C.match(mn) and floor != "avx_f16c":
43        return "F16C"
44    if AVX2_ONLY.match(mn):
45        return "AVX2"
46    if mn.startswith("vp") and "ymm" in ops and not mn.startswith(AVX1_YMM_INT_OK):
47        return "AVX2"
48    return None
49
50
51def main():
52    ap = argparse.ArgumentParser()
53    ap.add_argument("binary")
54    ap.add_argument("--floor", required=True, choices=["none", "avx", "avx_f16c"])
55    ap.add_argument("--show", type=int, default=3, help="instructions shown per function")
56    a = ap.parse_args()
57    if not shutil.which("objdump") or not shutil.which("nm"):
58        print("objdump / nm not found")
59        return 77
60    kind = {}
61    for line in subprocess.run(["nm", "--defined-only", a.binary], capture_output=True, text=True).stdout.splitlines():
62        p = line.split()
63        if len(p) >= 3:
64            kind[int(p[0], 16)] = p[1]
65    names = {}
66    for line in subprocess.run(["nm", "--defined-only", "-C", a.binary], capture_output=True, text=True).stdout.splitlines():
67        p = line.split(None, 2)
68        if len(p) == 3:
69            names.setdefault(int(p[0], 16), p[2])
70    proc = subprocess.Popen(["objdump", "-d", "-w", "--no-show-raw-insn", a.binary], stdout=subprocess.PIPE, text=True, bufsize=1 << 20)
71    head = re.compile(r"^([0-9a-f]+) <(.+)>:$")
72    ins = re.compile(r"^\s*[0-9a-f]+:\s+(\S+)\s*(.*)$")
73    cur, cur_addr, hits = None, 0, {}
74    for line in proc.stdout:
75        m = head.match(line)
76        if m:
77            cur_addr = int(m.group(1), 16)
78            cur = names.get(cur_addr, m.group(2))
79            continue
80        m = ins.match(line)
81        if not m or cur is None:
82            continue
83        mn, ops = m.group(1), m.group(2)
84        if mn in ("data16", "rex", "lock", "rep", "repz", "repnz", "notrack", "bnd") and ops:
85            mn, _, ops = ops.partition(" ")
86        r = bad_reason(mn, ops, a.floor)
87        if r:
88            h = hits.setdefault((cur_addr, cur), {"reasons": set(), "ex": []})
89            h["reasons"].add(r)
90            if len(h["ex"]) < a.show:
91                h["ex"].append(mn + " " + ops.strip())
92    proc.wait()
93    ok_tier, bad = [], []
94    for (addr, name), h in sorted(hits.items(), key=lambda x: x[0][1]):
95        k = kind.get(addr, "?")
96        local = k in ("t", "d", "b", "r")
97        tier = ("(anonymous namespace)::kn::" in name and local) or re.match(r"^strata_vit::cpu_ops_(sse41|avx|avx2|avx512)\(\)$", name)
98        (ok_tier if tier else bad).append((name, k, h))
99    print("floor %s: %d functions with instructions above the floor; %d are kernel-tier code behind the CPU check, %d are NOT" % (
100        a.floor, len(hits), len(ok_tier), len(bad)))
101    for name, k, h in bad:
102        weak = " WEAK/COMDAT" if k in ("W", "w", "V", "v", "u") else ""
103        print("  NOT GUARDED [%s]%s %s: %s | e.g. %s" % (k, weak, name[:200], ",".join(sorted(h["reasons"])), " ; ".join(h["ex"])))
104    return 1 if bad else 0
105
106
107if __name__ == "__main__":
108    sys.exit(main())