```python
#!/usr/bin/env python3
"""Check that MVE/CDE intrinsics assemble when their core register operands are
pinned to odd and even registers.
One file per wrapper is generated from gcc.target/arm/mve/intrinsics and a CDE
template. Each file is compiled,
assembled and disassembled to FILE.s, and failures are reported per insn
pattern that emitted an instruction
the assembler rejected. Exits non-zero if any file fails.
Usage: check-reg-pairs.py SRCDIR OUTDIR COMPILER [ARGS...]
SRCDIR root of the gcc source tree
OUTDIR where the files are written; compare toolchains with diff -r -x
'*.o' -x '*.log' -x '*.dp.s'
COMPILER compiler and arguments to build each file with. The MVE tests are only used
if -march contains "mve"
(the floating-point ones only if it contains "mve.fp"), and the CDE tests if
it contains "cde".
Set OBJDUMP to override the objdump found through COMPILER.
Example:
check-reg-pairs.py . /tmp/reg-pairs arm-none-eabi-gcc -mthumb
-march=armv8.1-m.main+mve.fp+fp.dp+cdecp0 -mfloat-abi=hard
"""
import concurrent.futures
import glob
import os
import re
import shutil
import subprocess
import sys
# r7 is the Thumb frame pointer and cannot be pinned when it is needed.
FP_REG = 7
MAX_REG = 12
# Even and odd bases pin every value to both register parities.
BASES = [b for b in range(10) if b != FP_REG]
# Number of core registers used by each pinned type; pointers use one.
TYPE_REGS = {t: 1 for t in ("int8_t", "uint8_t", "int16_t", "uint16_t", "int32_t", "uint32_t",
"int", "unsigned",
"unsigned int")}
TYPE_REGS.update({t: 2 for t in ("int64_t", "uint64_t", "long long", "unsigned long
long")})
FUNC_RE = re.compile(r"^(?P<ret>[A-Za-z_][\w ]*?\**)\n(?P<name>\w+)
\((?P<params>[^)]*)\)\n\{\n", re.MULTILINE)
# gcc.target/arm/acle/cde.c is macro-based, so the CDE tests use this instead.
CDE_SOURCE = """\
/* { dg-additional-options "-O2" } */
#include "arm_cde.h"
uint64_t
cx1d (void)
{
return __arm_cx1d (0, 33);
}
uint64_t
cx1da (uint64_t acc)
{
return __arm_cx1da (0, acc, 33);
}
uint64_t
cx2d (uint32_t n)
{
return __arm_cx2d (0, n, 33);
}
uint64_t
cx2da (uint64_t acc, uint32_t n)
{
return __arm_cx2da (0, acc, n, 33);
}
uint64_t
cx3d (uint32_t n, uint32_t m)
{
return __arm_cx3d (0, n, m, 33);
}
uint64_t
cx3da (uint64_t acc, uint32_t n, uint32_t m)
{
return __arm_cx3da (0, acc, n, m, 33);
}
"""
def nregs(ctype):
"""Return the number of core registers to pin CTYPE to, or 0."""
t = " ".join(ctype.split())
return 1 if t.endswith("*") else TYPE_REGS.get(t, 0)
def fit(reg, n):
"""Return the first register >= REG that can hold N consecutive registers
without using FP_REG or going beyond
MAX_REG, or None."""
if reg <= FP_REG < reg + n:
reg = FP_REG + 1
return reg if reg + n - 1 <= MAX_REG else None
def pin(ctype, var, value, reg):
return f' register {ctype} {var} __asm__ ("r{reg}") = {value};\n __asm__ volatile
("" : "+r" ({var}));\n'
def make_wrapper(m, base):
"""Return the name and source of a wrapper calling the function matched by
M with its arguments and result pinned
from register BASE, or None if nothing can be pinned."""
ret, name, params = m.group("ret", "name", "params")
body = ""
args = []
reg = base
if params.strip() not in ("", "void"):
for p in params.split(","):
pm = re.fullmatch(r"\s*(.*?[\s*])(\w+)\s*", p)
if not pm:
return None
ptype, pname = pm.group(1).strip(), pm.group(2)
n = nregs(ptype)
if n:
reg = fit(reg, n)
if reg is None:
return None
body += pin(ptype, f"{pname}_p", pname, reg)
pname += "_p"
reg += n
args.append(pname)
call = f"{name} ({', '.join(args)})"
n = nregs(ret)
rreg = fit(base, n) if n else None
if rreg is not None:
body += pin(ret, "res", call, rreg) + " return res;\n"
elif not body:
return None
else:
body += f" {'' if ret == 'void' else 'return '}{call};\n"
wname = f"{name}_r{base}"
return wname, f"{ret}\n{wname} ({params.strip() or
'void'})\n{{\n{body}}}\n"
def write_tests(outdir, stem, text):
"""Write one file per wrapper for the functions in TEXT, which are made always_inline,
and return the paths."""
wrappers = [w for m in FUNC_RE.finditer(text) for base in BASES if (w :=
make_wrapper(m, base))]
text = FUNC_RE.sub(lambda m: m.group(0) if m.group("name") == "main"
else "static inline __attribute__ ((always_inline))\n"
+ m.group(0), text)
paths = []
for wname, wsrc in wrappers:
paths.append(os.path.join(outdir, f"{stem}-{wname}.c"))
with open(paths[-1], "w") as f:
f.write(text + "\n" + wsrc)
return paths
def extra_options(text):
"""Return the C dg-options and dg-additional-options of a test, without
-save-temps, which would write to the
current directory."""
opts = []
for m in
re.finditer(r'dg-(?:additional-)?options\s+"([^"]*)"(?:\s*\{\s*target\s+([^\s}]+)\s*\})?',
text):
if m.group(2) in (None, "c"):
opts += [o for o in m.group(1).split() if o not in ("-save-temps",
"--save-temps")]
return opts
def find_objdump(command):
"""Return $OBJDUMP, the objdump COMMAND finds, or the one next to it."""
if os.environ.get("OBJDUMP"):
return os.environ["OBJDUMP"]
try:
prog = subprocess.run(command + ["-print-prog-name=objdump"],
capture_output=True, text=True).stdout.strip()
except OSError as e:
sys.exit(f"error: cannot run {command[0]}: {e.strerror}")
if not os.path.isabs(prog) and command[0].endswith("gcc"):
prog = shutil.which(command[0][:-3] + "objdump") or ""
if not prog:
sys.exit("error: cannot find objdump for the compiler; set OBJDUMP")
return prog
DP_RE = re.compile(r"@ \d+\t\[c=\d+ l=\d+\]\s+(\S+?)(?:/\d+)?\s*$")
GAS_ERROR_RE = re.compile(r"^.*?:(\d+): Error: (.*?)(?: -- `(\S+).*)?$",
re.MULTILINE)
CC_ERROR_RE = re.compile(r"^.*?: (?:error|internal compiler error): (.*)$",
re.MULTILINE)
def run(cmd, log):
res = subprocess.run(cmd, capture_output=True, text=True)
log.write(res.stdout + res.stderr)
return res
def compile_one(path, command, objdump):
"""Compile PATH with -dp, assemble it and disassemble the object. Return
a list of failure descriptions, each
naming the insn pattern that emitted a rejected instruction, or the compiler
error."""
with open(path) as f:
opts = extra_options(f.read())
base = os.path.splitext(path)[0]
with open(base + ".log", "w") as log:
res = run(command + opts + ["-S", "-dp", path, "-o", base + ".dp.s"],
log)
if res.returncode:
errs = CC_ERROR_RE.findall(res.stderr) or ["compilation failed"]
return ["compiler error: " + re.sub(r"'[^']*'", "'...'", e) for e
in errs]
res = run(command + opts + ["-c", base + ".dp.s", "-o", base + ".o"],
log)
if res.returncode:
with open(base + ".dp.s") as f:
lines = f.read().splitlines()
fails = []
for lineno, msg, insn in GAS_ERROR_RE.findall(res.stderr):
# -dp annotates the first line of each pattern's output.
pattern = next((m.group(1) for l in reversed(lines[:int(lineno)]) if (m
:= DP_RE.search(l))), "?")
fails.append(f"{pattern} ({insn}): {msg}")
return fails or ["assembly failed"]
res = subprocess.run([objdump, "-dr", "--no-addresses", base + ".o"],
capture_output=True, text=True)
with open(base + ".s", "w") as f:
f.writelines(l for l in res.stdout.splitlines(keepends=True) if "file
format" not in l)
return [] if res.returncode == 0 else ["objdump failed"]
def compile_all(paths, command):
objdump = find_objdump(command)
with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as pool:
results = list(pool.map(lambda p: compile_one(p, command, objdump),
paths))
# Map each failure to the intrinsics tests that hit it.
failures = {}
for path, fails in zip(paths, results):
for fail in fails:
failures.setdefault(fail,
set()).add(os.path.basename(path).rsplit("-", 1)[0])
nfailed = sum(1 for fails in results if fails)
if failures:
print("\nFailures (insn pattern (instruction): assembler error, or compiler
error):")
for fail in sorted(failures):
print(f" {fail}\n tests: {' '.join(sorted(failures[fail]))}")
print(f"\n{nfailed} of {len(paths)} files failed")
return 1 if nfailed else 0
def main():
if len(sys.argv) < 4:
sys.exit(__doc__)
srcdir, outdir, command = sys.argv[1], sys.argv[2], sys.argv[3:]
indir = os.path.join(srcdir, "gcc/testsuite/gcc.target/arm/mve/intrinsics")
if not os.path.isdir(indir):
sys.exit(f"error: {indir} not found")
march = next((a[len("-march="):] for a in reversed(command) if
a.startswith("-march=")), "")
mve = "mve" in march
mve_fp = "mve.fp" in march
cde = "cde" in march
if not mve and not cde:
sys.exit("error: -march enables neither MVE nor CDE")
os.makedirs(outdir, exist_ok=True)
paths = []
for path in sorted(glob.glob(os.path.join(indir, "*.c"))) if mve else []:
with open(path) as f:
text = f.read()
# Skip tests expected not to compile, and floating-point tests unless
MVE has floating point.
if "dg-error" in text or ("arm_v8_1m_mve_fp_ok" in text and not
mve_fp):
continue
paths += write_tests(outdir, os.path.basename(path)[:-2], text)
if cde:
paths += write_tests(outdir, "cde", CDE_SOURCE)
print(f"Generated {len(paths)} files in {outdir}")
return compile_all(paths, command)
if __name__ == "__main__":
sys.exit(main())
```
I've executed the above script using the following:
```bash
for opts in \
-mthumb\ -march=armv8.1-m.main{,+dsp}{,+pacbti}+cdecp0\
-mfloat-abi={soft,softfp} \
-mthumb\ -march=armv8.1-m.main{,+dsp}+{fp,fp.dp}{,+pacbti}+cdecp0\
-mfloat-abi={soft,softfp,hard} \
-mthumb\
-march=armv8.1-m.main+{mve{,+fp,+fp.dp},mve.fp{,+fp.dp}}{,+pacbti}{,+cdecp0}\
-mfloat-abi={softfp,hard} \
-mthumb\ -march=armv8-m.main{,+dsp}+cdecp0\ -mfloat-abi={soft,softfp} \
-mthumb\ -march=armv8-m.main{,+dsp}+{fp,fp.dp}+cdecp0\
-mfloat-abi={soft,softfp,hard}
do
echo "== $opts"
python3 check-reg-pairs.py /tmp/reg-pairs/src "/tmp/reg-pairs/out/${opts//
/_}" \
/tmp/reg-pairs/gcc/bin/arm-none-eabi-gcc $opts
done
```
--
https://forge.sourceware.org/gcc/gcc/pulls/266#issuecomment-8105